为什么即使在Oreo中杀死了应用程序,后台服务仍在运行?

时间:2019-02-22 10:15:26

标签: android service

我正在从活动开始服务

 btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(MainActivity3.this, TestService.class);
            startService(i);
        }
    });

我正在运行每5秒运行一次的TimerTask

t= new Timer();

    tt = new TimerTask() {
        @Override
        public void run() {
            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Log.e("wake", "after sleep");

            Intent i = new Intent("receive");
            LocalBroadcastManager.getInstance(TestService.this).sendBroadcast(i);

        }
    };

    t.scheduleAtFixedRate(tt, 1000, 5000);

当我启动服务时,这是logcat

 E/onCreate: called
 E/onStartCommand: called
 E/wake: after sleep
 E/wake: after sleep

当我按下“后退”按钮关闭我的应用程序时,这就是日志

E/MainActivity3: onstop
E/MainActivity3: ondestroy
E/wake: after sleep

当我从最近的应用程序菜单中强制关闭我的应用程序时,这是日志猫

E/onCreate: called
E/onDestroy: called
E/wake: after sleep

据我了解,当在Android 8(Oreo)中关闭应用程序时,如果没有持久通知,则该服务不应在后台运行

这是我的服务课程

public class TestService extends Service {

Timer t;
TimerTask tt;

@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("onDestroy", "called");
}


@Override
public void onCreate() {
    super.onCreate();
    Log.e("onCreate", "called");

    t= new Timer();

    tt = new TimerTask() {
        @Override
        public void run() {
            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Log.e("wake", "after sleep");

            Intent i = new Intent("receive");

LocalBroadcastManager.getInstance(TestService.this).sendBroadcast(i);

        }
    };

    t.scheduleAtFixedRate(tt, 1000, 5000);

}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    Log.e("onBind", "called");
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e("onStartCommand", "called");
    return super.onStartCommand(intent, flags, startId);
}
}

0 个答案:

没有答案