与许多其他人一样,我收到以下错误“无法启动服务意图...未找到”
我正在设置每天运行一次活动的通知(在我的测试中,它设置为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);
}
NotificationService是:
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>
谁能弄明白我哪里出错?
答案 0 :(得分:1)
如果您也发布了logcat错误(使用stacktrace),那将会有所帮助。
在任何情况下,我都可以看到此代码错误,可能会给您错误:
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
您使用PendingIntent
表示Service
。但是PendingIntent
需要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