Broadcasting custom intent from one service to another - android

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)

Related

How to send Order broadcast receiver using pending intent android

Hi i have function like when user hit on notification i have to check my application is in foreground if it so, just close the notification. Otherwise need to open up the application.
I have use concept of ordered broadcast to achieve but i am stuck to call ordered broadcast receiver from pending intent.
To send an ordered broadcast using a PendingIntent, use one of the send() methods, for example this one, that takes a PendingIntent.OnFinished argument. This capability is not explicitly documented and only the description of the parametersto PendingIntent.OnFinished gives some hint that ordered broadcasts are supported.
Here is example for sending an ordered broadcast:
Intent i = new Intent("com.my.package.TEST_ACTION");
PendingIntent.OnFinished listener = new PendingIntent.OnFinished() {
#Override
public void onSendFinished(PendingIntent pendingIntent, Intent intent,
int resultCode, String resultData, Bundle resultExtras) {
Log.i("TEST", String.format("onSendFinished(): result=%d action=%s",
resultCode, intent.getAction()));
}
};
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
int initResult = -1;
try {
pi.send(initResult, listener, null);
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
I confirmed that this produces an ordered broadcast by defining a number of receivers with this general form, registered in the manifest with different priorities:
public class ReceiverA extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("AAAA", String.format("result=%d ordered=%b", getResultCode(), isOrderedBroadcast()));
setResultCode(1111);
}
}
The logcat output confirmed that the receivers were invoked in the expected order, that isOrderedBroadcast() is true for each, and the result code set by setResultCode() is passed to the next receiver, and finally to the PendingIntent.OnFinished callback.

Send integer value using Broadcast receiver in 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);
}

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

Android Broadcast from Service To Activity

I am trying to send a Broadcast from a service out to an Activity. I can verify the broadcast is sent from within the service, but the Activity doesn't pick up anything.
Here is the relevant service code:
Intent i = new Intent(NEW_MESSAGE);
i.putExtra(FriendInfo.USERNAME, StringUtils.parseBareAddress(message.getFrom()));
i.putExtra(FriendInfo.MESSAGE, message.getBody());
i.putExtra("who", "1");
sendBroadcast(i);
And the receiving end in the activity class:
public class newMessage extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if(action.equalsIgnoreCase(IMService.NEW_MESSAGE)){
Bundle extra = intent.getExtras();
String username = extra.getString(FriendInfo.USERNAME);
String message = extra.getString(FriendInfo.MESSAGE);
String who = extra.getString("who");
}
}
}
The BroadcastReceiver is defined within an Activity. I am registering the receiver in the onCreate method of the Activity, not in the Manifest file.
I'm stumped as to why it won't rec. anything.
Any insight?
EDIT
Registering takes place as follows:
registerReceiver(messageReceiver, new IntentFilter(IMService.NEW_MESSAGE));
Where "messageReceiver" is defined as
private newMessage messageReceiver = new newMessage();
IMService.NEW_MESSAGE is merely a string = "NewMessage"
I'm not sure if it is specific to the set up, or if it is a fix in general, but moving the register/unregister to the onResume/onPause _respectively_ and not registering in the onCreate solved the problem for me.
Try this two things:
Use manifest file to register receiver(but it barely helps)
Try make your Receiver a regular class, not inner one.
Inner class broadcast receiver will not be able to handle broadcast(means it unable to locate that class ).
So make it as a separate class
Definitely it will work.

Android-Broadcast Receiver

I am new to android. I what to know the difference between Intent and BroadcastReceiver. I am more confused with BroadcastReceiver than Intent.
Please help me out. Simple code will be helpful.
Ok, I will explain it with an example.
Let's suppose I want to create an app to check subway status from it's webpage. I also want a system notification if the subway is not working ok.
I will have:
An Activity to show results.
A Service to check if the subway is working and show a notification if it's not working.
A Broadcast Receiver called Alarm Receiver to call the service every 15 minutes.
Let me show you some code:
/* AlarmReceiver.java */
public class AlarmReceiver extends BroadcastReceiver {
public static final String ACTION_REFRESH_SUBWAY_ALARM =
"com.x.ACTION_REFRESH_SUBWAY_ALARM";
#Override
public void onReceive(Context context, Intent intent) {
Intent startIntent = new Intent(context, StatusService.class);
context.startService(startIntent);
}
}
Explanation:
As you can see you can set an alarm. and when the alarm is received we use an intent to start the service. Basically the intent is a msg which can have actions, an serialized stuff.
public class StatusService extends Service {
#Override
public void onCreate() {
super.onCreate();
mAlarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intentToFire = new Intent(AlarmReceiver.ACTION_REFRESH_ALARM);
mAlarmIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);
}
#Override
public void onStart(Intent intent, int arg1) {
super.onStart(intent, arg1);
Log.d(TAG, "SERVICE STARTED");
setAlarm();
Log.d(TAG, "Performing update!");
new SubwayAsyncTask().execute();
stopSelf();
}
private void setAlarm() {
int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
mAlarms.setInexactRepeating(alarmType, SystemClock.elapsedRealtime() + timeToRefresh(),
AlarmManager.INTERVAL_HALF_DAY, mAlarmIntent);
}
}
Explanation:
The service starts and:
Set the alarm for the next call. (Check the intent it's used. Just a msg)
Calls an AsyncTask which takes care of updating an notifying the Activity
It doesn't make sense to paste the AsyncTask but when it finished it calls:
private void sendSubwayUpdates(LinkedList<Subway> subways) {
Intent intent = new Intent(NEW_SUBWAYS_STATUS);
intent.putExtra("subways", subways);
sendBroadcast(intent);
}
This creates a new Intent with a certain NEW_SUBWAYS_STATUS action, put inside the intent the subways and sendBroadcast. If someone is interested in getting that info, it will have a receiver.
I hope I made myself clear.
PS: Some days ago someone explained broadcast and intents in a very cool way.
Someone wants to share his beer, so he sends a broadcast
with an intent having action:"FREE_BEER" and with an extra: "A glass of beer".
The API states:
A BroadcastReceiver is a base class for code that will receive intents sent by sendBroadcast().
An intent is an abstract description of an operation to be performed.
So, a BroadcastReceiver is just an Activity that responds to Intents. You can send your own broadcasts or even the Android Device can send these system wide broadcasts including things like the battery is low, or the device just booted-up.

Categories

Resources