Change Activity behaviour when C2DM Push notification is received - android

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.

Related

LocalBroadcastManager not working

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

Android broadcast receiver not working with intent receiver

Hi I developed one small android application in which I am using one activity one intent service and one broadcast receiver.
So my code looks like :
public class Main_Activity extends Activity {
private ResultReceiver resultReciver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_);
Log.i("***************************88", "inside activity on create");
IntentFilter filter = new IntentFilter("com.nilkash.broadcast.receiver");
resultReciver = new ResultReceiver();
registerReceiver(resultReciver, filter);
//LocalBroadcastManager.getInstance(this).registerReceiver(resultReciver, filter);
Intent intent = new Intent(this, ExampleService.class);
startService(intent);
}
public class ResultReceiver extends BroadcastReceiver{
public ResultReceiver()
{
}
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Log.i("**********************", "inside broadcast receiver: ");
}
}
}
And intent service
public class ExampleService extends IntentService{
public ExampleService(String value)
{
super(value);
}
public ExampleService()
{
super("");
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Log.i("********************************", "inside intetn reciver: ");
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.nilkash.broadcast.receiver");
//broadcastIntent.putExtra("value", "nilkash");
sendBroadcast(intent);
//LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
In manifest file I define service.
So my problem is that I start service from activity and its working fine. From service on intent receive I sent one broadcast receiver but it not listening inside my broadcast receiver.
Am i doing some thing wrong? Need Help. Thank you.
There is an error: sendBroadcast(intent);. Should be another intent object (broadcastIntent).

BroadcastReceiver onReceive() not working

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)

sending intent extras from service to activity

I have a service that listens for (ON_BATTERY_CHANGE), then onReceive service sends a Broadcast to My MainActivity. The problem is that I somehow can't get them from service to my main activity. Code: Main Activity:
public class MainActivity extends Activity
private BroadcastReceiver batteryReceiverService;
private TextView text2;
....
protected void onCreate(Bundle savedInstanceState) {
text2=(TextView)findViewById(R.id.TV_text2);
batteryReceiverService = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
text2.setText("left: "+intent.getStringExtra("H")+" hours "+intent.getStringExtra("M")+" minute(s)");
Log.e("text2","text2 HHH " +intent.getStringExtra("H")); //log shows 0
Log.e("text2","text2 MMM " +intent.getStringExtra("H")); // log shows 0
}
};
registerReceiver(batteryReceiverService, new IntentFilter(UltimateBatterySaverService.BROADCAST_ACTION));
....
#Override
protected void onDestroy() {
unregisterReceiver(batteryReceiverService);
super.onDestroy();
}
Service:
public class UltimateBatterySaverService extends Service {
private Intent intent;
static final String BROADCAST_ACTION = "lt.whitegroup.ultimatebatterysaver";
private BroadcastReceiver batteryLevelReceiver;
....
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onDestroy() {
unregisterReceiver(batteryLevelReceiver);
super.onDestroy();
}
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryLevelReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent){
// Receiving data, calculating and etc
averageChargingH=timeAllInHours;
averageChargingM=timeAllInMinutes;
// to put extras and send broadcast
does();
......
public void does(){
String strLong = Long.toString(averageChargingH);
String strLong2 = Long.toString(averageChargingM);
Log.e("cccccc","strLong h "+strLong); // getting good value not 0(everything ok)
Log.e("cccccc","strLong2 m"+strLong2); // getting good value not 0(everything ok)
intent.putExtra("H", strLong);
intent.putExtra("M", strLong2);
sendBroadcast(intent);
}
Any ideas why my information is not transfered correctly?
The does() method seems to be using variables in the same scope as onReceive so I'm guessing that the intent variable in does() is actually the Intent passed in from onReceive.
Try adding some logging before sending the broadcast to check if the action of the intent is correct, or simply create the broadcast intent in the onReceive method and name it intent2.

Service to Activity communication

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.

Categories

Resources