In my Application I have to notify my Activity from IntentService class .
For that purpose I am using LocalBroadcastManager. But I am not receiving anything in the onReceive of my Broadcast Receiver. Here is what I have written.
In my BaseActivity I have registered my receiver.
public class BaseActivity extends FragmentActivity implements App {
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(custom-event-name));
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mMessageReceiver);
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
System.out.println("Overlay Message" +bundle.getString("message"));
}
};
}
I am sending a local broadcast from my RegisterAlarmIntentService class.
public class RegisterAlramIntentService extends WakefulIntentService implements
APIConstants {
public RegisterAlramIntentService() {
super("AlarmService");
}
#Override
public String getTag() {
return "AlarmService";
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("Working till here fine In RegisterAlarm");
Bundle bundle = intent.getExtras();
Intent localIntent = new Intent(custom-event-name);
localIntent.putExtras(bundle );
LocalBroadcastManager.getInstance(this).sendBroadcast(
localIntent);
}
}
onHandleIntent() method is called. But nothing is received in onReceive() of my receiver.
Please Help. Thanks in advance!!
Try
public class RegisterAlramIntentService extends WakefulIntentService implements
APIConstants {
Intent localIntent;
public RegisterAlramIntentService() {
super("AlarmService");
localIntent = new Intent(custom-event-name);
}
#Override
public String getTag() {
return "AlarmService";
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("Working till here fine In RegisterAlarm");
Bundle bundle = intent.getExtras();
Thread.sleep(5000); // For Testing only because it is in whole new thread (which may not wait for your reciever to setup)
localIntent.putExtras(bundle );
LocalBroadcastManager.getInstance(this).sendBroadcast(
localIntent);
}
}
Also in manifest :
<service android:name="com.commonsware.android.localcast.RegisterAlramIntentService"/>
See this
Related
I followed this tutorial: http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/#comment-2952759611
I am able to send Firebase notifications to an Android app.
My class which extends the Firebase messaging service is
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification() != null) {
String notificationTitle = remoteMessage.getNotification().getTitle();
String notificationBody = remoteMessage.getNotification().getBody();
handleNotification(notificationTitle, notificationBody);
}
private void handleNotification(String title, String body) {
if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
pushNotification.putExtra("title", title);
pushNotification.putExtra("message", body);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
} else {
// If the app is in background, firebase itself handles the notification
}
}
}
In one of my activities I have a listener defined and all other activities extend this class
public class DisplayNotificationActivity extends AppCompatActivity {
private BroadcastReceiver mRegistrationBroadcastReceiver;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_notification);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// process notification
}
}
}
}
An example of a class which extends DisplayNotificationActivity is:
public class ListNotificationsActivity extends DisplayNotificationActivity {
private BroadcastReceiver mRegistrationBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_notifications);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// process notification
}
};
}
}
If I am on the DisplayNotificationActivity activity when I receive a notification everything works as expected, but if I am on another activity such as ListNotificationsActivity then the DisplayNotificationActivity onCreate method is called, not the onCreate in the active activity.
How do I have the current activity handle the receiving of a notification on any activity without repeating the same code in all activities?
Edit: I do pause and resume the activity, this code is in DisplayNotificationActivity
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.REGISTRATION_COMPLETE));
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.PUSH_NOTIFICATION));
NotificationUtils.clearNotifications(getApplicationContext());
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
Your activity DisplayNotificationActivity is super class for activity ListNotificationsActivity and you have called super.onCreate() method in ListNotificationsActivity that definitely will call super method onCreate of your super class i.e. DisplayNotificationActivity.
Now for solution what you can do is use interface:
public abstract class DisplayNotificationActivity extends AppCompatActivity {
private BroadcastReceiver mRegistrationBroadcastReceiver;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_notification);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// process notification
onNotificationReceived(your notification message);
}
}
}
public void onNotificationRecieved(String notiMessage);
}
And on your ListNotificationsActivity :
public class ListNotificationsActivity extends DisplayNotificationActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_notifications);
}
#Override
public void onNotificationRecieved(String notiMessage) {
//process your notification
}
}
I have not run the code see if this works.
I am using a LocalBroadcastManager to make broadcast to my activtiy and services using APPLICATION CONTEXT , like this:
public class CommonForApp extends Application{
public void broadcastUpdateUICommand(String[] updateFlags,
String[] flagValues) {
Intent intent = new Intent(UPDATE_UI_BROADCAST);
for (int i = 0; i < updateFlags.length; i++) {
intent.putExtra(updateFlags[i], flagValues[i]);
}
mLocalBroadcastManager = LocalBroadcastManager.getInstance(mContext);
mLocalBroadcastManager.sendBroadcast(intent);
}}
Now Using a Listener in my Service, I am calling broadcastUpdateUICommand() ,like this:
public class mService extends Service {
public BuildNowPLaylistListListener buildCursorListener = new BuildNowPLaylistListListener() {
#Override
public void onServiceListReady() {
mApp.broadcastUpdateUICommand(
new String[] { CommonForApp.INIT_DRAWER},
new String[] {""});
}}}
And i am receiving the broadcast in my Activity, like this:
public class mActivity extends Activity{
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mtoast.showtext("in onreceive"); //toast to check
if (intent.hasExtra(CommonForApp.INIT_DRAWER))
initialiseDrawer();
}};
}
mApp is instance of Application.
CommonForApp is my Application Class.
But in my activity i am not receving any broadcast(the broadcast manager is initialised using application context) .
Can Anyone suggest me why i am not receiving broadcast in my activity? ..
.Thanks in advance !
in activity:
protected BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, final Intent intent) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(intent.hasExtra("type")){
// Do some action
}
}
});
}
};
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("data-loaded"));
}
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
then you send broadcast:
public static void sendBroadcastMessageDataLoaded(Context context, String dataType){
Intent intent = new Intent("data-loaded");
intent.putExtra("type", dataType);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
I Have three activities
On activity A i register the broadcast receiver ,then i go to activity B from there i go to activity C.
and finally onBackPressed of activity c ,i send the broadcast
but onReceive is not called
My first Activity
private MyBroadCastReceiver myRecevier = new MyBroadCastReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent frag=new Intent(MainActivity.this,Activity2.class);
//frag.putExtra("Limit", foo);
startActivity(frag);
// }
}
});
}
#Override
protected void onResume() {
super.onResume();
//Register the activity to the broadcast receiver
registerReceiver(myRecevier, new IntentFilter(MyBroadCastReceiver.ACTION));
}
#Override
protected void onPause() {
super.onPause();
//Unregister the activity from the broadcast receiver. Good practice ;)
unregisterReceiver(myRecevier);
}
public class MyBroadCastReceiver extends BroadcastReceiver{
public static final String ACTION = "com.uberrueco.mybroadcastreceiver.receivers";
#Override
public void onReceive(Context context, Intent intent) {
Log.d("MyBroadCastReceiver", "received");
Toast.makeText(context,"Received "+intent.getStringExtra("editText"), Toast.LENGTH_LONG).show();
}
}
}
Second activity has nothing but an intent to activity 3
Third Activity
public class Activity3 extends Activity {
EditText etReceivedBroadcast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity3);
etReceivedBroadcast = (EditText) findViewById(R.id.etReceivedBroadcast);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent intent = new Intent(this, MyIntentService.class);
intent.putExtra("editText", etReceivedBroadcast.getText().toString());
startService(intent);
}
}
and finally my IntentService class
public class MyIntentService extends IntentService{
public MyIntentService(){
super("MyIntentService");
}
public MyIntentService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d("MyIntentService", "handling intent...");
//Intent created for broadcasting
Intent intentBroadCast = new Intent();
//Filter the broadcast to the action desired
intentBroadCast.setAction(MyBroadCastReceiver.ACTION);
intentBroadCast.putExtra("editText", intent.getStringExtra("editText"));
//Send the broadcast :D
sendBroadcast(intentBroadCast);
}
}
You are calling unregisterReceiver in onPause of MainActivity . So you are not recieving the broadcast.
Move register to onCreate and unregister to onDestroy of your MainActivity.
if your onHandleIntent() was called then you should try like.
Intent intentBroadCast = new Intent(MyBroadCastReceiver.ACTION);
intentBroadCast.putExtra("editText", intent.getStringExtra("editText"));
//Send the broadcast :D
sendBroadcast(intentBroadCast);
make changes like below code
private MyBroadCastReceiver myRecevier = new MyBroadCastReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Register the activity to the broadcast receiver
this.registerReceiver(myRecevier, new IntentFilter(MyBroadCastReceiver.ACTION));
Submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent frag=new Intent(MainActivity.this,Activity2.class);
//frag.putExtra("Limit", foo);
startActivity(frag);
// }
}
});
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
//Unregister the activity from the broadcast receiver. Good practice ;)
this.unregisterReceiver(myRecevier);
}
#Override
protected void onPause() {
super.onPause();
//Unregister the activity from the broadcast receiver. Good practice ;)
unregisterReceiver(myRecevier);
}
public class MyBroadCastReceiver extends BroadcastReceiver{
public static final String ACTION = "com.uberrueco.mybroadcastreceiver.receivers";
#Override
public void onReceive(Context context, Intent intent) {
Log.d("MyBroadCastReceiver", "received");
Toast.makeText(context,"Received "+intent.getStringExtra("editText"), Toast.LENGTH_LONG).show();
}
}
}
u need to use like this this.unregisterReceiver() and this.registerReceiver()
An activity instantiates a ResultReceiver and overrides onReceiveResult. The activity then sends an Intent to an IntentService and includes the ResultReceiver as an extra. Once the IntentService is finished processing it sends a message back to the ResultReceiver and processes it in onReceiveResult.
The issue is if the user navigates away from the Activity then the result is still sent back to the ResultReceiver which causes all types of issues. Is there not a way to stop this behavior? I've tried stopping the IntentService in the activity's onDestroy() but the result is still sent back.
Here is a sample Activity
public class Foo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = new Intent(this, SampleIntentService.class);
i.putExtra("receiver", mReceiver);
startService(i);
}
#Override
public void onDestroy() {
stopService(new Intent(this, SampleIntentService.class));
mReceiver = null;
super.onDestroy();
}
ResultReceiver mReceiver = new ResultReceiver(new Handler()) {
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Handle response from IntentService here
}
};
}
Here is a sample IntentService
public class SampleIntentService extends IntentService {
public SampleIntentService() {
super(SampleIntentService.class.getName());
}
#Override
protected void onHandleIntent(Intent intent) {
ResultReceiver rec = intent.getParcelableExtra("receiver");
if (rec != null) {
rec.send(200, null);
}
}
}
I solved this issue by creating a custom ResultReceiver as follows.
public class SampleResultReceiver extends ResultReceiver {
private Receiver mReceiver;
public SampleResultReceiver(Handler handler) {
super(handler);
}
public void setReceiver(Receiver receiver) {
mReceiver = receiver;
}
public interface Receiver {
void onReceiveResult(int resultCode, Bundle resultData);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (mReceiver != null) {
mReceiver.onReceiveResult(resultCode, resultData);
}
}
}
Then in my Activity I do the following:
public class Foo extends Activity implements Receiver {
private SampleResultReceiver mReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReceiver = new SampleResultReceiver(new Handler());
mReceiver.setReceiver(this);
Intent i = new Intent(this, SampleIntentService.class);
i.putExtra("receiver", mReceiver);
startService(i);
}
#Override
public void onDestroy() {
if (mReceiver != null) {
mReceiver.setReceiver(null);
}
super.onDestroy();
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Handle response from IntentService here
}
}
This will cause any messages sent to your custom ResultReceiver to end up nowhere after the Activity has been destroyed :)
I am trying to update the UI (Activity) after some action has been performed in the service. This is very simple example but it doesn't seem to work for me. What am I missing here?
ExampleService:
public class ExampleService extends IntentService{
#Override
protected void onHandleIntent(Intent intent) {
notifyActivity();
}
private void notifyActivity() {
Intent broadcast = new Intent(this, ExampleActivity.class);
sendBroadcast(broadcast);
}
}
ExampleActivity:
public class ExampleActivity extends ListActivity {
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
registerReceiver(receiver, filter);
}
}
You cannot send a broadcast to an anonymous dynamic receiver that way. You will need to define an action string in the Intent and use that action string in the IntentFilter.
You might consider using LocalBroadcastManager for this scenario, for better performance. Here is a sample project demonstrating this.