2015-10-26 26 views
0

我有一個由alarmmanager每5秒調用一個intentservice類。 Alarmmanager調用intentservice,它工作正常。但是當它調用時,它會創建新的intentservice。我只想調用intentService的onHandleIntent方法不想創建新的方法。這裏是我的代碼:如何重複調用intentservice onHandleIntent方法而不創建新的intentservice

IntentService類:

public class MyIntentService extends IntentService { 
    private static final String serviceName = "MyIntentService"; 

    public MyIntentService() { 
     super(serviceName); 
    } 

    public void onCreate() { 
     super.onCreate(); 
     Log.d("Servis", "onCreate()"); //this is called every 5 seconds too 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
    //do something 
    } 
} 

設置alarmManager爲IntentService

public void setAlarm(View v) 
{ 
     Calendar cal = Calendar.getInstance(); 
     AlarmManager am =(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); 
     long interval = 1000 * 5; 
     Intent serviceIntent = new Intent(context, MyIntentService.class); 

     PendingIntent servicePendingIntent = 
       PendingIntent.getService(context, 12345, serviceIntent,PendingIntent.FLAG_CANCEL_CURRENT); 

     am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),interval, servicePendingIntent 
     ); 
} 

回答

1

我有由alarmmanager每5秒被稱爲intentservice類。

這對於Android 5.1及更高版本無效,其中最小setRepeating()週期爲60秒。另外,請記住,在Android 6.0+上,打盹模式和應用程序待機模式意味着在一天中的大部分時間裏,您無法在任何位置接近該頻率。

但是當它調用時,它會創建新的intentservice。

這就是IntentService背後的要點。一旦onHandleIntent()結束,IntentService就會被銷燬。

我只是想調用intentService的onHandleIntent方法不想創建新的方法。

然後不要使用IntentService。使用Service,覆蓋onStartCommand()而不是onHandleIntent(),並執行自己的後臺線程邏輯。不再需要時,請務必停止服務(例如,stopSelf())。

+0

非常感謝你的啓發:) – gencer

相關問題