Passing a string from an activity to a broadcast receiver - android

I am having a problem while passing a string from my main activity to my broadcast receiver when the app is not currently open on the screen.
When the MainActivity class is created the intent filter returns the correct information through the broadcast receiver but as soon as the user goes to the homescreen on their phone the broadcast receiver starts returning "null" for the toast when the receiver is triggered offscreen.
1. New Intent
Intent home_page = new Intent(newIntent.this,MainActivity.class);
ownAddress = ""+customInput.getText().toString();
home_page.putExtra("session_number", ""+ownAddress);
startActivity(home_page);
2. MainActivity.java:
public class MainActivity extends DroidGap {
SmsReceiver mAppReceiver = new SmsReceiver();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
final String ownAddress = bundle.getString("session_number");
registerReceiver(mAppReceiver, new IntentFilter("SmsReceiver"));
Intent intent = new Intent("SmsReceiver");
intent.putExtra("passAddress", ownAddress);
sendBroadcast(intent);
}
}
3. SmsReceiver.java:
public class SmsReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Toast showme = Toast.makeText(context,"Number: "+intent.getExtras().get("passAddress"),Toast.LENGTH_LONG);
showme.show();
}
}
Is there anyway to pass the string through to the broadcast receiver while the app is only running in the background or regardless of when the MainActivity class is created?

I may be wrong here but, logically, the reason why "the broadcast receiver starts returning "null" for the toast when the receiver is triggered offscreen" is because the context that you pass to the onReceive constructor is destroyed when the user goes to the homescreen.
I guess one solution for passing the string would be to create a public static string variable in MainActivity which is used to store the string value you want to pass. Then all you have to do is access this string statically in your BroadcastReceiver.

Related

onReceive called even when Broadcast not sent [duplicate]

I have a registered BroadcastReceiver in my main activity. Activity sends a sticky in one of the tabs to trigger the broadcast receiver (TabActivity application).
Everything works fine, but when I restart the app the sticky is sent automatically (not triggered by user) and view is opened.
My question is: how is that possible? Did I misunderstand something? And how can I fix that?
MainActivity:
OnCreate:
registerReceiver(openOutgoingCall, new IntentFilter("OPENOUTGOINGCALL"));
BroadcastReceiver:
private BroadcastReceiver openOutgoingCall = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if(extras.isEmpty() == false) {
HashMap<String,String> callData = (HashMap<String, String>) extras.get("callData");
openOutgoingCall(callData);
}
}
};
Activity inside TabHost
public void openCall(View view) {
Intent i = new Intent("OPENOUTGOINGCALL");
i.putExtra("callData", detailInfo);
sendStickyBroadcast(i);
}
Sticky broadcasts are supposed to stay around (even they are received) so that they can be retrieved afterwards too. Perhaps you should try the simple way of broadcasting using:
sendBroadcast(i);
Read this.

BroadcastReceiver receives more Intents than sent

I have next problem:
I create a custom BroadcastReceiver and register it in main activity onCreate handler:
public class MainActivity extends ListActivity {
private static final LogReceiver logReceiver = new LogReceiver();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(this).registerReceiver(logReceiver, new IntentFilter(LogReceiver.ACTION_LOG));
}
...
}
BroadcastReceiver class:
public class LogReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("intent", "intent <-");
}
}
Then I send multiple Intents from a local service using next code:
Intent intent = new Intent(LogReceiver.ACTION_LOG).putExtra("log", logString);
localBroadcastManager.sendBroadcast(intent);
Log.i("intent", "intent ->");
The log looks very strange for me:
intent ->
intent <-
intent ->
intent <-
intent <-
intent ->
intent <-
intent <-
intent <-
...
The 1st time LogReceiver receives only one Intent and this is correct but each next time it receives more equal Intents than sent.
I can switch from Intent approach in my project but just interesting why this happens?
You should deregister the receiver in the onDestroy of the Activity.
Additionally you should check if this receiver really has to be static.
If you need the receiver throughout the application it should be saved in a separate singleton class or in a custom Application class instead of one Activity.
You could then register the receiver in the first started Activity. But you should make sure it is registered only once for example by storing a boolean registered into the receiver that is checked before registering at the LocalBroadcastManager.

Broadcast receiver is triggered automatically on start

I have a registered BroadcastReceiver in my main activity. Activity sends a sticky in one of the tabs to trigger the broadcast receiver (TabActivity application).
Everything works fine, but when I restart the app the sticky is sent automatically (not triggered by user) and view is opened.
My question is: how is that possible? Did I misunderstand something? And how can I fix that?
MainActivity:
OnCreate:
registerReceiver(openOutgoingCall, new IntentFilter("OPENOUTGOINGCALL"));
BroadcastReceiver:
private BroadcastReceiver openOutgoingCall = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if(extras.isEmpty() == false) {
HashMap<String,String> callData = (HashMap<String, String>) extras.get("callData");
openOutgoingCall(callData);
}
}
};
Activity inside TabHost
public void openCall(View view) {
Intent i = new Intent("OPENOUTGOINGCALL");
i.putExtra("callData", detailInfo);
sendStickyBroadcast(i);
}
Sticky broadcasts are supposed to stay around (even they are received) so that they can be retrieved afterwards too. Perhaps you should try the simple way of broadcasting using:
sendBroadcast(i);
Read this.

