【发布时间】:2016-09-02 07:30:04
【问题描述】:
我有执行服务的主要活动。在这个服务中,我初始化了一个 BroadcastReceiver(警报)。
然后我需要从警报广播的 onReceive 方法发送广播,但不起作用。但是,如果我在警报中执行其他方法的 sendBroadcast() ,则可以正常工作。
请参阅代码以解释我:
Activity(初始化服务并获取broadcastReceiver)
private final BroadcastReceiver abcd = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Intent in = getIntent();
//finish();
Log.d("sdasd", "onReceive: BROADCAST RECIBIDO!!!");
}
};
服务
alarm alarm = new alarm();
public void onCreate()
{
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
alarm.setAlarm(this, tiempo);
return START_STICKY;
}
Alarm.class
@Override
public void onReceive(Context context, Intent intent)
{
context.sendBroadcast(new Intent("xyz"));
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
}
public void setAlarm(Context context, int tiempo)
{
Log.e("TAG", "setAlarm: ");
context.sendBroadcast(new Intent("xyz"));
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), tiempo, pi); // Millisec * Second * Minute
}
在alarm.class 中,执行了serAlarm() 中的sendBroadcast,但未执行onreceive 中的sendBroadcast。吐司很完美。
为什么?
【问题讨论】:
-
你在哪里注册的
BroadcastReceiver?在您共享的代码中,您实例化了它,但您没有注册它 -
您的
abcd订阅了哪些操作?显示您注册abcd接收者的代码 -
我在活动的 onCreate 中注册了 abc 接收器 //registerReceiver(abcd, new IntentFilter("xyz"));接收器工作正常,但不能进入其他广播的 onReceive
标签: android broadcastreceiver alarm