How do i get data from the gcm? - android

Can someone show me the hierarchy that stands behind the process when I'm getting a new data from the GCM? The process that happened only in the client. Example: First the data is getting to the displayMessage function in CommonUtilities class. Seconds the data is transmitted to the onMessage function in GCMIntentService class, and so on.
Thanks!
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
// Showing received message
lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
WakeLocker.release();
}
};

If all the process with registering the device and getting the registrationId is passes as it should be, getting the data in your onMessage() should be something similar to this :
#Override
protected void onMessage(Context arg0, Intent intent) {
Log.d(TAG, "MESSAGE RECEIVED : "+intent.getExtras().toString());
String action = intent.getStringExtra("action");
int extra = 0;
try {
extra = Integer.parseInt(intent.getStringExtra("action_id"));
} catch (Exception e){
/* ignore */
}
String message = intent.getStringExtra("message");
generateNotification(getApplicationContext(), message, action, extra);
}
Of course this is in my app, the keys which you will use to get the right data depends on what kind of data is sending your server to the client device. And after receiving this portion of data you can do whatever you like with it, maybe create a notification and alert the user about the message.
Edit :
If you want to show some kind of message in your activity using BroadcastReceiver you can do something like this : In your onMessage after receiving the message send broadcastIntent
Intent intent = new Intent("messageReceived");
sendBroadcast(intent);
and add
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(messageReceived);
to your activity and register your broadcast receiver like :
registerReceiver(myReceiver, intentFilter);
and handler the message in your receiver like this :
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("messageReceived")) {
// Do your stuff here.
}
}

Related

how to detect and notify user of message from server?

app sent transaction to the server, user closes app, now a message needs to be
sent back to the phone from the server 10+ minutes later. The phone may be asleep, or the user might be checking his email. The question which I have is:
how can the phone be notified that a message has been received from server ?
how to display that message ?
A possible solution would be Google cloud messaging, but I still am not able to answer these 2 questions
1) You have to use SERVICE for that.
2) And to show that message.
Do like this.
The variable and method are members of Service class:
public final static String ACTION = "com.apps.example.MainActivity";
private void messageFromServer()//this method sends broadcast messages
{
Intent intent = new Intent(MOVEMENT_UPDATE);
String messageFromServer=serverMessage //here you will put server message
intent.putExtra("MessageFromServer", messageFromServer);
sendBroadcast(intent);
}
And this are the methods from Main activity:
You have to register receiver in the onResume method:
#Override
public void onResume()
{
IntentFilter intentFilter;
intentFilter= new IntentFilter(YourService.ACTION);
messageFromServer= new MessageFromServer();
registerReceiver(messageFromServer, intentFilter);
startYourService();
super.onResume();
}
private void startYourService()
{
startService(new Intent(this, YourService.class));
}
public class MessageFromServer extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
// this method receives broadcast messages.
// Be sure to modify AndroidManifest.xml file in
// order to enable message receiving
String messageFromServer = intent.getStringExtra("MessageFromServer");
updateGUI();// here you can update the ui
}
}
and put service in you manifest file.
<service android:name="com.apps.service.YourService" ></service>

Android IntentService not receiving extra

