0

我已經創建了一個服務,我想通過AlarmManager定期撥打電話。我已經寫了相同的代碼,但它沒有調用。如果我通過AlarmManager調用BroadcasrReciever,那麼它工作正常。使用AlarmManager撥打服務

下面是我的代碼,

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_home); 

     Intent alarmIntent = new Intent(this, LocationUpdateService1.class); 
     PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0); 
     AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
     manager.setRepeating(AlarmManager.RTC_WAKEUP, 20000, 11000, pendingIntent); 

    } 

我的服務類,

public class LocationUpdateService1 extends Service { 
    @Nullable 
    @Override 
    public IBinder onBind(Intent intent) { 
     Toast.makeText(getApplicationContext(), "I created", Toast.LENGTH_LONG); 
     return null; 
    } 
} 

我manifiest文件,

<service 
      android:name=".Services.LocationUpdateService1"> 
     </service> 

我一定要建立廣播接收器類調用我的服務? 我的代碼有什麼問題?爲什麼不定期打電話?

+1

你需要讓你的''PendingIntent' PendingIntent.getService()' - 不是'getBroadcast()' - 如果你想讓它開始'Service'。另外,除非綁定「Service」,否則'onBind()'不會觸發。您可能需要'onCreate()'或'onStartCommand()'。 –

+0

[我應該使用PendingIntent.getService()還是使用AlarmManager的getBroadcast?](http://stackoverflow.com/questions/7308298/should-i-use-pendingintent-getservice-or-getbroadcast-with-alarmmanager) –

+0

我更改爲getBroadcast()getService(),仍然不能正常工作 –

回答

1

確保你不要使用PendingIntent.getBroadcast,它不會工作。使用的getService()代替,就像這樣:

PendingIntent pendingIntent = PendingIntent.getService(this, 0, alarmIntent, 0); 
+0

無法理解參數。如果可能,請使用正確的代碼轉換我的代碼。 –

+0

@KevalPatel很簡單,只需更新答案:) – alway5dotcom