2015-07-21 79 views
0

我的服務工作正常,但是當我嘗試通過「Clean Master」應用程序清除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); 
} 

}

+0

如果該服務被粘然後它會自動啓動無需要實現任何類型的代碼。 – Pankaj

+0

@Override public int onStartCommand(Intent intent,int flags,int startId){TODO自動生成方法存根 return Service.START_STICKY; 我使用這個,但不適合我 –

回答

1

3.1開始,如果你的應用是強制停止,也不會重新啓動,直到用戶手動重新運行該應用程序

相關問題