2014-12-06 178 views
0

我創建了一項服務,該服務在電話啓動時啓動。但是,當我打開應用程序時,服務會再次啓動並停止運行舊服務,但服務正常運行。但是當我關閉應用程序時,該服務也會停止。如何使用啓動時啓動的服務以及如果啓動時啓動的服務被系統殺死,如何重新運行該服務?Android打開應用程序後臺服務後停止並啓動新服務

這裏是我的代碼

AndroidManifest.xml中

<receiver android:name=".MyBroadcastReceiver" > 
    <intent-filter> 
     <action android:name="android.intent.action.BOOT_COMPLETED" /> 
    </intent-filter> 
</receiver> 

<service android:name=".AppMainService" /> 

MyBroadCastReceiver

public class MyBroadcastReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     Intent startServiceIntent = new Intent(context, AppMainService.class); 
     context.startService(startServiceIntent); 
    } 
} 

AppMainService

public class AppMainService extends IntentService { 

    private Timer timer; 
    private ReceiveMessagesTimerTask myTimerTask; 
    public static AppPreferences _appPrefs; 
    public static SQLiteDatabase qdb; 
    public static Config config; 
    public static Engine engine; 

    /** 
    * A constructor is required, and must call the super IntentService(String) 
    * constructor with a name for the worker thread. 
    */ 
    public AppMainService() { 
     super("HelloIntentService"); 
    } 
    public void onStart(Intent intent, Integer integer) { 
     super.onStart(intent, integer); 
    } 
    public void onCreate() { 
     super.onCreate(); 
     DB db = new DB(this); 
     qdb = db.getReadableDatabase(); 

     _appPrefs = new AppPreferences(getApplicationContext()); 
     config = new Config(); 
     engine = new Engine(); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     super.onStartCommand(intent, startId, startId); 
     Log.i("sss", "Service sarted"); 
     return START_REDELIVER_INTENT; 
    } 
    /** 
    * The IntentService calls this method from the default worker thread with 
    * the intent that started the service. When this method returns, IntentService 
    * stops the service, as appropriate. 
    */ 
    @Override 
    protected void onHandleIntent(Intent intent) { 
     timer = new Timer(); 
     myTimerTask = new ReceiveMessagesTimerTask(); 
     timer.schedule(myTimerTask, 0, 10000); 
    } 

    class ReceiveMessagesTimerTask extends TimerTask { 

     @Override 
     public void run() { 
      //Sending messages 
      Log.i("Service", String.valueOf(System.currentTimeMillis())+_appPrefs.getToken()); 
     } 
    } 
} 

,在我的活動

protected void onCreate(Bundle savedInstanceState) { 
     ... 

     Intent intent = new Intent(this, AppMainService.class); 
     startService(intent); 
} 

回答

0

此行爲是由設計,因爲您是子類IntentService。一旦它處理了所有的意圖,它就會自動關閉。如果您希望自己的服務持續下去,請改爲擴展Service並實施您自己的線程機制。