IntentService won't start using AlarmManager

2019-02-21 13:43发布

I know there is a lot of questions about this but I really don't know where is my mistake.

My service is registered in the AndroidManifest.xml file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.app" >
        ...
        <service android:name="com.example.android.app.ScheduledService">
        </service>
    </application>
</manifest>

My service extends IntentService

public class ScheduledService extends IntentService {
    public ScheduledService() {
        super("ScheduledService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(getClass().getSimpleName(), "I ran!");
    }
}

My Activity starts the service

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d(getClass().getSimpleName(), "Setting alarm!!");

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent alarmIntent = new Intent(this, com.example.android.app.ScheduledService.class);
        PendingIntent pending = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);

        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() +
                        10 * 1000, pending);
    }
}

I don't see any exception in the logs. Is there something else I should do to setup my alarm?

3条回答
看我几分像从前
2楼-- · 2019-02-21 14:02

The API says:

typically comes from IntentSender.getBroadcast().

that means PendingIntent.getService can work too. I tested it, and it works.

查看更多
孤傲高冷的网名
3楼-- · 2019-02-21 14:07

As in documentation, PendingIntent.getBroadcast() is used to retrieve a PendingIntent that will perform a broadcast, like calling Context.sendBroadcast().

You need to call PendingIntent.getService() instead, which will start IntentService:

PendingIntent pending = PendingIntent.getService(this, 0, alarmIntent, 0);
查看更多
相关推荐>>
4楼-- · 2019-02-21 14:13

Look closely at the AlarmManager API and the PendingIntent. The AlarmManager.set() API is expecting a broadcast intent, which you are providing. However, you're trying to send a broadcast intent to a service, which cannot be done. Just create a BroadcastReceiver to catch the Intent and your BR should then start your service.

查看更多
登录 后发表回答