在android中,如何在活动退出时停止包含处理程序的子线程?

时间:2016-05-18 01:01:16

标签: android multithreading

示例:

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. 我在一个包含a的活动中启动一个消费子线程 处理程序更改ui,但当我退出活动时如何停止子线程?
  2. 当我按下后退键时,我希望子线程继续运行。但是当我重新进入活动并更改ui时,我应该如何跟踪进度?
  3. 线程?

1 个答案:

答案 0 :(得分:0)

之前我确实喜欢这样:

  1. 定义类扩展HashSet
  2. 运行
  3. 后,使用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); } } 或其他内容来保存每个帖子
  4. 中断HashSet中的所有线程
  5. 代码如下所示,希望对您有所帮助

    {{1}}