Kap*_*put 8 android android-service
我在最近2天遇到了一个问题,我想点击api并向用户显示Toast当用户从后台任务中刷掉应用程序时,我发现从应用程序从后台删除时service可能会出现这种情况onTaskRemoved.
代码:
MyService.java
public class MyService extends Service {
private static final String TAG = MyService.class.getSimpleName();
Handler mHandler;
@Override
public void onCreate() {
super.onCreate();
mHandler = new Handler();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: ");
mHandler.post(new Runnable() {
@Override
public void run() {
new ToastPoP(MyService.this).showLongToast("Service started");
}
});
return Service.START_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.d(TAG, "onTaskRemoved: ");
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(App.getInstance(), "Removed", Toast.LENGTH_SHORT).show();
// api call too
}
});
// for kitket
Intent restartService = new Intent(getApplicationContext(),
this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
Run Code Online (Sandbox Code Playgroud)
在Manifest我添加了这个:
<service
android:name=".MyService"
android:stopWithTask="false"
>
</service>
Run Code Online (Sandbox Code Playgroud)
并service在SplashScreen中启动:
Intent i = new Intent(this, MyService.class);
this.startService(i);
Run Code Online (Sandbox Code Playgroud)
服务启动良好但从onTaskRemoved我从后台删除应用程序时从未调用过.为什么?我做错了什么?
注意:
有趣的结果是我能够在某些设备中获得Toast但在大多数设备中都没有,并且所有设备都有OS-Android 5.0
him*_*eam -3
试试这个
<service
android:name=".MyService"
android:enabled="true"
android:stopWithTask="false" />
Run Code Online (Sandbox Code Playgroud)
只需替换Service.START_STICKY;为START_STICKY;
一旦应用程序从最近的应用程序列表中删除/清除,您就可以调用onTaskRemoved(Intent rootIntent)。
| 归档时间: |
|
| 查看次数: |
4063 次 |
| 最近记录: |