如何在用户强制停止后自动重启服务

时间:2015-07-21 09:47:33

标签: java android android-service

我的服务工作正常,但当我尝试清除Ram" Clean Master"应用程序然后服务被杀死它不能重新启动自己,我试图找到解决方案,但它仍然没有重新启动,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);
}

}

1 个答案:

答案 0 :(得分:1)

3.1开始,如果您的应用程序被强制停止,则在用户再次手动运行应用程序之前不会重新启动