2

大家好,我如何在从服务接收意图以及一些 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);*/
    }

但是它崩溃了?,该怎么办?

4

2 回答 2

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 是为了修复 unregister 中的错误,以防它被调用两次)

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;
    }
}
于 2012-12-14T14:05:58.000 回答
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);
}


}
于 2012-12-14T14:04:00.533 回答