GCM Push Notifications not opening app - android

Whenever a gcm message comes back to my phone, I receive a notification. However, when I press it, it doesn't open my app. It only disappears. Previously when I used PendingIntent.FLAG_ONE_SHOT, it would work, but if I sent multiple messages, it wouldn't be up to date. Please help.
This is my notification code
public class GCMNotificationIntentService extends IntentService{
//set ID for the notification, so it can be updated
public static final int notifyID = 9001;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
Log.d("GCMN","GCMNTEST");
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
sendNotification("Deleted messages on server: "
+ extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
sendNotification("Message Received from Google GCM Server:\n\n"
+ extras.get(AppConstants.MSG_KEY));
}
}
GCMBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg){
Intent resultIntent = new Intent(this, HomeActivity.class);
Log.d("RECEIVEDPT2",msg);
resultIntent.putExtra("msg", msg);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this).setContentTitle("Alert")
.setContentTitle("You've received a new message")
.setSmallIcon(R.drawable.ic_cast_dark);
//Set pending intent
mNotifyBuilder.setContentIntent(resultPendingIntent);
//Set vibration
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
defaults = defaults | Notification.DEFAULT_VIBRATE;
defaults = defaults | Notification.DEFAULT_SOUND;
mNotifyBuilder.setDefaults(defaults);
// Set the content for Notification
mNotifyBuilder.setContentText("You have new notifications");
// Set autocancel
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.amosang.pushtest" >
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- GCM Permissions - Start here -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="com.example.amosang.pushtest.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.amosang.pushtest.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
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:exported="true"
android:name=".HomeActivity"
android:label="#string/title_activity_home" >
</activity>
<receiver
android:name=".GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<action android:name="com.example.amosang.pushtest" />
</intent-filter>
</receiver>
<service android:name=".GCMNotificationIntentService" />
<activity
android:name=".NewRequest"
android:label="#string/title_activity_new_request" >
</activity>
</application>
I can't seem to add FLAG_ACTIVITY_NEW_TASK as it doesn't compile.

Here is tested code that will help you to achieve the desired result.
private void notify(String msg) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Title")
.setVibrate(new long[]{5000})
.setLights(Color.GREEN, 3000, 3000) //for notification led light with color
.setContentText(msg)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}

