简体   繁体   English

广播接收者内部活动

[英]broadcast receiver inside activity

Hi folks how I can implement a Broadcast receiver in an activity that receives intent from a service along with some parameter's of int and string type? 大家好我如何在一个活动中实现一个广播接收器,该活动接收来自服务的意图以及一些int和string类型的参数?

UPDATE: 更新:

I have this under the Activity: 我在活动下有这个:

 private BroadcastReceiver ReceivefrmSERVICE = new BroadcastReceiver(){

    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context, "IN DA BroadCASTER",
                Toast.LENGTH_LONG).show();

    }

   };

and I have this under a function in the service that is called on a event from another activity when a checked button is checked: 我在服务中的一个函数下有这个函数,当选中一个选中的按钮时,它会调用来自另一个活动的事件:

 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);*/
    }

But its crashing?? 但它的崩溃? ,What to do? ,该怎么办?

BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {         
       // DO YOUR STUFF
    }
}

IntentFilter filter = new IntentFilter();

in onResume: (so you receive only while in foreground) 在onResume :(所以你只在前台收到)

filter.addAction(/* the action you want to receive */);
registerReceiver(receiver, filter);

in onPause: (the try catch is to fix a bug in unregister in case it is called twice) in 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;
    }
}
 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);
}


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM