Starting a service using Alarm Manager

I am trying to start a service using Alarm Manager. I tried everything but it just didn't start. I am calling the below code from a button listener.

    private void setAlarmManager(String interval) throws NumberFormatException, IOException
    {
        AlarmManager service = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(getApplicationContext(), MyService.class);

        PendingIntent pending = PendingIntent.getBroadcast(getApplicationContext(),
                                                           0,
                                                           i,
                                                           PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar cal = Calendar.getInstance();

        cal.add(Calendar.MINUTE, Integer.valueOf(interval));
        service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                                    (Integer.valueOf(interval) * 60000), pending);
    }

      

and my manifest looks like this:

<service android:enabled="true" android:name="com.pack.android.service.MyService"
            />

      

I am trying to start a service according to a user specified time in minutes. But my service is never called.

If I call the service using the following code, it works. My target version of the project is 16.

getApplicationContext().startService(i);

      

+3


source to share


1 answer


change PendingIntent.getBroadcast

to PendingIntent.getService

to run serivce with PendingIntent

like:



PendingIntent pending = PendingIntent.getService(getApplicationContext(),
                                     0,
                                     i,
                                   PendingIntent.FLAG_CANCEL_CURRENT);

      

+4


source







All Articles