android - Android 服务的 onTaskRemoved 永远不会被调用!为什么?

标签 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: ");
}
}

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

最佳答案

试试这个

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

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

一旦应用程序从最近的应用程序列表中删除/清除,您将能够调用 onTaskRemoved(Intent rootIntent)

关于android - Android 服务的 onTaskRemoved 永远不会被调用!为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40021274/

相关文章:

java - <> 在类名中是什么意思?

android - 我可以在 xamarin android 应用程序中设置设备语言/文化吗

android - Android Cordova 插件中的请求权限不会提示用户

android - 如果我在短时间后再次启动它,我应该停止我的 android 服务吗?

android - 将数据从 Activity 发送到 Service

android - 广播接收器中的线程未发生网络调用

Android Pie (9.0) WebView 多进程

java - Android onConfigurationChanged 未被调用

安卓。关闭应用程序时 WorkManager 是否正在运行?

android - Android 平板电脑上的系统栏大小