broadcast receiver inside activity

10,155
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)

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)

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;
    }
}
Share:
10,155
Naaz
Author by

Naaz

please delete me

Updated on June 04, 2022

Comments

  • Naaz
    Naaz almost 2 years

    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?

    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?