如何正确停止Android中的所有线程?

时间:2017-04-15 08:23:25

标签: java android multithreading

在下面的代码中,我维护“isFound”布尔变量来确定线程是否应该运行。但是,当我将“isFound”设置为true时。我的线程将再次运行一次。换句话说,它们将无法正常停止,这也会导致UI无法正确更新Textview。我想这是由于一些同步的问题,但我不知道如何处理它,我尝试使用同步块,但它仍然无法正常工作。

import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private ProgressBar progressBar;
    private TextView message;
    private TextView magicNumDisplay;
    private boolean isFound = false;
    private NotificationManager notificationManager;
    private Notification notifyDetail;

    private final Handler handler = new Handler(){
        public void handleMessage(Message msg) {

            if (isMagic(msg.what)) {
                isFound = true;
                progressBar.setVisibility(View.INVISIBLE);
                magicNumDisplay.setText("The magic number is " + msg.what);
                handler.removeMessages(0);
                message.setText("A magic number s found");
                Intent intent = new Intent("MAGIC_NUMBER");
                intent.putExtra("THREAD_NAME", msg.obj.toString());
                intent.putExtra("MAGIC_NUMBER", String.valueOf(msg.what));
                sendBroadcast(intent);

            } else {
                message.setText("Finding a magic number...");
            }

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        message = (TextView) findViewById(R.id.message);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        magicNumDisplay = (TextView) findViewById(R.id.magic_num_display);
        progressBar.setVisibility(View.VISIBLE);
        IntentFilter filter = new IntentFilter("MAGIC_NUMBER");
        BroadcastReceiver receiver =  new MagicNumberReceiver();
        registerReceiver(receiver, filter);

        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    }

    public void onStart(){
        super.onStart();
        Thread firstThread = new Thread(backgroundTask, "First");
        Thread secondThread = new Thread(backgroundTask, "Second");
        firstThread.start();
        secondThread.start();
    }

    public boolean isMagic(int num) {
        return (num % 7 == 0 && isLastDigitEqualTwo(num));
    }

    public boolean isLastDigitEqualTwo(int num) {
        String numString = String.valueOf(num);
        return Integer.parseInt(numString.substring(numString.length() - 1))==2;
    }

    Runnable backgroundTask = new Runnable() {
        @Override
        public void run() {

            try {

                while (!isFound) {
                    Thread.sleep(1000);
                    int number = (int) (Math.random() * 9999);
                    Message msg = handler.obtainMessage(number, Thread.currentThread().getName());
                    handler.sendMessage(msg);
                    Log.e(Thread.currentThread().getName(), "The number is :" + number);
                }
            } catch(InterruptedException e){
                    Log.e("Exception", e.getMessage());
                }

        }
    };
    public class MagicNumberReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context localContext, Intent callerIntent) {
            String threadName = callerIntent.getStringExtra("THREAD_NAME");
            String magicNum = callerIntent.getStringExtra("MAGIC_NUMBER");

            Log.e("Magic", "Thread name:"+threadName+" Magic Number:"+magicNum);

            int MAGIC_NUMBER_NOTIFICATION_ID=200;
            notifyDetail = new Notification.Builder(getApplicationContext())
                    .setContentTitle("Magic Number")
                    .setContentText("Thread Name: " + threadName + ".  Magic Number: " + magicNum+".")
                    .setSmallIcon(R.drawable.droid)
                    .setVibrate(new long[] {1000, 1000, 1000, 1000})
                    .setLights(Integer.MAX_VALUE,  500,  500)
                    .build();
            notificationManager.notify(MAGIC_NUMBER_NOTIFICATION_ID,notifyDetail);

        }
    }
}

0 个答案:

没有答案