Android BroadCastReceiver refresh all activities - android

I have an issue using BroadCastreceiver to refresh activities in my application. I'm using a service which is doing some calculations and in onDestroy() method I'm doing this :
#Override
public void onDestroy(){
super.onDestroy();
Intent intent = new Intent("finish");
this.sendBroadcast(intent);
}
and in my activities I'm doing this :
receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("finish")) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
Intent previewMessage = new Intent(Tutorial.this, Tutorial.class);
parentActivity.startChildActivity("Tutorial", previewMessage);
progressBar.setVisibility(View.GONE);
sync.setImageResource(R.drawable.sync_icon2);
final SharedPreferences isLogged = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = isLogged.edit();
editor.putBoolean("getProgBar", false);
editor.commit();
}
}
};
registerReceiver(receiver, new IntentFilter("finish"));
I have that function in all my activities and the problem is that if I change 2-3 of them before my service stop, after that I can see in my LogCat logs from other activities which has that function too, but I'm not currently on these activities. They are just somewhere in activity stack. But the thing that I can't understand is it reloading them (even if I can't see it visually) and how to prevent this kind of issues. I need to refresh only activity which I'm in.
Thanks!

Just add these to your activities. You have to unregister your broadcastreceiver and register it again in your onResume() like this :
#Override
public void onPause(){
super.onPause();
YourActivity.this.unregisterReceiver(receiver);
}
#Override
public void onResume(){
super.onResume();
IntentFilter intentFilter = new IntentFilter("com.example.MyService");
YourActivity.this.registerReceiver(receiver, intentFilter);
}

Related

Broadcast Receiver null pointer Android

I keep getting the following error:
> java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.BroadcastReceiver.onReceive(android.content.Context, android.content.Intent)' on a null object reference
When I try to receive a broadcast from my service class.
Service:
#Override
public void onDestroy(){
super.onDestroy();
Intent intent = new Intent("UpdateLocation");
intent.putExtra("Location",journ);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
That is the code to send the broadcast sending a custom object(Journ) to my main activity.
Main:
#Override
protected void onCreate(Bundle savedInstanceState)
LocalBroadcastManager.getInstance(this).registerReceiver(
mReceiver, new IntentFilter("UpdateLocation"));
//Listen for service to send location data
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
temp= intent.getExtras().getParcelable("Location");
}
};
}
#Override
public void onPause() {
if (!tracking) {
finish();
}
//Run service in background to keep track of location
startService(new Intent(this, locationService.class));
super.onPause();
}
#Override
public void onResume() {
if (!tracking) {
return;
}
if (mGoogleApiClient != null) {
//Reconnect to google maps
mGoogleApiClient.reconnect();
}
stopService(new Intent(this, locationService.class));
super.onResume();
}
I am not sure how to go about doing this, I am trying to pass the object from my service class which runs when my app is in the background and when it resumes the service should stop and sends the data it gathered to my main activity.
This, however, doesn't work, any ideas?
In case people were wondering my on create method does contain more code, but I didn't think it necessary to include.
In onCreate mReciever is a null object (if you didn't assign it earlier), so you should assign it before registering a receiver.
Change this part:
if (mReceiver == null) {
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
temp= intent.getExtras().getParcelable("Location");
}
};
}
//Listen for service to send location data
LocalBroadcastManager.getInstance(this)
.registerReceiver(mReceiver, new IntentFilter("UpdateLocation"));

Android:How to send data Activity to Fragment using BroadcastReceiver

Send data from Activity to Fragment in Android using BroadcastReceiver. I know there is varies way to communicate Activity to Fragment.
But i don't know how to send data and receive using BroadcastReceiver.
From your Activity
Intent intent = new Intent("KEY");
sendBroadcast(intent);
In your fragment
private BroadcastReceiver mNotificationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUi();
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(mNotificationReceiver, new IntentFilter("KEY"));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mNotificationReceiver);
}

LocalBroadcastManager not working

I'm trying to sendMessage from service to activity, but for some reason it's not working.
Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
Boolean state = intent.getBooleanExtra("state",false);
if(state){
Toast.makeText(getApplicationContext(),"Данные успешно отправлены",Toast.LENGTH_SHORT).show();
}
}
};
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
Service
private void sendMessage(boolean state) {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("state", state);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
Log.d "broadcasting message" is shown and then nothing happens
PROBLEM SOLVED
In android manifest
<service
android:name=".service.TerminalService"
android:process=":update_service" >
</service>
It seems when android:process is specified localbroadcastmanager is not working. I just deleted android:process line and it worked
Nothing wrong with your code .only update your receive method else clause
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
Boolean state = intent.getBooleanExtra("state",false);
if(state){
Toast.makeText(getApplicationContext(),"Данные успешно отправлены",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(),"else message ",Toast.LENGTH_SHORT).show();
}
}
};
com.android.support:localbroadcastmanager -> change
androidx.localbroadcastmanager:localbroadcastmanager:1.0.0

Dynamically register/unregister a broadcast receiver in android

