What’s the difference between an intent used for startActivity() and an intent used for the sendBroadcast() method? In a tutorial, I found an way for dynamically registering a broadcast receiver. For this purpose, I had to provide a string as my intent name. How to choose an intent name in this case and use for sendBroadcast() or registerReceiver()?
Should I add something to my android_manifest.xml file? according to the tutorial, I have currently declared an intent name like this:
private static final String SEARCH_ACTION = "com.example.usingwebservices.rest.SEARCH";
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
registerReceiver(receiver, new IntentFilter(SEARCH_ACTION));
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(progress!=null){
progress.dismiss();
}
String response = intent.getStringExtra(RestTask.HTTP_RESPONSE);
result.setText(response);
}
};
I think you do right thing. there are two methods to register receiver, following enter link description here:
You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the <receiver> tag in your AndroidManifest.xml.
and the message to queue in service maybe like :
Intent i = new Intent("com.example.usingwebservices.rest.SEARCH");
i.putExtra(RestTask.HTTP_RESPONSE, "msgdetails");
context.sendBroadcast(i);
the intent's contruction ,the parameter is an action name:
Intent(String action)
and when used startActivity, the contruction I used:
Intent(Context packageContext, Class<?> cls)
you can see reference of Intent following here:
and I think Google want package the most msg format .
Related
For this code, as I'm using LocalBroadcastManager:
LocalBroadcastManager.getInstance(this).registerReceiver(mMessage, new IntentFilter("timer"));
mMessage = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
int t = intent.getIntExtra("time", 0);
tv.setText(t+"");
}
};
No, You do not need to define it in manifest.xml file. It is a good practice and recommended that you register your Receiver in onResume() method and also unregister it by calling unregisterReceiver method in onPause() method of your activity.
No need to register the receiver in the Manifest file.
Register the receiver in the onResume() method by calling registerReceiver() method.
Don't forget to unregister the receiver in the onPause() method by calling unregisterReceiver().
I have a broadcast receiver and im again broadcasting message from that broadcast onreceive's method .
public static class MyBroadcastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
Intent intent1 = new Intent("com.test.test");
sendBroadcast(intent1);
}
}
But it gives error on sendBroadcast
cannot make a static reference to the non-static method sendbroadcast(intent)
from the type context wrapper.
please help me solving this issue.
Use
context.sendBroadcast(intent1);
instead of
sendBroadcast(intent1);
because sendBroadcast is not method of BroadcastReceiver class.
you are using wrong syntax for making broadcast receiver
first you need to understand what is meaning of static class in java?
Static Class
and now you must refer these link for implementation of broadcast receiver
Link 1
I'm trying to send a broadcast from IntentService to Activity, but it doesn't work, even the Service did send the broadcast ( I check by debugger tool ).
The strange thing is that I have few other service that broadcast but only this particular one doesn't work.
Here is my code:
IntentService:
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Intent myItent = new Intent ("test");
sendBroadcast(intent);
}
BroadcastReceiver in MainActivity:
private BroadcastReceiver testbcreceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "succeed",
Toast.LENGTH_SHORT).show();
System.out.println("success");
}
};
onResume, where I register the BroadcastReceiver. Note that I have 4 service here, 2 out of 4 work fine.
protected void onResume() {
super.onResume();
mds.open();
registerReceiver(testbcreceiver, new IntentFilter("test"));
registerReceiver(downloadServiceReceiver, new IntentFilter(
DownloadChapterService.NOTIFICATION));
registerReceiver(parsingMangaReceiver, new IntentFilter(
ParsingMangaLinkService.NOTIFICATION));
registerReceiver(parsingMangaChapterReceiver, new IntentFilter(
ParsingChapterMangaService.NOTIFICATION));
}
And in AndroidManifest.xml:
<service android:name="anvu.bk.service.ToastService">
</service>
Thank you for looking at my question.
Change it
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Intent myItent = new Intent ("test");
sendBroadcast(intent);
System.out.println("wait");
}
To
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Intent myItent = new Intent ();
myItent .setAction(DownloadChapterService.NOTIFICATION); // Define intent-filter
sendBroadcast(myItent );
System.out.println("wait");
}
When creating your intent to be broadcast, prefix your action with your package name and set it like this:
public static final String TEST_ACTION = "anvu.bk.service.TEST_ACTION";
protected void onHandleIntent(Intent intent) {
Intent myItent = new Intent ();
myIntent.setAction(TEST_ACTION);
sendBroadcast(intent);
}
Then, in your onResume(), register your receiver:
IntentFilter filter = new IntentFilter();
//basically, we need the same string as when we were preparing intent for broadcast
//so set action this way, or use string "anvu.bk.service.TEST_ACTION" instead
//of course, use the class name where you declared TEST_ACTION :)
filter.addAction(IntentService.TEST_ACTION);
registerReceiver(testbreceiver, filter);
Then remember to unregister your receiver in onDestroy() with:
unregisterReceiver(testbreceiver);
As a side note, don't use System.out.println() - use Android's Log.d() to log things. Here's why:
System.out.println() (or printf() for native code) should never be used. System.out and System.err get redirected to /dev/null, so your print statements will have no visible effects. However, all the string building that happens for these calls still gets executed.
I am trying to communicate/update UI from Service to activity. The broadcast I receive is not what I had sent. Any ideas why?
Service code:
#Override
//binder returns NULL
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Intent i = new Intent();
i.putExtra("lol", "haha");
i.setAction(MYACTION);
sendBroadcast(i);
Activity code:
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter intentFilter = new IntentFilter(MYACTION);
registerReceiver(recv, intentFilter);
}
BroadcastReceiver recv = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent getintent = getIntent();
String action = getintent.getAction();
//ACTION RECEIVED IS DIFFERENT FROM MYACTION. IT IS ACTION.MAIN
// VALUE RECEIVED IS NULL
String val = getintent.getStringExtra("lol");
}
I have not registered the receiver in manifest. Is it necessary?
As mentioned in comments: I do not receive the same action in broadcast receiver and the value from intent is NULL.
What am I doing wrong?
Thanks for your help.
You dont need to use getIntent, because it translates to Activity's intent, not received broadcast's intent. So in your case, you need to use intent only which refers to broadcasted intent. And make sure you do make a check before reading the desired value from bundle, because there might be a possibility that you are getting another broadcast first which doesn't contain lol in its bundle.
So in your broadcast receiver, do it like this:
....
String val = getintent.getStringExtra("lol");
if(val.equals("your_action_string"){
String val = intent.getStringExtra("lol"); //getIntent() replaced by intent
}
....
P.S. no, you dont need to register any broadcast receiver because it is created and being used programmatically
If you are making web requests or extended tasks I'd check out the async task. It makes it way easier to update the UI. Just make sure you call onPreExecute() and onPostExecute() to do this. I don't like services and receivers.
http://developer.android.com/reference/android/os/AsyncTask.html
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 );
}