Try to use:
`PendingIntent.getActivity(context, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);`
instead of
`PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);`
Please add android:exported="true" [http://developer.android.com/intl/es/guide/topics/manifest/service-element.html] in android manifest inside activity tag which is supposed to be opened after tapping notification from status bar.

Related

Pending Intent or on click of Notification Does Not Open My desire Activity

please find the code of sendNotfication. I tried lots of things but still not working. Do I need to change in some Mainfest file ?
private void sendNotification(String messageBody) {
int requestID = (int) System.currentTimeMillis();
Intent intent = new Intent(getApplicationContext(), NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestID /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(requestID/* ID of notification */, notificationBuilder.build());
}
Please find the mainfest file. This is the same that i found example in firbase. but still when i click on notfication it always went to SplashScreen.
I tried the recent comments but still not working.
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:fullBackupContent="#xml/backup_descriptor"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme.NoActionBar">
<activity
android:name=".SplashScreenActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".HomeActivity"
android:screenOrientation="portrait" />
<!-- [START firebase_service] -->
<service android:name=".FCMTest.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- [END firebase_service] -->
<service
android:name=".FCMTest.MyJobService"
android:exported="false">
<intent-filter>
<action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/abc" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
<activity android:name="com.example.guptasachin.myapplication.NotificationActivity"></activity>
You are using request Id in many places..
Please check the below working code to open the desired Activity :
Here , activity = CurrentActivity context,
mNotificationId = unique constatnt number like 200,201..e.t.c
Try the below code :
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(activity);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mBuilder.setColor(activity.getResources().getColor(R.color.pricify_red));
mBuilder.setSmallIcon(R.drawable.transparent_img);
} else {
mBuilder.setColor(activity.getResources().getColor(R.color.pricify_red));
mBuilder.setSmallIcon(R.drawable.app_logo);
}
mBuilder.setContentTitle(title)
.setContentText(msg);
Intent i = new Intent();
i.setComponent(new ComponentName(currentActivity.this, DesiredActivity.class));
PendingIntent pIntent = PendingIntent.getActivity(activity, 0, i, 0);
mBuilder.setContentIntent(pIntent);
NotificationManager mNotificationManager =
(NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mNotificationId, mBuilder.build());

android notification is not taking me to the activity when the app is hidden but works when the app is open

I'm unable to go the activity(dosomething.class) when the app is not open but it works when the app's mainactivity.class is open. How can I go to the doactivty.class when the app is running in the background or hidden?
Currently, it takes me the mainactivity.class when I click on the notification also when the mainactivity.class is not shown then the notification sound is not played. I've tried many ways to get it to work but currently nothing is working.
Code:
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.example">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name="com.example.example.MainActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.example.Firebase.MyFirebaseInstanceService" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name="com.example.example.Firebase.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity
android:exported="true"
android:launchMode="singleTask"
android:name="com.example.example.dosomething"
android:icon="#drawable/logo"
android:label="example"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar" />
<activity
</application>
</manifest>
I tried this :
Intent intent = new Intent(this, dosomething.class);
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this)//
.setContentTitle("title")//
.setContentText("text")//
.setStyle(new NotificationCompat.BigTextStyle().bigText("title"))//
.setSmallIcon(R.drawable.logo)//
.setContentIntent(pendingIntent)//
.setTicker("testapp")//
.build();
notification.defaults |= Notification.DEFAULT_ALL;
NotificationManager notificationManager = (NotificationManager) getBaseContext().getSystemService(Service.NOTIFICATION_SERVICE);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
and this :
Intent intent = new Intent(getApplicationContext(), dosomething.class);
intent.putExtra("data", tasks);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle("title")
.setContentText("text")
.setAutoCancel(true)
.setLights(Color.parseColor("#0086dd"), 2000, 2000);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(dosomething.class);
stackBuilder.addNextIntent(intent);
// PendingIntent contentIntent = PendingIntent.getActivity(this,0, intent,PendingIntent.FLAG_ONE_SHOT);
PendingIntent contentIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(1, mBuilder.build());
and this :
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this,"channelid");
//Create the intent that’ll fire when the user taps the notification//
Intent intent = new Intent(getApplicationContext(), dosomething.class);
intent.putExtra("data", tasks);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setSmallIcon(R.drawable.logo);
mBuilder.setContentTitle(remoteMessage.getNotification().getTitle());
mBuilder.setContentText(remoteMessage.getNotification().getBody());
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(001, mBuilder.build());

I'm not able to open specified activity via notification

I'm using Firebase notifications to send notifications in my Android App. I want to achieve following:
When user clicks notification, activity of my choice should open and activity should perform some actions automatically which I'll define like loading specific url within webview, etc.
What I did?
In Firebase console, under custom data, I set key as click_action. And value as ttdemo and sent notifications.
In my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".aboutmain" />
<activity android:name=".Timetable">
<intent-filter>
<action android:name="ttdemo"/>
</intent-filter>
</activity>
<activity android:name=".Results" />
<activity android:name=".timetable_downloads" />
<activity android:name=".result_downloads" />
<activity android:name=".eforms" />
<activity android:name=".write" />
<activity android:name=".qpapers" />
<activity android:name=".november2014" />
<activity android:name=".november_2014_downloads" />
<activity android:name=".april_2015" />
<activity android:name=".november_2015" />
<activity android:name=".april_2016"></activity>
</application>
Current scenario:
I'm getting notifications but Timetable activity is not opened.
Instead, the main activity opens.
Try like blow code when your onMessageReceived method called.
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
if (data.containsKey("click_action")) {
String className = data.get("click_action");
Class cls;
try {
cls = Class.forName(className);
Intent i = new Intent(context, cls);
//i.putExtras(extras); // put extras if you required
context.startActivity(i);
}catch(ClassNotFoundException e){
//means you made a wrong input in firebase console
}
}
}
To send a notification with firebase console, put a key-value-pair as custom data like this:
Key: click_action
Value: <fully qualified class name of your activity>
You need to pass panding intent to notification in the onMessageReceived(RemoteMessage remoteMessage) method of class FirebaseMessagingService
Intent resultIntent = new Intent(FirebaseMessagingService.this, MobilActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent intent = PendingIntent.getActivity(getApplicationContext(), 0,
resultIntent, PendingIntent.FLAG_CANCEL_CURRENT);
and set to notification object as
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setContentIntent(resultPendingIntent)
and method like
private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(inboxStyle)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.growth_indus)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(AppConstants.getParamInt(AppConstants.GlobalParamEnum.NOTIFICATION_ID), notification);
}
Finally, I achieved the objective!
This solution worked perfectly for me! http://androidbash.com/firebase-push-notification-android/

