1

像许多其他人一样,我收到以下错误“无法启动服务意图...未找到”

我正在设置一个通知以每天运行一次活动(在我的测试中它设置为 30 秒)。这是通知代码:

Intent i = new Intent(this, OnNotificationReceiver.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.cancel(pi); // cancel any existing alarms

    am.setRepeating(AlarmManager.RTC_WAKEUP, notifyTime, AlarmManager.INTERVAL_FIFTEEN_MINUTES/30, pi);

OnNotificationReceiver.class 是:

public class OnNotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        WakeReminderIntentService.acquireStaticLock(context);
        Intent i = new Intent(context, NotificationService.class);
        context.startService(i);
    }

通知服务是:

public class NotificationService extends WakeReminderIntentService {
    public NotificationService() {
        super("ReminderService");
    }

    @Override
    void doNotificationWork(Intent intent) {
                 //Does work here
    }
}

WakeReminderIntentService 是:

public abstract class WakeReminderIntentService extends IntentService {
abstract void doNotificationWork(Intent intent);

public static final String LOCK_NAME_STATIC = "com.companionfree.pricewatcher";
private static PowerManager.WakeLock lockStatic = null;

public static void acquireStaticLock(Context context) {
    getLock(context).acquire();
}

synchronized private static PowerManager.WakeLock getLock(Context context) {
    if (lockStatic==null) {
        PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE);

        lockStatic=mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_NAME_STATIC);
        lockStatic.setReferenceCounted(true);
    }
    return(lockStatic);
}

public WakeReminderIntentService(String name) {
    super(name);
}

@Override
final protected void onHandleIntent(Intent intent) {
    try {
        doNotificationWork(intent);
    } finally {
        getLock(this).release();
    }
}
}

我的清单显示:

<receiver android:name=".OnNotificationReceiver"></receiver>

    <service android:name=".NotificationService"></service>
    <service android:name=".WakeReminderIntentService"></service>
</application>

谁能弄清楚我哪里出错了?

4

1 回答 1

1

如果您也发布了 logcat 错误(带有堆栈跟踪),那将会有所帮助。

在任何情况下,我都可以看到这段代码是错误的,并且可能会给你这个错误:

Intent i = new Intent(this, OnNotificationReceiver.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_ONE_SHOT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(pi); // cancel any existing alarms

您正在使用PendingIntenta Service。但是你需要一个PendingIntentfor a BroadcastReceiver。尝试调用PendingIntent.getBroadcast()

Intent i = new Intent(this, OnNotificationReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_ONE_SHOT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(pi); // cancel any existing alarms
于 2012-07-15T21:48:32.547 回答