2

I have created one service which I want to call periodically through AlarmManager. I have written code for same, But it's not calling. If I call BroadcasrReciever through AlarmManager, then it's working fine.

Below is my Code,

@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);

    }

My service class is,

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

My manifiest file,

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

Do I have to create BroadcastReceiver class to call my service ? What is wrong in my code ? and why it's not calling periodically ?

Keval Patel
  • 925
  • 4
  • 24
  • 46
  • 2
    You need to get your `PendingIntent` with `PendingIntent.getService()` - not `getBroadcast()` - if you want it to start a `Service`. Also, `onBind()` isn't going to fire unless something binds the `Service`. You probably want `onCreate()` or `onStartCommand()` instead. – Mike M. Jul 31 '16 at 04:01
  • Possible duplicate of [Should I use PendingIntent.getService() or getBroadcast with AlarmManager?](http://stackoverflow.com/questions/7308298/should-i-use-pendingintent-getservice-or-getbroadcast-with-alarmmanager) – Mike M. Jul 31 '16 at 04:01
  • I changed to getBroadcast() to getService(), Still not working – Keval Patel Jul 31 '16 at 04:09
  • Did you check if `onCreate()` or `onStartCommand()` are called? – David Wasser Aug 03 '16 at 09:26
  • 1
    Please edit your post to show that you are using `getService()` and not `getBroadcast()`. – David Wasser Aug 03 '16 at 09:26
  • I removed service thing, And for now I am using PendingIntent.getBroadcast() only... Thanks – Keval Patel Aug 03 '16 at 16:44

1 Answers1

2

Make sure you don't use PendingIntent.getBroadcast, it wouldn't work. Using getService() instead, like this:

PendingIntent pendingIntent = PendingIntent.getService(this, 0, alarmIntent, 0);
xxx
  • 3,315
  • 5
  • 21
  • 40