【发布时间】:2017-12-14 01:21:48
【问题描述】:
我认为我根本不清楚,我确实希望服务能够持续存在,即使主要活动被用户操作或 android 系统破坏,它也做得很好,但是当应用程序在某个点重新打开时,我会想检查是否存在 bg 活动并使用操作按钮将其停止,提前 THX。
我启动了一个后台服务,在我的MainActivity 我可以停止它并重新运行它,当应用程序从正在运行的应用程序列表中关闭时,该服务仍然存在,问题是当我重新启动关闭的应用程序并尝试停止带有按钮的服务我的应用程序崩溃了,因为它显然试图停止不再有引用的服务。
private void startBg(){
if (!hasPermissions() || mScanning) {
return;
}
clearLogs();
BgServiceIntent = new Intent(MainActivity.this, BgScanService.class);
startService(BgServiceIntent);
}
private void stopBg(){
stopService(BgServiceIntent);
}
重新打开应用程序后调用stopBg() 失败,因为BgServiceIntent 不再指向此服务,因此我得到了这个:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: mobile.link.imbera.apsys.imberalink, PID: 20104
java.lang.NullPointerException
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1568)
at android.app.ContextImpl.stopServiceCommon(ContextImpl.java:1628)
at android.app.ContextImpl.stopService(ContextImpl.java:1589)
at android.content.ContextWrapper.stopService(ContextWrapper.java:499)
at mobile.link.imbera.apsys.imberalink.MainActivity.stopBg(MainActivity.java:180)
at mobile.link.imbera.apsys.imberalink.MainActivity.lambda$onCreate$1$MainActivity(MainActivity.java:124)
at mobile.link.imbera.apsys.imberalink.MainActivity$$Lambda$1.onClick(Unknown Source)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
【问题讨论】:
-
使用MainActivity的@Override protected void onResume()和@Override protected void onPause()来启动和停止服务