2011-09-27 21 views
1

我有一個服務,它在給定的時間間隔內自動調用數據庫。要做到這一點,它從互聯網上獲取信息。在Android中停止取消綁定服務

我需要解除綁定,以便它可以運行所有活動。但是當應用程序關閉時,終止服務將會很好。爲了防止電池耗盡。這怎麼能實現?

回答

2

我認爲你應該讓你的服務由啓動broadcastReceiver啓動,然後讓AlarmManager重新啓動它。

public class DbUpdateService extends Service { 
    //compat to support older devices 
    @Override 
    public void onStart(Intent intent, int startId) { 
     onStartCommand(intent, 0, startId); 
    } 


    @Override 
    public int onStartCommand (Intent intent, int flags, int startId){ 
    //your method to update the database 
    UpdateTheDatabaseOnceNow(); 

    //reschedule me to check again tomorrow 
    Intent serviceIntent = new Intent(DbUpdateService.this,DbUpdateService.class); 
    PendingIntent restartServiceIntent = PendingIntent.getService(DbUpdateService.this, 0, serviceIntent,0); 
    AlarmManager alarms = (AlarmManager)getSystemService(ALARM_SERVICE); 
    // cancel previous alarm 
    alarms.cancel(restartServiceIntent); 
    // schedule alarm for today + 1 day 
    Calendar calendar = Calendar.getInstance(); 
    calendar.add(Calendar.DATE, 1); 

    // schedule the alarm 
    alarms.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), restartServiceIntent); 
    return Service.START_STICKY; 
    } 

} 

要在引導時開始使用你的服務這樣的:

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 

public class serviceAutoLauncher extends BroadcastReceiver{ 

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

} 

最後添加到您的清單來安排你的serviceAutoLauncher在每次啓動上馬:

<receiver android:name="serviceAutoLauncher"> 
     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED"></action> 
      <category android:name="android.intent.category.HOME"></category> 
     </intent-filter> 
    </receiver> 
0

這取決於您如何啓動服務。如果您在打開「活動」時啓動它,請在您的Activities onDestroy()中調用stopService。