2013-05-20 49 views
3

我需要一個服務,在我的應用程序中第一次啓動並永久運行,即使用戶重新啓動他的電話,我的服務會自動啓動而無需運行我的應用程序。我寫這個代碼,但當用戶重新啓動他的手機,我的服務不會重新開始!安排Android服務在電話重新啓動後重新開始

public class notifService extends Service { 
    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     super.onStart(intent, startId); 
     return Service.START_STICKY; 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
    } 
} 

,並在主要活動我開始服務是這樣的:

// start service 
Intent service = new Intent(MainActivity.this, notifService.class); 
MainActivity.this.startService(service); 

感謝您的幫助。

回答

4

收聽BroadcastReceiver中的android.intent.action.BOOT_COMPLETED並啓動您的服務。

例如

public class YourDefinedBootReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Intent service = new Intent(context, notifService.class); 
    context.startService(service); 
    } 
} 

而且,你必須持有權限:

編號:Automatically starting Services in Android after bootingAndroid Start Service on Boot Automatically