I am starting the service , and I put a message in extra,
Intent mServiceIntent = new Intent(this, TextToSpeechService.class);
mServiceIntent.putExtra(Intent.EXTRA_TEXT, "a message");
mServiceIntent.setType(HTTP.PLAIN_TEXT_TYPE);
this.startService(mServiceIntent);
but running , the service starts and the log shows a message = null...
public class MyService extends IntentService {
static final String TAG = "MyService";
public MyService() {
super("My Service");
}
#Override
protected void onHandleIntent(Intent intent) {
String message = intent.getStringExtra("message");
Log.d(TAG, "received message, should say: " + message);
}
could it be related to the MIME TYPE, when I state mServiceIntent.setType(HTTP.PLAIN_TEXT_TYPE);
( using import org.apache.http.protocol.HTTP;)
As #Squonk already mentioned your code doesn't really go together. To start your Service you have to use an Intent like this:
// The class you set here determines where the Intent will go.
// You want it to start MyService so we write MyService.class here.
Intent intent = new Intent(this, MyService.class);
intent.putExtra(Intent.EXTRA_TEXT, "a message");
startService(intent);
You can very well use the Intent.EXTRA_TEXT constant as key for your extra, but you have to use the same key to retrieve the message in your Service:
#Override
protected void onHandleIntent(Intent intent) {
String message = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.d(TAG, "received message, should say: " + message);
}
The code in your MyService doesn't really show if you actually use the mime type in your MyService so I removed it from my example above.

Receiving same intent broadcast multiple times but only sending once

I have an intent that gets sent under a certain condition. The logs prove it is only sent ONCE, but the receiver is receiving it multiple times milliseconds apart.
10-01 10:09:59.201: I/System.out(13543): SENDER CHECKPOINT
10-01 10:09:59.211: I/System.out(13543): RECEIVER CHECKPOINT
10-01 10:09:59.291: I/System.out(13543): RECEIVER CHECKPOINT
I have confirmed that there is only ONE registration of the Broadcast Receiver and only ONE action filter used with the registered BR. It is only used in a single activity where a service running in another thread broadcasts the intent. Again, the logs substantiate the ONE broadcast and multiple receipts. What's more, the extras are null in the echo receipt.
How can this be? Is it possible the OS is echoing it?
Code that sends the broadcast:
private void sendBroadcast(boolean status, String message, String action){
System.out.println("SENDER CHECKPOINT");
Intent intent = new Intent(action);
Bundle bundle = new Bundle();
bundle.putBoolean("status", status);
bundle.putString("message", message);
intent.putExtras(bundle);
sendBroadcast(intent);
}
Code that receives the broadcast:
private class displayUpdate extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("RECEIVER CHECKPOINT");
};
}
Registration:
#Override
public void onResume() {
super.onResume();
try {
// just in case onResume is called w/o a pause
try{activity.unregisterReceiver(displayReceiver);}catch(Exception e){}
filterRefreshUI = new IntentFilter(REFRESH_UI);
activity.registerReceiver(displayReceiver, filterRefreshUI);
} catch (Exception e) {
e.printStackTrace();
}
}
Unregistration:
#Override
public void onPause() {
super.onPause();
try{unregisterReceiver(displayReceiver);}catch(Exception e){}
}
REALLY IT'S THAT SIMPLE! Yet the receiver fires TWICE!
In case you were wondering - Registration/Unregistration are handled in the onPause/onResume to prevent leaking memory if the App is killed by the OS.

In BroadcastReceiver, getResultCode() always returns -1 for SMS sent and delivered actions

Following most people I guess, I am deriving my SMS handling code from http://mobiforge.com/developing/story/sms-messaging-android. I am trying to catch the broadcasts for sent and delivered messages, with this code (for sent messages):
appContext.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.i("Debug",
"My embedded receiver: "
+ String.valueOf(getResultCode()));
}
}, new IntentFilter("iam.applications.SmsReceiver.SMS_SENT"));
This always results in getResultCode() returning a value of -1, even when the SMS is successfully sent. I don't know of another way to tell whether my SMS was sent or not.
I have also subclassed BroadcastReceiver to see if that makes any difference, but it does not. -1 is always returned:
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("Debug",
"Result code in onReceive: " + String.valueOf(getResultCode()));
}
My creation of the PendingIntent looks like this (snippet from a for-loop for processing parts of long SMS messages):
Intent sentIntent = new Intent(
"iam.applications.SmsReceiver.SMS_SENT");
sentIntent.putExtra(SmsHandler.PHONE_NUMBER, phoneNumber);
sentIntent.putExtra(SmsHandler.MESSAGE, message);
sentPIArray.add(PendingIntent.getBroadcast(appContext,
(int) Calendar.getInstance().getTimeInMillis(), sentIntent,
PendingIntent.FLAG_UPDATE_CURRENT));
I'm a big idiot:
// Field descriptor #14 I
public static final int RESULT_OK = -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 );
}

Categories

Resources