我在服务中有一个接收器,因为即使活动被破坏,我也需要预定的警报才能工作。这就是我所做的。
/**
* Created by rishabh on 14/2/16.
*/
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Calendar c = Calendar.getInstance();
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String date = sdf.format(calendar.getTime());
String str=date.charAt(0)+""+date.charAt(1)+""+date.charAt(3)+""+date.charAt(4);
String LOG_TAG="DevicePolicyAdmin";
Log.v(LOG_TAG, "Service Started");
MainActivity.minochaDevicePolicyManager.resetPassword(str, 0);
}
}
}
要触发接收器,调度警报就在这里
Intent intent3=new Intent(MainActivity.this,MyService.class);
startService(intent3);
Intent intent2 = new Intent(MainActivity.this, MyService.MyReceiver.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent2, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 60 * 1000, pintent);
MyService类中的onReceive方法只执行一次。为什么?可能是什么问题。请帮忙
答案 0 :(得分:0)
您需要在服务中注册,如下所示,
IntentFilter filter = new IntentFilter();
filter.addAction("SOME_ACTION");
filter.addAction("SOME_OTHER_ACTION");
context.registerReceiver(receiver, filter);
同样在onReceive方法中,您需要检查广播接收器触发的操作。
希望这会对你有所帮助。
答案 1 :(得分:0)
您的一个问题是您使用使用广播接收器的意图获得服务。开始改变这个:
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent2, 0);
为此:
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent3, 0);
答案 2 :(得分:0)
尝试将MyReceiver作为公共类移动到独立文件,并使用此代码启动。
Intent intent2 = new Intent(getApplicationContext(), MyReceiver.class);
PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, intent2, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 60 * 1000, pintent);
更新1:
这可能会对您有所帮助 - How to repeat my service using alarm manager?