1

example:

new Thread(){
        private Message message;

        public void run() {
            PackageManager packageManager = getPackageManager();
            List<PackageInfo> packages = packageManager.getInstalledPackages(0);


            progressBar1.setMax(packages.size());
            int progress = 0;



            for (PackageInfo packageInfo : packages) {
                ScanInfo scanInfo = new ScanInfo();
                String appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();
                String packageName = packageInfo.packageName;
                scanInfo.appName = appName;
                scanInfo.packageName = packageName;
                String sourceDir = packageInfo.applicationInfo.sourceDir;
                String md5 = MD5Utils.getFileMd5(sourceDir);
                String desc = AntivirusDao.checkFileVirus(md5);

                System.out.println("-------------------------");

                System.out.println(appName);

                System.out.println(md5);


                if(desc == null){
                    scanInfo.desc = false;
                }else{
                    scanInfo.desc = true;
                }
                progress++;
                progressBar1.setProgress(progress);
                message = Message.obtain();
                message.what = SCANNING;
                message.obj = scanInfo;
                handler.sendMessage(message);
            }
            message = Message.obtain();
            message.what = FINISHED;
            handler.sendMessage(message);
        };
    }.start();

  1. I start a consuming child thread in an activity that contains a handler to change ui, but when i exit the activity how do i stop the child thread?
  2. when i pressed the back key , i hope the child thread continue running.But how should i keep trace of the progress when i reenter the activity and change ui?

thread?

  • 1
    a search on SO or Google will give several answers. Here is one http://stackoverflow.com/questions/8505707/android-best-and-safe-way-to-stop-thread – pellucide May 18 '16 at 01:05

1 Answers1

0

I did like this before:

  1. define a class extend Thread
  2. use a HashSet or something else to hold every thread after it runs
  3. interrupt ALL Threads in the HashSet

codes are like this below, hope helpful

HashSet<MyThread> myThreads = new HashSet<>();

@Override
public void onDestroy() {
    super.onDestroy();
    if (myThreads.iterator().hasNext())
        myThreads.iterator().next().interrupt();
}

private void doSomething() {
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //doing some work
        }
    };
    MyThread thread = new MyThread(runnable);
    thread.run();
    myThreads.add(thread);
}

class MyThread extends Thread {
    public MyThread(Runnable runnable) {
        super(runnable);
    }
}
Wooby
  • 216
  • 2
  • 10