2013-08-16 229 views
0

我已經開發了一項服務,在活動啓動時自動啓動。 但我想停止一定的時間間隔說10秒後服務,並在30秒後說一段時間後再次啓動服務。 我是一個新的android編程,所以沒有得到如何做到這一點,請幫助。 我正在使用廣播接收器來啓動服務。延遲啓動服務

+0

使用報警管理 –

+0

可能重複[如何安排一些代碼執行在Android或:?究竟是Android的守護線程(http://stackoverflow.com/questions/3883246/how- to-schedule-some-code-execution-in-android-or-what-exactly-are-daemon-threa) – Gusdor

+0

使用TimerTask或AlarmManager – AndroUser

回答

5

我會建議使用報警管理器和發送掛起的意圖來啓動服務。就像這樣:

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
Intent serviceIntent = new Intent(context, ServiceReceiver.class); 
PendingIntent pi = PendingIntent.getBroadcast(context, ServiceIdsConstants.SERVICE_ID,  serviceIntent , PendingIntent.FLAG_UPDATE_CURRENT); 
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 30000, pi); 

然後在廣播接收器做到這一點:

Intent intent = new Intent(context, MyServiceService.class); 
context.startService(intent); 
+0

使用wifimanager和bluetoothmanager時可以使用鬧鐘管理器嗎? – user2661237

+0

我不確定我是否按照你的問題。一般來說,廣播接收器沒有很多時間來執行。你通常會從他們開始一項服務。然後使用服務上下文,您可以獲得藍牙或WiFi管理器。 –

+0

是否有任何理由直接使用am.getBroadcast(serviceIntent)而不是直接使用am.getService(MyServiceService),完全繞過廣播? – averasko

0

只是寫了一個實用工具,您和其他人可以使用:

public static void startDelayedWakefulService(Context context,long delayInMillis,Class<? extends Service> serviceClass) { 
    AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); 
    Intent serviceIntent = new Intent(context, DelayedStartServiceBroadcastReceiver.class); 
    serviceIntent.putExtra("className",serviceClass.getName()); 
    PendingIntent pi= PendingIntent.getBroadcast(context, 7, serviceIntent , PendingIntent.FLAG_UPDATE_CURRENT); 
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeInMillis()+delayInMillis, pi); 
} 

public class DelayedStartServiceBroadcastReceiver extends WakefulBroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     String className = intent.getStringExtra("className"); 
     try { 
      startWakefulService(context,new Intent(context,Class.forName(className))); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
      completeWakefulIntent(intent); 
     } 
    } 
} 

不要忘記將它添加到您的清單

<receiver 
     android:name=".utils.DelayedStartServiceBroadcastReceiver" 
     android:enabled="true" 
     android:exported="true" > 
    </receiver>