我想在我的应用关闭后立即启动一项服务

时间:2019-05-03 06:15:25

标签: android service worker

我能够(从最近的应用程序堆栈中)检测到应用程序终止,并且我试图以onActivityDestroyed方法启动服务,但该服务未启动。我还尝试了调用worker类来执行某些任务,但是即使这样也没有被调用。

我进入日志onActivityDestroyed方法,这意味着它在应用终止时被调用,但是我猜不到进一步的代码正在执行或不允许。

用于调用服务类意图的类代码。

public class AppKilledDetectService implements Application.ActivityLifecycleCallbacks {

    private static final String TAG = AppKilledDetectService.class.getSimpleName();
    private static AppKilledDetectService instance;
    private OneTimeWorkRequest uploadWorkRequest;

    public static AppKilledDetectService init(Application application) {
        if (instance == null) {
            instance = new AppKilledDetectService();
            application.registerActivityLifecycleCallbacks(instance);
        }
        return instance;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        uploadWorkRequest = new OneTimeWorkRequest.Builder(PostDataService.class)
                .build();
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {
        Log.e(TAG, "onActivityResumed");
    }

    @Override
    public void onActivityPaused(Activity activity) {
        Log.e(TAG, "onPause");
    }

    @Override
    public void onActivityStopped(Activity activity) {
        Log.e(TAG, "onActivityStopped");
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        Log.e(TAG, "onActivityDestroyed");

        // WorkManager.getInstance().enqueue(uploadWorkRequest);

        Intent i = new Intent(activity, PostDataService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            activity.startForegroundService(i);
        } else
            activity.startService(i);
    }
}

我已经尝试过服务,IntentService和worker类,什么也没得到调用。

您需要在上面的类中确切地看到这部分代码,谢谢!

@Override
public void onActivityDestroyed(Activity activity) {
    Log.e(TAG, "onActivityDestroyed");

    // WorkManager.getInstance().enqueue(uploadWorkRequest);

    Intent i = new Intent(activity, PostDataService.class);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        activity.startForegroundService(i);
    else
        activity.startService(i);
}

0 个答案:

没有答案