即使应用程序处于后台,服务也会被杀死

时间:2019-09-06 11:24:38

标签: java android service

我正在使用服务来执行某些任务,该任务仅在应用程序在后台运行时才能运行,而且该服务运行了一段时间,并在一段时间后被销毁。以前,这完全可以正常工作,但是不知道我在哪里做错了。

这是我的服务代码:

public class MyService extends Service {
    Context context;
    public static final String TAG = MyService.class.getSimpleName();

    public MyService(Context applicationContext) {
        super();
        context = applicationContext;
        Log.i("myservice", "here service created!");
    }

    public MyService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "[onCreateService]");
        super.onStartCommand(intent, flags, startId);
        // Code
        registerOverlayReceiver();
        context = this;
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterOverlayReceiver();
        Log.i("EXIT", "ondestroy!");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void unregisterOverlayReceiver() {
        if (myReceiver != null) {
            unregisterReceiver(myReceiver);
        }
    }

    private static final String ACTION_DEBUG = "abc.action.DEBUG";

    private void registerOverlayReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(ACTION_DEBUG);
        registerReceiver(myReceiver, filter);
    }

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "[onReceive]" + action);
            if (action.equals(Intent.ACTION_SCREEN_ON)) {
                showMyActivity();
            } else if (action.equals(ACTION_DEBUG)) {
                showMyActivity();
            }
        }
    };

    private void showMyActivity() {
        Intent intent = new Intent();
        intent.setClass(this, MyActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

}

我已经调试了,但同样也找不到问题所在。 任何遇到过这种情况的人都可以帮助我。

0 个答案:

没有答案