Send integer value using Broadcast receiver in Android - android

How to pass a integer value from Service class using a Broadcast intent to a Activity. Below is my code but getting some errors,
Sending side
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
int dataJNI = BioLIb.intFromJNI();
intent.putExtra("mykey", dataJNI);
sendBroadcast(intent);
}
Receiving side
private Intent intent;
the above is a global variable. In my onCreate I will call BroadcastReceiver class like below.
intent = new Intent(this, BroadCastService.class);
onReceive of BroadcastReceiver i will call
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
int time = intent.getINtExtra("mykey", 1);
But I am not getting my exact value of dataJNI in a receiving side. I am always getting value is 1, How to get resolve this.

When you're sending you're putting an integer into the Intent Bundle. When receiving you0re trying to extract a long. Did you try using the same type in both sides?

use the intent that you received as a parameter of onReceive method
int time;
public void onReceive(Context context, Intent intent) {
updateUI(intent);
time = intent.getLongExtra("mykey", 1);
}

Related

How to send data from 1 app to another in android

I have 2 app, A and B, and i want send 2+2 from application A to B and in return i want to receive 4 from App B, please tell me the process and full code base.
1.From app A Trigger a broadCast1 with both of your numbers.
Intent intent = new Intent("com.myapps.appA");
intent.putExtra("num1",2);
intent.putExtra("num2",2);
sendBroadcast(intent);
now register the receiver for broadCast1 in App B, you can do this in onCreate of its Main activity.
private BroadcastReceiver broadcastReceiver1;
...
broadcastReceiver1 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
registerReceiver(broadcastReceiver1, new
IntentFilter("com.myapps.appA");
Inside onRecieve get both the numbers from the intent and Trigger another broadCast with the result i.e.
int num1 = intent.getIntExtra("num1",0);
int num2 = intent.getIntExtra("num2",0);
Intent intent2 = new Intent("com.myapps.appB");
intent2.putExtra("sum",num1+num2);
YourActivity.this.sendBroadcast(intent2);
Now Register the reciever for Broadcast2 Inside your App A, you can do this in onCreate of its Main activity.
private BroadcastReceiver broadcastReceiver2;
...
broadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
registerReceiver(broadcastReceiver2, new
IntentFilter("com.myapps.appB");
Inside its OnRecive() get the result
int sum = intent.getIntExtra("sum",0);
Most importantly don't forget to unregister the receivers in onStop on the activity

Broadcasting custom intent from one service to another

I have two services. I need to broadcast custom intent with data from one service. and in second service I need to receive it. I have tried following:
In first service:
public String ACTION_CHANGE_TIME_FORMAT = "com.example.agile.mywatchface.changetimeformat";
Intent timeFormatIntent = new Intent();
timeFormatIntent.putExtra("format", 12);
timeFormatIntent.setAction(ACTION_CHANGE_TIME_FORMAT);
LocalBroadcastManager.getInstance(this).sendBroadcast(timeFormatIntent);
In Second Service:
public String ACTION_CHANGE_TIME_FORMAT = "com.example.agile.mywatchface.changetimeformat";
public class TimeFormatReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Log.d(MyPreferences.LOGCAT_TAG, "Time format Broadcast received: ");
format = intent.getExtras().getInt("format", 0);
updateTime();
}
}
and I have registered and unregistered receivers properly in second service:
IntentFilter timeFormatIntentFilter = new IntentFilter();
timeFormatIntentFilter.addAction(ACTION_CHANGE_TIME_FORMAT);
MyWatchfaceService.this.registerReceiver(timeFormatReceiver, timeFormatIntentFilter);
Is there anything wrong here? I can't get data(format).
Edit: onRecieve() is not calling.
In Second Service:
Change format = intent.getExtras().getInt("format", 0); to format = intent.getIntExtra("format", 0);
The intent.getExtras() will return the Bundle which put by Intent.putExtras(Bundle bundle), but you didn't do it.
1_ Check that your onReceive() method is called. If not, your Receiver still does not registered.
2_ if (1) is OK, try int format = intent.getIntExtra("format", 0);
P/S: I dont know where do you use the "format" variable, consider use it as local variable and pass it like a parameter.
int format = intent.getIntExtra("format", 0);
updateTime(format)

Not receiving Extras from sendBroadcast

