大家好我如何在一个活动中实现广播接收器,该活动接收来自服务的意图以及一些int和string类型的参数?
更新
我在活动下有这个:
private BroadcastReceiver ReceivefrmSERVICE = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "IN DA BroadCASTER",
Toast.LENGTH_LONG).show();
}
};
我在服务中的一个函数下有一个函数,当选中一个选中的按钮时,来自另一个活动的事件调用该函数:
public void switchSpeaker(int hr, int min){
Toast.makeText(Server.this, hr +" , " +min, Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, andRHOME.class);
//intent.putExtra("sendMessage","1");
startActivity(intent);
/*PendingIntent pi = PendingIntent.getService(Server.this, 0, myIntent, 0);
AlarmManager almmgr = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar cldr = Calendar.getInstance();
int min1 = cldr.get(Calendar.MINUTE);
cldr.setTimeInMillis(System.currentTimeMillis());
cldr.add(Calendar.SECOND, 30);
almmgr.set(AlarmManager.RTC_WAKEUP, cldr.getTimeInMillis(), pi);*/
}
但它的崩溃? ,该怎么办?
答案 0 :(得分:10)
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// DO YOUR STUFF
}
}
IntentFilter filter = new IntentFilter();
onResume中的:(所以你只在前台收到)
filter.addAction(/* the action you want to receive */);
registerReceiver(receiver, filter);
onPause中的:( try catch用于修复取消注册中的错误,以防它被调用两次)
try {
unregisterReceiver(receiver);
} catch (IllegalArgumentException e) {
if (e.getMessage().contains("Receiver not registered")) {
// Ignore this exception. This is exactly what is desired
Log.w(TAG,"Tried to unregister the reciver when it's not registered");
} else {
// unexpected, re-throw
throw e;
}
}
答案 1 :(得分:0)
public class myActivity extends Activity {
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Message", Toast.LENGTH_SHORT);
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}