Unable to receive push notifications (android)

I have written very simple code (just for demo) for push notification following google developers guide. I am sending notification using Postman but I can't receive it on my emulator. I am using blue stacks with google play services. Here is my code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
#Override
public void run() {
String token = null;
InstanceID instanceID = InstanceID.getInstance(MainActivity.this);
try {
token = instanceID.getToken("590106578883",
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
} catch (IOException e) {
Log.d("TAG", e.getMessage());
}
Log.d("TAG", token + "");
int i = 0;
}
}).start();
} // onCreate
} // MainActivity
GcmListener.java
public class MyGcmListenerService extends GcmListenerService {
#Override
public void onMessageReceived(String from, Bundle data) {
sendNotification(data.toString());
}
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentTitle("GCM Message")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
} // MyGcmListenerService
Manifest.java
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.topnotchdev.pushnotifications.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="gcm.play.android.samples.com.gcmquickstart" />
</intent-filter>
</receiver>
<service
android:name=".MyGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
</application>
Here is the response from google server
{
"multicast_id": 7574264493447786438,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1459889454670774%d32a6865f9fd7ecd"
}
]
}

Android GCM Message not receiving

I am sending GCM message from my server with gcm.php. And it says messages sent.
{"multicast_id":6717271501903387817,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1459264392497404%479be975f9fd7ecd"}]}
For the Android Here is the AndroidManifest :
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="android.jokerslab.com.demogpsinfonet.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="android.jokerslab.com.demogpsinfonet.permission.C2D_MESSAGE" />
<!-- GCM Permissions - End here -->
<uses-permission android:name="android.permission.VIBRATE" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!-- android.jokerslab.com.demogpsinfonet-->
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="GCMNotificationIntentService" />
</intent-filter>
</receiver>
<!-- Register Service -->
<service android:name=".GCMNotificationIntentService" />
BoradCast Receiver :
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
GCMNotificationIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Notificaiton Service :
public class GCMNotificationIntentService extends IntentService {
// Sets an ID for the notification, so it can be updated
public static final int notifyID = 9001;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
sendNotification("Deleted messages on server: "
+ extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
sendNotification("Message Received from Google GCM Server:nn"
+ extras.get(ApplicationConstants.MSG_KEY));
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
Toast.makeText(
getApplicationContext(),
"It's working",
Toast.LENGTH_LONG).show();
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.putExtra("msg", msg);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
resultIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Alert")
.setContentText("You've received new message.")
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark);
// Set pending intent
mNotifyBuilder.setContentIntent(resultPendingIntent);
// Set Vibrate, Sound and Light
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
defaults = defaults | Notification.DEFAULT_VIBRATE;
defaults = defaults | Notification.DEFAULT_SOUND;
mNotifyBuilder.setDefaults(defaults);
// Set the content for Notification
mNotifyBuilder.setContentText("New message from Server");
// Set autocancel
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
}
}
Any Hints what am i missing here ?
In the manifest file, I think you are missing some lines for the receiver:
<service
android:name="com.example.MyGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
If we check the document for Set up a GCM Client App on Android and compare to the given manifest code that support GCM, the code above is missing in your manifest file.
To receive simple downstream messages, use a service that
extendsGcmListenerService to handle messages captured by GcmReceiver.
GcmReceiver extends WakefulBroadcastReceiver, guaranteeing that the
CPU is awake so that your listener service can complete its task.
By overriding the method GcmListenerService.onMessageReceived, you can
perform actions based on the received message:
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
if (from.startsWith("/topics/")) {
// message received from some topic.
} else {
// normal downstream message.
}
// ...
}
register receiver in manifest as
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="packageName" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
and in in GCMIntentService
#Override
protected void onMessage(Context context, Intent data) {
// context=GCMIntentService.this;
this.context=context;
notifyMessage(data);
}

Categories

Resources