【问题标题】:onTaskRemoved of a Android Service is never being called ! Why?永远不会调用 Android 服务的 onTaskRemoved !为什么?
【发布时间】:2016-10-13 12:39:43
【问题描述】:

我在过去 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: ");
}
}

Manifest 我添加了这个:

 <service
        android:name=".MyService"
        android:stopWithTask="false"
        >
    </service>

并在 SplashScreen 中启动 service

 Intent i = new Intent(this, MyService.class);
    this.startService(i);

服务启动良好,但当我从后台删除应用程序时,从未调用过 onTaskRemoved。为什么 ?我做错了什么?

注意:

有趣的结果是,我能够在某些设备上获得 Toast,但在大多数设备中却不行,而且所有设备都具有 OS-Android 5.0

【问题讨论】:

  • 只需在 Manifest 中的服务标签中设置 android:stopWithTask="true"。
  • @Radhey 我试过了,没有效果,服务也被应用程序破坏了
  • 你最终找到解决方案了吗?
  • @himCream 没有 :( 还没有
  • 我认为这可能是原因:stackoverflow.com/a/42120277/247013

标签: android android-service


【解决方案1】:

试试这个

<service
            android:name=".MyService"
            android:enabled="true"
            android:stopWithTask="false" />

只需将Service.START_STICKY; 替换为START_STICKY;

一旦从最近的应用列表中删除/清除应用,您就可以致电onTaskRemoved(Intent rootIntent)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    相关资源
    最近更新 更多