簡體   English   中英

用戶強制停止后如何自動重新啟動服務

[英]How to automatically restart a service after force stop by user

我的服務工作正常,但是當我嘗試通過“ Clean Master”應用程序清除Clear Ram時,該服務被殺死,它無法自行重啟,我嘗試查找解決方案,但仍無法重啟,onDestroy()和onStartCommand()方法均未運行”服務被殺后不能工作這是我的服務代碼,請幫助我!

public class OverlayService extends Service {
LinearLayout oView;
static String color1;
private int flag;
SharedPreferences pref;
Editor editor;
Intent intent;
@Override
public IBinder onBind(Intent intent) {
    return null;
}
@Override
public void onCreate() {
    super.onCreate();
    intent=new Intent(this, OverlayService.class);
    pref = getApplicationContext().getSharedPreferences("ValueSave", MODE_PRIVATE);
    editor = pref.edit();
    flag = pref.getInt("flag", WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
    oView = new LinearLayout(this);  
    int cl = Color.parseColor(color1);
    oView.setBackgroundColor(cl); 
    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
            0 | flag, PixelFormat.TRANSLUCENT);        
    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    if(flag == WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN){
        editor.putBoolean("colorstatus", true);
    }
    else{
        editor.putBoolean("colorstatus", false);
    }
    editor.commit();

    wm.addView(oView, params);
}

public static void color(String a,String b){
    color1 = "#"+a+b;
}

@Override
public void onDestroy() {              
    if(oView!=null){
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        wm.removeView(oView);
    }
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    return Service.START_STICKY;
}

@SuppressLint("NewApi") @Override
public void onTaskRemoved(Intent rootIntent) {
    // TODO Auto-generated method stub
    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);
    super.onTaskRemoved(rootIntent);
}

}

3.1開始,如果您的應用程序被強制停止,則在用戶再次手動運行該應用程序之前,它不會重新啟動

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM