我想在安卓奥利奥版本中每 30 分钟跟踪一次用户。当用户从最近的应用程序托盘中杀死时,跟踪服务将停止。我尝试使用前台服务/工作管理器,它们在 Pie 中运行良好,但同样不适用于奥利奥。
Intent serviceIntent = new Intent(this, exampleService.class); serviceIntent.putExtra("inputExtra", input); ContextCompat.startForegroundService(this,serviceIntent);
示例服务.Java
public class ExampleService extends Service {
private Timer mTimer;
private Handler mHandler = new Handler();
private static final int TIMER_INTERVAL = 120000; // 2 Minute
private static final int TIMER_DELAY = 0;
@Override
public void onCreate() {
super.onCreate();
if (mTimer != null)
mTimer = null;
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new DisplayToastTimerTask(), TIMER_DELAY, TIMER_INTERVAL);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input=intent.getStringExtra("inputExtra");
Intent notificationIntent=new Intent(this, MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,
notificationIntent,0);
Notification notification=new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Example Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
return START_STICKY;
}
@Override
public void onDestroy() {
startAgainService();
super.onDestroy();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
startAgainService();
super.onTaskRemoved(rootIntent);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private class DisplayToastTimerTask extends TimerTask {
Handler mHandler = new Handler();
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Hello world every 5 minute", Toast.LENGTH_SHORT).show();
}
});
}
}
private void startAgainService() {
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
}
}
一些设备制造商已决定修改库存Android,以便在用户从最近的应用程序中滑出该应用程序时强制停止该应用程序。
正如WorkManager的公共问题跟踪器所报道的那样 -是否支持中国制造商(华为,Oppo,小米...),没有办法解决这个问题。
在这些情况下,你的工作将停止,直到用户再次启动你的应用。