Passing Data from Broadcast Receiver to another Activity

Hi I've been having an issue with Broadcast Receivers and passing information to another activity. I'm trying to create an application that will capture incoming SMS messages, look for a website in the text, then pop up an Alert Dialog box asking if the user wants to go to the website.
public class TextReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent)
{
// .. other code that
// sets received SMS into message
Toast toast = Toast.makeText(context,
"Received Text: " + message.getMessageBody(), Toast.LENGTH_LONG);
toast.show();
}
So that code works fine, receive a text it pops up a toast with the message. The toast is useless but it shows the receiver works. But I want to communicate with an activity to show an Alert Dialog and start up a webView. I already programmed the code that will take a string search for the website and open the webView. Is it possible to get the string from the broadcast receiver and do something like this?:
public class ReceiveText extends Activity{
public void onCreate(Bundle savedInstanceState) {
// Somehow pass the string from the receiver into this activity,
//stored in variable messages
findOpen(messages);
// is that possible?
}
public class findOpen(string messages){
// do stuff ... open alert...open site if OK
}
So basically I just want to pass a string from a Broadcast Receiver to another activity that will use that string. The rest of the code is basically in place all I need is that string... I'm new to this and Java and any help would be much appreciated. Thanks
Instantiate a BroadcastReceiver in the activity you want to get your data to, for example:
private BroadcastReceiver mServiceReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent)
{
//Extract your data - better to use constants...
String IncomingSms=intent.getStringExtra("incomingSms");//
String phoneNumber=intent.getStringExtra("incomingPhoneNumber");
}
};
Unregister your receiver on onPause():
#Override
protected void onPause() {
super.onPause();
try {
if(mServiceReceiver != null){
unregisterReceiver(mServiceReceiver);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Register it on onResume():
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.SmsReceiver");
registerReceiver(mServiceReceiver , filter);
}
Broadcast your data from the service via an Intent, for Example:
Intent i = new Intent("android.intent.action.SmsReceiver").putExtra("incomingSms", message);
i.putExtra("incomingPhoneNumber", phoneNumber);
context.sendBroadcast(i);
and that's it! goodLuck!
If you have your activity named ReceiveText, then in your BroadcastReceiver, you should do the following:
Intent i = new Intent(context, ReceiveText.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("message", message.getMessageBody());
context.startActivity(i);
Then, in your activity, you will need to getExtra as so:
Intent intent = getIntent();
String message = intent.getStringExtra("message");
And then you will use message as you need.
If you simply want the ReceiveText activity to show the message as a dialog, declare <activity android:theme="#android:style/Theme.Dialog" /> in your manifest for ReceiveText and then set the message to a textview in the activity.
EDIT: This restarts your activity. this answer is likely a better solution for most people.
We can send the data from onReceive to another activity using LocalBroadcastManager.
It means you are again broadcasting the data using the context
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Broadcast", "wifi ConnectivityReceiver");
Bundle extras = intent.getExtras();
Intent intent = new Intent("broadCastName");
// Data you need to pass to another activity
intent .putExtra("message", extras.getString(Config.MESSAGE_KEY));
context.sendBroadcast(intent );
}

How to send data to a running activity from Broadcast Receiver,

I am able to receive C2DM message fine but I want to send the data to a running activity, i.e when the activity is running, if the receiver receives C2DM message it is to send the data to the running activity. The code of receiver is (no bugs in the code):
public class C2dmreceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.w("C2DM", "Message Receiver called");
if ("com.google.android.c2dm.intent.RECEIVE".equals(action))
{
final String payload = intent.getStringExtra("key1");
Log.d("C2DM", "message = " + payload );
}
}}
I have tried like this inside the activity in an attempt to register the receiver in the activity so that the receiver can send data and the running activity can receive the data :-
C2dmreceiver c2dmr = new C2dmreceiver();
Registration.this.registerReceiver(c2dmr, new IntentFilter());
I don't know what to put inside the IntentFilter(), also what else I have to put in the code of the activity and the code of the receiver so that while the activity is running and some C2DM message comes the receiver can send the data to the running activity.
So, please tell me the code that is to put in the activity and in the receiver and may also be in the manifest so that the data from the receiver could be send to running activity.
Any advice is highly appreciated.
First of all it's not the best idea to subscribe c2dm receiver in activity. Do it in manifest. For passing data to activity you can create static string field in Activity and set you String there.
You can do something like this:
in Activity
public static YourActivity mThis = null;
#Override
protected void onResume() {
super.onResume();
mThis = this;
}
#Override
protected void onPause() {
super.onPause();
mThis = null;
}
In your BroadcastReceiver:
#Override
public void onReceive(Context context, Intent intent) {
...
if (YourActivity.mThis != null) {
((TextView)YourActivity.mThis.findViewById(R.id.text)).setText("received c2dm");
}
else {
...
}

Categories

Resources