LocalBroadcastManager not working - android

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

Related

BroadcastReceiver onReceive() not working

I don't understand why the onReceive method is never called. I've followed all the examples online, and I've looked through many similar questions on this site. Any ideas? Have I missed something?
public class MainActivity extends Activity {
public BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Receiver", "Receiving message");
String action = intent.getAction();
String message;
if (action.equals(BUTTON_ACTION)) {
message = intent.getStringExtra("BUTTON");
Log.d("R", message);
}
}
};
String BUTTON_ACTION = "button";
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver,
new IntentFilter(BUTTON_ACTION));
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
}
At this point, I get the log when the button is pressed. But the onReceive method is never reached in my receiver.
public void button1(View view) {
Log.d("sender", "Broadcasting message");
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(BUTTON_ACTION).addCategory("Button Press")
.putExtra("BUTTON", "Button 1 has been pressed.").addFlags(Intent.));
LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);
}
}
Looks like you're sending the broadcast intent with a category set, but your BroadcastReceiver isn't set up to handle a category. If you remove the category from the broadcast intent (or add it to the IntentFilter), that may fix it for you.
From the docs:
Note that unlike the action, an IntentFilter with no categories will only match an Intent that does not have any categories.
(http://developer.android.com/reference/android/content/IntentFilter.html)

sending intent extras from service to activity

I have a service that listens for (ON_BATTERY_CHANGE), then onReceive service sends a Broadcast to My MainActivity. The problem is that I somehow can't get them from service to my main activity. Code: Main Activity:
public class MainActivity extends Activity
private BroadcastReceiver batteryReceiverService;
private TextView text2;
....
protected void onCreate(Bundle savedInstanceState) {
text2=(TextView)findViewById(R.id.TV_text2);
batteryReceiverService = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
text2.setText("left: "+intent.getStringExtra("H")+" hours "+intent.getStringExtra("M")+" minute(s)");
Log.e("text2","text2 HHH " +intent.getStringExtra("H")); //log shows 0
Log.e("text2","text2 MMM " +intent.getStringExtra("H")); // log shows 0
}
};
registerReceiver(batteryReceiverService, new IntentFilter(UltimateBatterySaverService.BROADCAST_ACTION));
....
#Override
protected void onDestroy() {
unregisterReceiver(batteryReceiverService);
super.onDestroy();
}
Service:
public class UltimateBatterySaverService extends Service {
private Intent intent;
static final String BROADCAST_ACTION = "lt.whitegroup.ultimatebatterysaver";
private BroadcastReceiver batteryLevelReceiver;
....
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onDestroy() {
unregisterReceiver(batteryLevelReceiver);
super.onDestroy();
}
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryLevelReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent){
// Receiving data, calculating and etc
averageChargingH=timeAllInHours;
averageChargingM=timeAllInMinutes;
// to put extras and send broadcast
does();
......
public void does(){
String strLong = Long.toString(averageChargingH);
String strLong2 = Long.toString(averageChargingM);
Log.e("cccccc","strLong h "+strLong); // getting good value not 0(everything ok)
Log.e("cccccc","strLong2 m"+strLong2); // getting good value not 0(everything ok)
intent.putExtra("H", strLong);
intent.putExtra("M", strLong2);
sendBroadcast(intent);
}
Any ideas why my information is not transfered correctly?
The does() method seems to be using variables in the same scope as onReceive so I'm guessing that the intent variable in does() is actually the Intent passed in from onReceive.
Try adding some logging before sending the broadcast to check if the action of the intent is correct, or simply create the broadcast intent in the onReceive method and name it intent2.

Use IntentFiler in onPause()

I want to start my Application (ex update my TextView) after press back button. But it didn't work. Please help me.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intentFilter = new IntentFilter();
intentFilter.addAction("SMS_RECEIVED_ACTION");
registerReceiver(intentReceiver, intentFilter);
}
protected void onPause() {
registerReceiver(intentReceiver, intentFilter);
super.onPause();
}
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
sendSMS("123","message");
}
};
I have updated your code try this and if any problem is there then ask me. I will try to help you ..
#Override
public void onBackPressed() {
// FOR UPDATING YOUR TEXT VIEW.
Intent broadcast_intent = new Intent("SMS_RECEIVED_ACTION");
broadcast_intent.putExtra("number", textview_value_to_set);
sendBroadcast(broadcast_intent);
// // FOR STARTING YOUR NEW ACTIVITY.
Intent intent = new Intent(getApplicationContext(), class_name.class);
startActivity(intent);
super.onBackPressed();
}
Use this as your broadcast receiver. Dont forget to register reciever.
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("SMS_RECEIVED_ACTION")) {
TextView text = (TextView)findViewById(R.id.text);
text.setText(intent.getExtras().getString("number"));
}
}
};

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