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