我有以下在手机启动时调用的广播接收器 (Bootreciever.java
),我正尝试启动一个使用重复警报间歇运行的服务。
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Inside onRecieve() :D" , Toast.LENGTH_LONG).show();
Log.d(getClass().getName(), "Inside onRecieve() :D");
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyService.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 3000, 1000, pi);
}
基本上,我将重复闹钟设置为触发 3 秒,然后每隔一秒触发一次。接收到启动完成广播就好了——但服务没有启动。 MyService.java
看起来像这样:
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Hello from MyService!", Toast.LENGTH_LONG);
Log.d(getClass().getName(), "Hello from MyService!");
stopSelf();
return super.onStartCommand(intent, flags, startId);
}
启动服务时我做错了什么?
Logcat 没有告诉我任何信息,我的 list 中定义了服务。该服务在使用 startService()
调用时可以正常工作,但在 PendingIntent
中使用时似乎会失败。
最佳答案
代替 PendingIntent.getBroadcast()
使用 PendingIntent.getService()
关于android - 通过警报启动服务不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10809720/