编程语言
首页 > 编程语言> > java-Service中的处理程序和线程继续运行,而Service似乎已停止

java-Service中的处理程序和线程继续运行,而Service似乎已停止

作者:互联网

我有一个使用Handler和Thread每5秒运行一些代码的服务.当我调用stopSelf()时,该服务似乎已停止,因为从设备Setting->;应用->运行它并不在那里.
但是,尽管我已停止了该服务,但线程内的代码仍每5秒运行一次.即使服务已停止,为什么处理程序和线程仍然存在?服务停止后,如何停止处理程序和线程.

final Handler h = new Handler();
final int delay = 5000; // milliseconds

h.postDelayed(new Runnable() {
        public void run() {
            // do something
            final SharedPreferences sharedPref = getSharedPreferences(
                    getString(R.string.prefs), Context.MODE_PRIVATE);
            if (sharedPref != null) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // SOME CODE
                        Log.d("UPDATING"," something here");
                        isUpdated = updateToServer(data);
                        if(isUpdated) {
                            sharedPref.edit().putBoolean("updated",true).commit();
                            stopSelf();
                        }
                    }
                }).start();
            }
            h.postDelayed(this, delay);
        }
    }, delay);

解决方法:

您应该在发布Runnable之前验证isUpdated,如果isUpdated == true,则不要再次发布,代码如下:

final Handler h = new Handler();
final int delay = 5000; // milliseconds

h.postDelayed(new Runnable() {
        public void run() {
            // do something
            final SharedPreferences sharedPref = getSharedPreferences(
                    getString(R.string.prefs), Context.MODE_PRIVATE);
            if (sharedPref != null) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // SOME CODE
                        Log.d("UPDATING"," something here");
                        isUpdated = updateToServer(data);
                        if(isUpdated) {
                            sharedPref.edit().putBoolean("updated",true).commit();
                            stopSelf();
                        }
                    }
                }).start();
            }
            if(!isUpdated){
               h.postDelayed(this, delay);
            }

        }
    }, delay);

标签:android-handler,multithreading,android-service,java,android
来源: https://codeday.me/bug/20191120/2046262.html