我尝试设置android:isolatedProcess="true"
,但它无效
实际上我想一直显示永久通知
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), resourceIcon/*R.mipmap.ic_launcher*/))
.setSmallIcon(R.drawable.ic_icon_flo_not)
.setContentTitle(title)
.setOngoing(onGoing)
.setAutoCancel(autoCancelable)
.setPriority(priority)
.setContentText(message);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (playSound)
mBuilder.setSound(soundUri);
if (remoteViews == null) {
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, resultClass);
resultIntent.setAction(action);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
} else {
mBuilder.setContent(remoteViews);
}
答案 0 :(得分:1)
覆盖服务中的onTaskRemoved()并使用警报管理器再次启动服务。下面是代码。
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.d(TAG, "TASK REMOVED");
PendingIntent service = PendingIntent.getService(
getApplicationContext(),
1001,
new Intent(getApplicationContext(), MyService.class),
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
}
答案 1 :(得分:1)
Service.START_STICKY服务是那些由于某种原因终止而重启的服务。你只需要从onStartCommand返回Service.START_STICKY
cal()
{
a=$(ip addr | grep "wlan0" | sed '1d' |awk '{print $2}' | sed -e 's/\(.*\)...$/\1/')
echo $a
b=10.98.35.96
if [ $b = $a ]
then
echo same
#give command
kill -9 $$
else
echo notsame
sleep 3
cal
fi
}
cal
你只需要在上面做,没有必要做的事情
答案 2 :(得分:0)
重新创建服务 ,不重新启动。
如果您覆盖onCreate
并执行Log.d或Toast,您将看到在活动和应用程序销毁后onCreate被调用。
因此,重新创建代码后使其保持运行的诀窍是使用onCreate
方法编写代码,并将onStartCommand
仅用于return START_STICKY
。
需要注意的另一件事(由于我无法发表评论,因此我想用AlarmManager
添加到Abdul Kawee答案中):
在api27上已解决:您要做的就是将super.onTaskRemoved(rootIntent)
移到代码的最后一行。
我发现破坏性方法只能在覆盖方法的末尾调用super,否则某些资源在运行时将不再可用。