I want to dynamically register and unregister my receiver class with the broadcast:
"android.net.wifi.STATE_CHANGE"
This works very well if I do this in the manifest. But this makes it static. I want to do it dynamically in the activity class. What is its correspondent command in the activity class?
This is what my code is...
and I am getting a problem because of registering and unregistering(multiple times) my receiver(which is starting a service).
public class startScreen extends Activity {
/** Called when the activity is first created. */
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.example.MyService");
context.startService(serviceIntent);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.initial);
final IntentFilter filter = new IntentFilter();
filter.addAction("android.net.wifi.STATE_CHANGE");
Button button = (Button) findViewById(R.id.button1);
final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
try {
...some code...
if (bool == true) {
toggleButton.setChecked(true);
this.registerReceiver(receiver, filter);
} else
toggleButton.setChecked(false);
} catch (Exception e) {
Log.e("Error", "Database", e);
} finally {
...
}
toggleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((toggleButton.isChecked())) {
getBaseContext().registerReceiver(receiver, filter);
} else {
if (receiver != null) {
getBaseContext().unregisterReceiver(receiver);
receiver = null;
}
}
}
});
}
#Override
protected void onResume() {
super.onResume();
if (bool == true) {
if (receiver == null)
this.registerReceiver(receiver, filter);
}
}
#Override
protected void onPause() {
super.onPause();
if (receiver != null) {
this.unregisterReceiver(receiver);
receiver = null;
}
}
}
The LocalBroadcastManager class is used to register for and send broadcasts of Intents to local objects within your process. This is faster and more secure as your events don't leave your application.
The following example shows an activity which registers for a customer event called my-event.
#Override
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));
}
// handler for received Intents for the "my-event" event
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onPause() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
// This method is assigned to button in the layout
// via the onClick property
public void onClick(View view) {
sendMessage();
}
// Send an Intent with an action named "my-event".
private void sendMessage() {
Intent intent = new Intent("my-event");
// add data
intent.putExtra("message", "data");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
use the below methods to register/unregister your receiver:
registerReceiver(BroadcastReceiver receiver, new IntentFilter("android.net.wifi.STATE_CHANGE"));
unregisterReceiver(BroadcastReceiver receiver);
For reference have a look at this
Don't add dynamic broadcast receiver in onReceive on broadcast file. Add it on first activity or main activity of your application. If you needed it only when your application is open. But if you need it always received response just added it on manifest file
Register dynamic broadcast receiver on main activity
MyReceiver reciver;
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
intentFilter.addAction("android.net.wifi.STATE_CHANGE");
reciver = new MyReceiver();
registerReceiver(reciver, intentFilter);
}
Unregister that broadcast receiver on activity stop or closed
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(reciver);
}
Perhaps I'm a bit too late, but the problem lies on the fact that you are setting the receiver = null in your onPause method, and then never setting it again. You are also trying to register it in your onResume method but only if it is null, which makes no sense too.
You should change the logic where you set/test the null value of the receiver, to instead just use a boolean variable to keep track of the receiver status (if it's registered or not).
public void registerBroadcastReceiver(View view) {
this.registerReceiver(broadCastReceiver, new IntentFilter(
"android.intent.action.TIME_TICK"));
}
public void unregisterBroadcastReceiver(View view) {
this.unregisterReceiver(broadCastReceiver);
}

Change Activity behaviour when C2DM Push notification is received

I have a working server/client solution that sends push notification to my device. The next step for my project would be to show a dialog on the activity window when the onReceive event is called in the C2DMReceiver class.
As I am new to android, I have no idea how to do this, so I would be really happy if someone could explain this to me.
Basically I reused the classes from the chrometophone Application for c2dm. The onReceive event is called, as I create a log entry for logcat. As the C2DMReceiver is a service, how to I get informed on my activity if there is a new message?
I googled a lot but couldn't find a working solution... I tried to use the registerReceiver() but I'm pretty sure I did it wrong. Does anyone have an example?
Ok, so here is what I got so far:
Activity
BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.w(Consts.LOG_TAG_SERVICE, "Test");
}
};
// Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.w(Consts.LOG_TAG_SERVICE, "started");
}
// Called when the activity is restarted
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addCategory("com.mydomain.myapp.CONTEXT");
registerReceiver(mReceiver, filter);
}
// Called when the activity is closed
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
C2DMReceiver
public class C2DMReceiver extends C2DMBaseReceiver {
public C2DMReceiver() {
super("my_test#gmail.com");
// TODO Load dynamic Gmail address
}
#Override
public void onRegistrered(Context context, String registrationId) {
Log.i(Consts.LOG_TAG_SERVICE, registrationId);
// Store the registration id in the preferences
SharedPreferences settings = Prefs.get(context);
SharedPreferences.Editor editor = settings.edit();
editor.putString("deviceRegistrationID", registrationId);
editor.commit();
// TODO: Send ID to server
}
#Override
public void onUnregistered(Context context) {
Log.w(Consts.LOG_TAG_SERVICE, "got here!");
}
#Override
public void onError(Context context, String errorId) {
Log.w(Consts.LOG_TAG_SERVICE, errorId);
}
#Override
protected void onMessage(Context context, Intent intent) {
Log.w(Consts.LOG_TAG_SERVICE, "C2DMReceiver: " + intent.getStringExtra("payload"));
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.mydomain.myapp.NEWMESSAGE");
broadcastIntent.putExtra("reading", intent.getStringExtra("payload"));
broadcastIntent.addCategory("com.mydomain.myapp.CONTEXT");
context.sendBroadcast(broadcastIntent);
}
}
This is all I got, but I never receive my own broadcast.. Does anyone have some inputs?
This should do it.
#Override
protected void onMessage(Context context, Intent intent) {
Log.w(Consts.LOG_TAG_SERVICE, "C2DMReceiver: " + intent.getStringExtra("payload"));
Intent i = new Intent(context, YourMainActivity.class);
i.putExtra("reading", intent.getStringExtra("payload"));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
You then handle the intent in your onStart in your main activity. If your activity is already running, it will be handled by the existing instance, if not, a new instance will be started.

Categories

Resources