如果我的应用程序正在运行,我按下主页按钮,应用程序进入后台.现在,如果长按home键并从最近的应用程序列表刷卡它杀死的应用程序,没有人像的事件onPause(),onStop()或者onDestroy()被调用,而该过程被终止.因此,如果我希望我的服务停止,杀死通知和取消注册听众,我该怎么做?我阅读了不少文章和博客,但没有得到任何有用的信息,我没有找到任何有关它的文档.任何帮助,将不胜感激.提前致谢.
Mys*_*icϡ 139
我刚刚解决了类似的问题.
如果通过从"最近的应用程序列表"轻扫应用程序而终止服务时,您可以执行此操作.
里面你的清单文件,守旗stopWithTask的true维修.喜欢:
<service
android:name="com.myapp.MyService"
android:stopWithTask="true" />
Run Code Online (Sandbox Code Playgroud)
但正如你所说,你想取消注册听众并停止通知等,我会建议这种方法:
里面你的清单文件,守旗stopWithTask的false维修.喜欢:
<service
android:name="com.myapp.MyService"
android:stopWithTask="false" />
Run Code Online (Sandbox Code Playgroud)现在在您的MyService服务中,覆盖方法onTaskRemoved.(只有在stopWithTask设置为时才会触发false).
public void onTaskRemoved(Intent rootIntent) {
//unregister listeners
//do any other cleanup if required
//stop service
stopSelf();
}
Run Code Online (Sandbox Code Playgroud)请参阅我的问题以获取更多详细信息,其中也包含其他部分代码.
希望这可以帮助.
emi*_*pmp 31
找到了一种方法来做到这一点
像这样做一个服务
public class OnClearFromRecentService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("ClearFromRecentService", "Service Started");
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("ClearFromRecentService", "Service Destroyed");
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("ClearFromRecentService", "END");
//Code here
stopSelf();
}
Run Code Online (Sandbox Code Playgroud)
}
2)在manifest.xml中注册此服务
<service android:name="com.example.OnClearFromRecentService" android:stopWithTask="false" />
Run Code Online (Sandbox Code Playgroud)
3)然后在您的启动活动上启动此服务
startService(new Intent(getBaseContext(), OnClearFromRecentService.class));
Run Code Online (Sandbox Code Playgroud)
现在每当你从android最近清除你的应用程序然后这个方法onTaskRemoved()将执行.
Ans*_*wal 15
我解决了类似的问题.如果您想要从最近的任务中滑动并在下次启动它时表现得正常,请按照以下步骤操作: -
1)在共享首选项中保存进程ID:
SharedPreferencesUtils.getInstance().putInt(SharedPreferencesUtils.APP_PROCESS_ID, android.os.Process.myPid());
2)从最近的任务清除后从启动器启动应用程序然后执行:
int previousProcessID = mSharedPreferencesUtils.getInt(SharedPreferencesUtils.APP_PROCESS_ID);
int currentProcessID = android.os.Process.myPid();
if ((previousProcessID == currentProcessID)) {
// This ensures application not killed yet either by clearing recent or anyway
} else {
// This ensures application killed either by clearing recent or by anyother means
}
Run Code Online (Sandbox Code Playgroud)
当您按下主页 - onPause并且onStop正在调用您的Activity时,所以此时您必须进行所有节省和清理,因为Android平台不会进一步保证onDestroy或将调用任何其他生命周期方法,因此该进程可能会被杀死没有任何通知.
| 归档时间: |
|
| 查看次数: |
66176 次 |
| 最近记录: |