使用返回START_STICKY並將其設置爲startForeground的服務,這樣,即使系統在一段時間後將其資源關閉並重新正常運行,您的應用程序也會一直運行,並且用戶將其很好地殺死這是甚至是大的應用程序抱怨,就像你在第一次安裝whatsapp時看到的那樣。這裏的服務應該是怎麼樣的一個例子:
public class Yourservice extends Service{
@Override
public void onCreate() {
super.onCreate();
// Oncreat called one time and used for general declarations like registering a broadcast receiver
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// here to show that your service is running foreground
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent bIntent = new Intent(this, Main.class);
PendingIntent pbIntent = PendingIntent.getActivity(this, 0 , bIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP);
NotificationCompat.Builder bBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("title")
.setContentText("sub title")
.setAutoCancel(true)
.setOngoing(true)
.setContentIntent(pbIntent);
barNotif = bBuilder.build();
this.startForeground(1, barNotif);
// here the body of your service where you can arrange your reminders and send alerts
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
}
這是一個持續的服務以執行代碼的最佳配方。
感謝您的回覆,我會研究/檢查它。 –