JeromeWasBannedBySONazis JeromeWasBannedBySONazis - 30 days ago 10
Android Question

The GCM Notification message from the Notification Bar will not be shown in the activity if the app isn't started already

I am using this tutorial for push notifications http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

It works fine but when I click on the status bar to see the received message, it doesn't show in the MainActivity which it starts. What is the issue?

MainActivity which receives the message

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


setContentView(R.layout.activity_main);
Log.v(TAG, "onCreate?");
cd = new ConnectionDetector(getApplicationContext());

// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}



// Getting name from intent
Intent i = getIntent();

name = i.getStringExtra("name");
pid= i.getStringExtra("pid");


// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);

// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
lblMessage = (TextView) findViewById(R.id.lblMessage);

registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));

// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);

// Check if regid already presents
if (regId.equals("")) {
//Toast.makeText(getApplicationContext(), "not registered, key is empty ", Toast.LENGTH_LONG).show();
// Registration is not present, register now with GCM
GCMRegistrar.register(this, SENDER_ID);

} else {
//Toast.makeText(getApplicationContext(), "else key is not empty ", Toast.LENGTH_LONG).show();
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.

//Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {

// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {

@Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(context, name, email, regId, flat, admin, dummy);
return null;
}

@Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}

};
mRegisterTask.execute(null, null, null);
}

}
//get info from sqlite database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
//TextView textview1 = (TextView)findViewById(R.id.textView1);
HashMap<String, String> map = new HashMap<String, String>();
map = db.getUserDetails();
String username = map.get("email");


if (username == null){
a=name;

movies = new ArrayList<HashMap<String, String>>();
new GetDaPid().execute();

// Closing dashboard screen
//finish();
}else{

b=username;

}
movies = new ArrayList<HashMap<String, String>>();
if (repid==null){

new GetDaPid().execute();
}else{
new GetDaComments().execute();
}




}
class GetDaComments extends AsyncTask<String, String, String>{

@Override
protected void onPreExecute() {
super.onPreExecute();
}


@Override
protected String doInBackground(String... args) {

}

protected void onPostExecute(String zoom){
zpDialog.dismiss();

MainActivity.this.runOnUiThread(new Runnable() {
public void run() {


ListAdapter adapter = new SimpleAdapter(MainActivity.this, movies,
R.layout.stickymessages, new String[] {"comments"},
new int[]{R.id.textView1});

setListAdapter(adapter);
ListView lv = getListView();


lv.setOnItemClickListener(new OnItemClickListener(){

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {



}
lv.setOnTouchListener(new ListView.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;

case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}

// Handle ListView touch events.
v.onTouchEvent(event);
return true;
}
});




}
});
}

}
class GetDaPid extends AsyncTask<String, String, String>{

@Override
protected void onPreExecute() {

}


@Override
protected String doInBackground(String... args) {

}

protected void onPostExecute(String zoom){
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {

new GetDaComments().execute();
}
});
}

}

/**
* Receiving push messages
* */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Log.e("broadcast", MainActivity.name);
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
Log.v(TAGE, "broadcast?");
/**
* Take appropriate action on this message
* depending upon your app requirement
* For now i am just displaying it on the screen
* */

// Showing received message
lblMessage.append("New Message: "+ newMessage + "\n");
Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();

// Releasing wake lock
WakeLocker.release();
}
};

@Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver Error", "> " + e.getMessage());
}
super.onDestroy();
}

}


GCM

public class GCMIntentService extends GCMBaseIntentService {

private static final String TAG = "GCMIntentService";

public GCMIntentService() {
super(SENDER_ID);
}

/**
* Method called on device registered
**/
@Override
protected void onRegistered(Context context, String registrationId) {
//Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, "Your device registred with GCM");
// Log.d("NAME", MainActivity.name);
ServerUtilities.register(context, MainActivity.name, MainActivity.email, registrationId, MainActivity.flat, MainActivity.admin, MainActivity.dummy);
}

/**
* Method called on device un registred
* */
@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
ServerUtilities.unregister(context, registrationId);
}

/**
* Method called on Receiving a new message
* */
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("price");

displayMessage(context, message);
// notifies user
generateNotification(context, message);
}

/**
* Method called on receiving a deleted message
* */
@Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}

/**
* Method called on Error
* */
@Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}

@Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}

/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);

String title = context.getString(R.string.app_name);

Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.putExtra("message", message);

PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT );

notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;

// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;

//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");

// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);

}

}


Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tromto.flat"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<!-- GCM connects to Internet Services. -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />

<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="com.tromto.flat.permission.C2D_MESSAGE"
android:protectionLevel="signature" />

<uses-permission android:name="com.tromto.flat.permission.C2D_MESSAGE" />

<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<!-- Network State Permissions to detect Internet status -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".RegisterActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"

android:configChanges="orientation|screenSize"
android:label="@string/app_name" >
</activity>
<!-- Login Activity -->
<activity
android:name=".LoginActivity"
android:label="Login Account" >
</activity>
<activity
android:name=".SearchableActivity"
android:label="@string/title_activity_searchable"
android:configChanges="orientation|screenSize" >
</activity>
<activity
android:name=".FlatListActivity"
android:label="@string/title_activity_flat_list"
android:configChanges="orientation|screenSize" >
</activity>

<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>

<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />

<category android:name="com.tromto.flat" />
</intent-filter>
</receiver>

<service android:name=".GCMIntentService" />

<activity
android:name=".MsgToflatActivity"
android:label="@string/title_activity_msg_toflat"
android:configChanges="orientation|screenSize" >
</activity>
<activity
android:name=".RegisteradminActivity"
android:label="@string/title_activity_registeradmin" >
</activity>
</application>

</manifest>

Answer Source

Update the TextView after you initialize it

lblMessage = (TextView) findViewById(R.id.lblMessage);

As you are making notification and putting the value with the key "message", so you need to retrieve the value though the same key "message"

lblMessage.append("New Message: "+ i.getStringExtra("message") + "\n");