IntentService无法开始使用AlarmManager [英] IntentService won't start using AlarmManager

查看:61
本文介绍了IntentService无法开始使用AlarmManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道对此有很多疑问,但我真的不知道我的错误在哪里。

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

我的服务已在AndroidManifest.xml文件中注册

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>

我的服务扩展了IntentService

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!");
    }
}

我的活动启动服务

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?

推荐答案

文档 PendingIntent .getBroadcast()用于检索将执行广播的 PendingIntent ,例如调用 Context.sendBroadcast()

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

您需要调用 PendingIntent.getService(),它将开始 IntentService

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

PendingIntent pending = PendingIntent.getService(this, 0, alarmIntent, 0);

这篇关于IntentService无法开始使用AlarmManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