I have a MainClass that registers a BroadcastReceiver and overrides its onReceive() method
BroadcastReceiver broadcastReceiver=new BroadcastReceiver(){
#Override
public void onReceive(Context context,Intent intent){
Log.w("MyApp","RICEVUTO MESSAGGIO BROADCAST: "+intent.getStringExtra("com.example.avis.NUOVANEWS"));
Log.w("MyApp","Intent TOSTRING "+intent.toString());
}
};
this.getApplicationContext().registerReceiver(broadcastReceiver, new IntentFilter("nuovanewsavis"));
In the class NewsService, when a new news is found, i broadcast a new message. Here's the code
Intent intento=new Intent("nuovanewsavis");
intent.setAction("nuovanewsavis");
intent.putExtra("com.example.avis.NUOVANEWS", "Nuova notizia");
this.sendBroadcast(intento);
The MainClass cannot get the extra: if i try to read it through getStringExtra i get a null.
Am i doing something wrong?
I think there has a typo...your using intent instead of intento when putting extra.
Intent intento = new Intent("nuovanewsavis");
intento.setAction("nuovanewsavis");
intento.putExtra("com.example.avis.NUOVANEWS", "Nuova notizia");
this.sendBroadcast(intento);

Multiple custom broadcasting (how to handle)

I want to add a custom broadcast receiver to my app. and I have 3 methods that should do the broadcast. and in my onReceive method i want to identify which method did the broadcast. I have 3 methods like this
public void method01(View v){
int flag = 1;
Intent intent = new Intent();
intent.addFlags(flag);
broadcastIntent(intent);
}
public void method02(){
int flag = 2;
Intent intent = new Intent();
intent.addFlags(flag);
broadcastIntent(intent);
}
public void method03(){
int flag = 3;
Intent intent = new Intent();
intent.addFlags(flag);
broadcastIntent(intent);
}
and this is my broadcastIntent method
public void broadcastIntent(Intent intent){
sendBroadcast(intent);
}
in my onReceive method i use getFlags() method to get the flag value from the intent and send it through a if, else. but this do not work. any suggestion for improvements are welcome.
You can also use Actions to identify each one of you Intent objects.
String action1 = "first_sender";
String action2 = "second_sender";
Intent createIntent01(){
Intent intent01 = new Intent();
intent01.setAction(action1);
return intent01;
}
Intent createIntent02(){
Intent intent02 = new Intent();
intent01.setAction(action2);
return intent02;
}
And in your onReceive method you can use the getAction() method of intents to check which action was sent. This is in case you're not already using Actions.
[[EDIT]]
To register a BroadcastReceiver you need to define an IntentFilter and register the actions you wish to receive this way:
mBroadcastReceiver broadcastReceiver = new mBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(action1);
intentFilter.addAction(action2);
registerReceiver(broadcastReceiver,intentFilter);
class mBroadcastReceiver extends BroadcastReceiver{
public void onReceive(Context arg0, Intent arg1){
String action = arg1.getAction();
if(action.equals(action1)){
//do something
}else if(action.equals(action2)){
//do something else
}
}
The first problem is that ypu didn't specify a target for your intent. You can use intent filters and actions like rodkarom suggested or specify receiver's class directly (see in my example). In both cases you need either to declare your broadcast receiver in AndroidManifest.xml, or register it at runtime (see rodkarom's answer for a sample).
The method addFlags is used to specify some internal properties of Intent (like start activity corresponding to this intent in a new task) , so you cannot use it for your own data. The list of possible flags is in the documentation for setFlags method.
You can use putExtra to achieve your goal:
// an Activity is just an example
public class SenderActivity extends Activity {
// ...
void method01() {
int flag = 1;
Intent intent = new Intent(getApplicationContext(), Receiver.class); // any Context is acceptable here
intent.putExtra(MyReceiver.EXTRA_FLAG, flag); // any string will do well, you just need it to be the same here and in getExtra later
sendBroadcast(intent);
}
}
public class MyReceiver extends BroadcastReceiver {
public static final String EXTRA_FLAG = "your.package.name.EXTRA_FLAG";
// and in onReceive
public void onReceive (Context context, Intent intent) {
int flag = intent.getIntExtra(EXTRA_FLAG, someDefaultValue);
if (flag == 1) {
// ...
}
// ...
}
}
I found out the way to this and thought of sharing the code. this is the broadcasting done in my main activity for 2 different methods.
public void method1(View view){
Intent intent = new Intent();
intent.setAction("method1");
sendBroadcast(intent);
}
public void method2(View view){
Intent intent = new Intent();
intent.setAction("method2");
sendBroadcast(intent);
}
and this is how i receive it..
public class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Broadcast Intent Detected.",Toast.LENGTH_LONG).show();
}
this is how i registered it on manifest.
<receiver android:name="Receiver" >
<intent-filter>
<action android:name="method1" >
</action>
<action android:name="method2" >
</action>
</intent-filter>
</receiver>
Hope this will help if any one else came up with similar problem. and big thank you to every one who posted their answers here.

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 );
}

Categories

Resources