Android面試題-service被kill之後怎麼讓它重啟
阿新 • • 發佈:2019-01-03
一: 在onStartCommand方法中將flag設定為START_STICKY;
return Service.START_STICKY;
二:在xml中設定了android:priority
<!--設定服務的優先順序為MAX_VALUE-->
<service android:name=".MyService"
android:priority="2147483647"
>
</service>
三:在onStartCommand方法中設定為前臺程序
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e (this.getClass().getName(), "---------------onStartCommand -----------");
Notification notification = new Notification(R.mipmap.ic_launcher, "服務正在執行",System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity (this, 0,notificationIntent,0);
RemoteViews remoteView = new RemoteViews(this.getPackageName(),R.layout.notification);
remoteView.setImageViewResource(R.id.image, R.mipmap.ic_launcher);
remoteView.setTextViewText(R.id.text , "Hello,this message is in a custom expanded view");
notification.contentView = remoteView;
notification.contentIntent = pendingIntent;
startForeground(1, notification);
return Service.START_STICKY;
}
四:在onDestroy方法中重啟service
@Override
public void onDestroy() {
super.onDestroy();
startService(new Intent(this, MyService.class));
}
五:用AlarmManager.setRepeating(…)方法迴圈傳送鬧鐘廣播,接收的時候呼叫service的onstart方法
Intent intent = new Intent(MainActivity.this,MyAlarmReciver.class);
PendingIntent sender = PendingIntent.getBroadcast( MainActivity.this, 0, intent, 0);
// We want the alarm to go off 10 seconds from now.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 1);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
//重複鬧鐘
/**
* @param type
* @param triggerAtMillis t 鬧鐘的第一次執行時間,以毫秒為單位
* go off, using the appropriate clock (depending on the alarm type).
* @param intervalMillis 表示兩次鬧鐘執行的間隔時間,也是以毫秒為單位
* of the alarm.
* @param operation 綁定了鬧鐘的執行動作,比如傳送一個廣播、給出提示等等
*/
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 2 * 1000, sender);
五:目前市場面的很多三方的訊息推送SDK喚醒APP,例如Jpush
總結
這純粹是面試的時候忽悠一下面試官,不代表著你的Service就永生不死了,只能說是提高了程序的優先順序。迄今為止我沒有發現能夠通過常規方法達到流氓需求(通過長按home鍵清除都清除不掉)的方法,目前所有方法都是指通過Android的記憶體回收機制和普通的第三方記憶體清除等手段後仍然保持執行的方法,有些手機廠商把這些知名的app放入了自己的白名單中,保證了程序不死來提高使用者體驗(如微信、QQ、陌陌都在小米的白名單中)。如果從白名單中移除,他們終究還是和普通app一樣躲避不了被殺的命運。
歡迎關注微信公眾號,長期推薦技術文章和技術視訊
微信公眾號名稱:Android乾貨程式設計師