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)
Related
I am creating sending broadcast from activity to fragment. But in my case receiver called three times as I only send broadcast once. please help
Here , I am registering broadcast in Fragment
#Override
public void onResume() {
super.onResume();
getActivity().registerReceiver(broadcastReceiver, new IntentFilter("example.com"));
}
#Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(broadcastReceiver);
}
And my receiver in Fragment
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Here I am receiving the data and want to update the list in
//my fragment
};
Sending the broadcast
Intent intent = new Intent("example.com");
intent.putExtra("data","any_data");
sendBroadcast(intent);
You must always set Action to Intent like below,
Intent intent = new Intent();
intent.setAction("action_type");
sendBroadcast(intent);
And in your receiver add this line :
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction("action_type")) {
// Write your code here now.
}
};
Hope it works.
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
I have 1 activity that I would like to start at different times with different variables from a Broadcast Receiver.
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equalsIgnoreCase("tv.abcd.v4.ORIGINAL_VIDEO_SCENE")){
channelName = intent.getExtras().getString("com.abcd.Channel");
JSONObject json = new JSONObject(intent.getExtras().getString("com.abcd.Data"));
String incomingScene = json.getString("url");
scene.putExtra("channel", channelName);
scene.putExtra("url", incomingScene);
scene.addFlags(Intent.FLAG_FROM_BACKGROUND);
scene.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
scene.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scene);
}
I have the code to start the activity via Intent and in the activity receiver the extras to make data appear.
Intent intent = getIntent();
sceneUrl = intent.getStringExtra("url");
Log.d("Image.incomingscene.url",sceneUrl);
channelName = intent.getStringExtra("channel");
Log.d("Image.incomingSceneAvatar",networkAvatar);
image = (ImageView)findViewById(R.id.imageView1);
image.setScaleType(ScaleType.FIT_CENTER);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
Picasso.with(this).load(sceneUrl).skipMemoryCache().fit().into(image, new EmptyCallback() {
});
Now after that I want to start the same activity again from the Broadcast Reciever with different data. So i want the previous activity to get out the way and allow this new instance to start up.
How to accomplish this feat?
register another broadcast receiver from the activity. Then, when you want to kill it, send a broadcast message from the broadcast receiver that you mentioned .
In your broadcastReceiver do something like the following :
public static final String CLOSE_Activity= "com.mypackage.closeactivity";
and in yopr OnReceive method do like the following :
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("HIT OUTGOING");
Intent i = new Intent();
i.setAction(CLOSE_Activity);
context.sendBroadcast(i);
}
then in your activity craete a receviver and register it in the onResume method and unregeister it in the onPause method , like the following :
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(RECEIVER_Class.CLOSE_Activity)) {
finish();
}
}
}
activity onResume method :
#Override
public void onResume() {
registerReceiver(broadcastReceiver, new IntentFilter(RECEIVER_Class.CLOSE_Activity));
}
activity onPause method :
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Please give me some feedback
Hope that helps .
I am trying to update the UI (Activity) after some action has been performed in the service. This is very simple example but it doesn't seem to work for me. What am I missing here?
ExampleService:
public class ExampleService extends IntentService{
#Override
protected void onHandleIntent(Intent intent) {
notifyActivity();
}
private void notifyActivity() {
Intent broadcast = new Intent(this, ExampleActivity.class);
sendBroadcast(broadcast);
}
}
ExampleActivity:
public class ExampleActivity extends ListActivity {
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
registerReceiver(receiver, filter);
}
}
You cannot send a broadcast to an anonymous dynamic receiver that way. You will need to define an action string in the Intent and use that action string in the IntentFilter.
You might consider using LocalBroadcastManager for this scenario, for better performance. Here is a sample project demonstrating this.
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.