I followed the documentation of google to implement push notifications.
When the app is open works fine, but when I close the app does not receive notifications.
Here is the code:
Manifest
<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.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="it.bsdsoftware.cnabologna.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<permission
android:name="it.bsdsoftware.cnabologna.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<application>
...
<service android:name=".notifiche.RegistrationIntentService"
android:exported="false" >
</service>
<service android:name=".notifiche.MyGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service android:name=".notifiche.MyInstanceIDListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
<receiver android:name=".notifiche.GcmBroadcastReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.GCM_RECEIVED_ACTION"/>
<category android:name="it.bsdsoftware.cnabologna" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
</intent-filter>
</receiver>
</application>
RegistrationIntentService.java
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";
public RegistrationIntentService() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
try {
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(getString(R.string.notifiche_push_sender_id), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.i(TAG, "GCM Registration Token: " + token);
sendRegistrationToServer(token);
} catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
}
}
private void sendRegistrationToServer(String token) {
OperazioneInvioToken op = new OperazioneInvioToken(token);
WebServiceTask ws = new WebServiceTask(op, this, false);
ws.execute();
}
}
MyGcmListenerService.java
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
#Override
public void onMessageReceived(String from, Bundle data) {
Bundle notification = data.getBundle("notification");
String title = "";
String message = "";
if(notification!=null){
title = notification.getString("title");
message = notification.getString("body");
}
NotificationUtility.showNotification(title, message);
NotificationUtility.setBadge(1);
}
}
MyInstanceIDListenerService.java
public class MyInstanceIDListenerService extends InstanceIDListenerService {
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. This call is initiated by the
* InstanceID provider.
*/
#Override
public void onTokenRefresh() {
// Fetch updated Instance ID token and notify our app's server of any changes (if applicable).
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
GcmBroadcastReceiver.java
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(), MyGcmListenerService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
When the app is open onMessageReceived of GcmListenerService class is called but when the app is closed is not called.
What did I do wrong?
Thanks
I resolved by updating the play service from com.google.android.gms:play-services:8.3.0 to com.google.android.gms:play-services:8.4.0
Related
I'm new to android. In my app, I didn't receive notification when the app is closed. If it is running it received. I tried all the way but still I didn't get the solution. Please find what I make wrong
Here my code:
Manifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.google.android.c2dm.permission.REGISTER" />
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
<permission android:name="com.h2o.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.h2o.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
android:name="com.h2o.ExternalReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<action android:name="com.google.android.c2dm.intent.REGISTER" />
<category android:name="com.google.android.gcm.demo.app" />
</intent-filter>
</receiver>
<service
android:name="com.h2o.MessageReceivingService"
android:label="com.h2o.MessageReceivingService" >
<intent-filter>
<action android:name="com.h2o.ExternalReceiver" />
<category android:name="com.h2o"/>
</intent-filter>
</service>
Receiver:
public class ExternalReceiver extends WakefulBroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),MessageReceivingService.class.getName());
startWakefulService(context,(intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Service:
public class MessageReceivingService extends Service{
private GoogleCloudMessaging gcm;
public static SharedPreferences savedValues;
public static void sendToApp(Bundle extras, Context context){
Intent newIntent = new Intent();
newIntent.setClass(context, AndroidMobilePushApp.class);
newIntent.putExtras(extras);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
}
public void onCreate(){
super.onCreate();
final String preferences = getString(R.string.preferences);
savedValues = getSharedPreferences(preferences, Context.MODE_PRIVATE);
gcm = GoogleCloudMessaging.getInstance(getBaseContext());
SharedPreferences savedValues = PreferenceManager.getDefaultSharedPreferences(this);
if(savedValues.getBoolean(getString(R.string.first_launch), true)){
register();
SharedPreferences.Editor editor = savedValues.edit();
editor.putBoolean(getString(R.string.first_launch), false);
editor.commit();
}
if(savedValuess.getBoolean(getString(R.string.first_launch), true)){
// Let AndroidMobilePushApp know we have just initialized and there may be stored messages
sendToApp(new Bundle(), this);
}
}
protected static void saveToLog(Bundle extras, Context context){
SharedPreferences.Editor editor=savedValues.edit();
String numOfMissedMessages = context.getString(R.string.num_of_missed_messages);
int linesOfMessageCount = 0;
for(String key : extras.keySet()){
String line = String.format("%s=%s", key, extras.getString(key));
editor.putString("MessageLine" + linesOfMessageCount, line);
linesOfMessageCount++;
}
editor.putInt(context.getString(R.string.lines_of_message_count), linesOfMessageCount);
editor.putInt(context.getString(R.string.lines_of_message_count), linesOfMessageCount);
editor.putInt(numOfMissedMessages, savedValues.getInt(numOfMissedMessages, 0) + 1);
editor.commit();
postNotification(new Intent(context, AndroidMobilePushApp.class), context);
}
protected static void postNotification(Intent intentAction, Context context){
final NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentAction, Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL);
final Notification notification = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Message Received!")
.setContentText("")
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.getNotification();
mNotificationManager.notify(R.string.notification_number, notification);
}
private void register() {
new AsyncTask(){
protected Object doInBackground(final Object... params) {
String token;
try {
token = gcm.register(getString(R.string.project_number));
Log.i("registrationId", token);
}
catch (IOException e) {
Log.i("Registration Error", e.getMessage());
}
return true;
}
}.execute(null, null, null);
}
public IBinder onBind(Intent arg0) {
return null;
}
}
Thanks in advance!
To be able to receive notifications when your application is closed, you have to register a service listener with the following permission
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
See the documentation for more details
https://developer.android.com/reference/android/service/notification/NotificationListenerService.html
you need to define your broadcast receiver in manifest like this:
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.google.android.gcm.demo.app" />
</intent-filter>
and in the broadcast receiver class add the following codes:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}}
there is some problem with wakeful broadcast receiver, read this
Confusion about WakefulBroadcastReceiver
For best practice it is recommended that you should use Firebase cloud messaging (FCM) instead of GCM.
Push Notification not received when app is closed in marshmallow .when my app open its work fine. In lollipop work fine doesn't matter app open or close.
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
i give permission in manifest file.
In addition to those permissions, you also need to specify a BroadcastReceiver in the AndroidManifest.xml file with the correct intent filter:
<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="com.example.yourapp" />
</intent-filter>
</receiver>
Then in your BroadcastReceiver show a notification:
public class GcmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String messageType = gcm.getMessageType(intent);
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// Show Notification
}
setResultCode(Activity.RESULT_OK);
}
}
I am writing an app that uses GCM Push Notifications, however when a notification appears, it opens the app but doesn't show the message. When I am in the app though, the messages show up normally. Please help.
This is my 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:exported="true"
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"
android:exported="false">
</service>
<activity
android:name=".NewRequest"
android:label="#string/title_activity_new_request" >
</activity>
</application>
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());
}
As requested in the comments, please include the code for HomeActivity which handles the notification so we can examine the code and suggest solutions. In the meantime, this is how I'd suggest you process the incoming GCM notification in your HomeActivity class (will update the answer once I see you code, if necessary). In my example, I have a helper method processIntent(Intent intent) which handles the Intent and its Extras. I call this method from both onCreate and onNewIntent methods.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.<layout-id>);
//here I call our processing method
processIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//call our processing method
processIntent(getIntent());
}
/**
* Helper method to process the incoming GCM Notification.
* #param intent
*/
private void processIntent(Intent intent){
if(intent == null) { return; }
Bundle extras = intent.getExtras();
try{
if(extras.containsKey("msg")){
//possibly a message
String message = extras.getString("msg");
Log.i(TAG, "Received Message "+message);
//do whatever with the message, like set as Text of TextView, etc
}
}
catch(Exception e){
Log.e(TAG, "Error Processing GCM Notification Intent", e);
}
}
I want to send a notification to the user when a task is assigned (i.e on a button click). When a task is assigned to the user I change some values in my server(i.e i'm performing a post method) I would like to know how to achieve this.
I have reached till registering the user when he logs in to my app & i'm storing users token id into my server I have also gone through google developers guide and have registered my app and obtained senderid and serverapikey. I will post the code till where I have reached please help me on how to proceed further.
LoginActivity
private void checkUserRegistrationToken() {
String url = URLMap.getGcmtokenUrl("gcmtoken_url");
employeeId = LoggedInUserStore.getLoggedInEmployeeId(getApplicationContext());
companyId = LoggedInUserStore.getLoggedInCompanyId(getApplicationContext());
url = url.replace("{eid}", employeeId).replace("{cid}", companyId);
final StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
tokenId = jObj.getString("TokenId");
if (tokenId.equals("null")) {
registerInBackground();
}
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error===" + error.toString());
}
});
request.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy());
RequestQueue queue = ((VolleyRequestQueue) getApplication()).getRequestQueue();
queue.add(request);
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcmObj == null) {
gcmObj = GoogleCloudMessaging.getInstance(LoginActivity.this);
}
tokenId = gcmObj.register(String.valueOf(R.string.gcm_defaultSenderId));
msg = "Registration ID:" + tokenId;
if (new ServiceManager(getApplicationContext()).isNetworkAvailable() && checkPlayServices()) {
String storeUrl = URLMap.getGcmtokenPostUrl();
employeeId = LoggedInUserStore.getLoggedInEmployeeId(getApplicationContext());
companyId = LoggedInUserStore.getLoggedInCompanyId(getApplicationContext());
HashMap<String, String> map = new HashMap<String, String>();
map.put("EmployeeId", employeeId);
map.put("CompanyId", companyId);
map.put("TokenId", tokenId);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, storeUrl, new JSONObject(map), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "Token has been posted in server!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, "Error posting token into server!!");
}
});
request.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy());
RequestQueue queue = ((VolleyRequestQueue) getApplication()).getRequestQueue();
queue.add(request);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Token Mesage=" + msg);
return msg;
}
#Override
protected void onPostExecute(String s) {
}
}.execute();
}
As you can see that I'm storing token id of user into my server.
Now I have also created a GcmBroadcastReceiver class
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
NotificationService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
and I have also created a NotificationService class which has on MessageReceived method
public class NotificationService extends GcmListenerService {
public static final int notifyID = 9001;
public static final String appname = "FM Ninja";
NotificationCompat.Builder builder;
public NotificationService() {
// super("GcmIntentService");
}
#Override
public void onMessageReceived(String from, Bundle data) {
Intent resultIntent = null;
PendingIntent resultPendingIntent;
resultIntent = new Intent(this, HomeActivity.class);
resultPendingIntent = PendingIntent.getActivity(this, 0,
resultIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("title")
.setTicker("New Message !")
.setContentText("first message please")
.setSmallIcon(R.mipmap.cms_launch_icon);
// 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);
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
}
}
The problem is even after adding permission in Manifeast when a call is made from server onMessageReceived is never getting executed Please help me.
I will also post manifeast file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--GCM Permissions-->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.google.android.c2dm.permission.SEND"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<permission android:name="com.six30labs.cms.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.six30labs.cms.permission.C2D_MESSAGE" />
<application
android:name="com.six30labs.cms.general.VolleyRequestQueue"
android:allowBackup="true"
android:icon="#mipmap/cms_launch_icon"
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.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name=".LoginActivity" />
<activity android:name=".ForgotPassword" />
<activity android:name=".NoInternet" />
<activity android:name=".HomeActivity"/>
<activity android:name=".ComplaintDetailsSupervisor" />
<activity android:name=".ComplaintDetailsEmployee" />
<activity android:name=".NavBarProfile" />
<activity android:name=".ComplaintDetailsWorker" />
<activity android:name=".AssignedDetailSupervisor" />
<activity android:name=".AcceptedComplaintDetailsWorker" />
<activity android:name=".VerifyDetailSupervisor"/>
<activity android:name=".ManagerComplaintListActivity"/>
<!--<service android:name="com.six30labs.cms.storage.RegistrationIntentService"
android:exported="false"/>-->
<receiver
android:name="com.six30labs.cms.general.GcmBroadcastReceiver"
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="com.six30labs.cms"/>
</intent-filter>
</receiver>
<!-- Register Service -->
<service android:name="com.six30labs.cms.general.NotificationService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
</application>
Server side script
public class GCMNotification
{
private CMSEntities db = new CMSEntities();
static string gcmid = "AIzaSyB7HSIF1RIvkyCnpP6KtYiy6wQ-s6YBscY";
public void AssignEmpNotification(string employeeid)
{
long id = Convert.ToInt64(employeeid);
PushBroker pushBroker = new PushBroker();
pushBroker.RegisterGcmService(new GcmPushChannelSettings(gcmid));
pushBroker.QueueNotification(new GcmNotification().ForDeviceRegistrationId("APA91bGElkVodLyubuMM90TEnfUMab0Fs6JudsjXcgIUrTrT8Zk3GezKYWc9w2gGs6pzLLq_nPSZCXU30M5iYKdRJcKZnkafWuwhnihZQ88vcwUrKhiQn6eWSqGrLCeHFblVT09IR7jy")
.WithJson(#"{""message"":""Hi Hello" + "wsfdasd" + #""",""title"":""title" + "vendorBids" + #""",""Bidsid"":""" + "1" + #""",""Eventdate"":""" + "2/2/2016" + #""",""vendorname"":""" + "name" + #"""}"));
pushBroker.StopAllServices();
}
}
The server needs to send http post request
to "https://android.googleapis.com/gcm/send" along with list of
registration ids and message as body data.
The body data is a combination of :
a. registration ids (which is a list of array)
b. message
The header is a combination of :
a. Content-Type
b. Authorization (key:project id)
List regIds = new ArrayList();
//add regIds to this list : regIds.add("value");
JSONObject data = new JSONObject ();
data.put("registration_ids", regIds);
data.put("Message", "Hello");
ApiKey is the value we received during project created in google store.
Map headers = new HashMap();
headers.put("Content-Type", "application/json");
header.put("Authorization","key=ApiKey");
After sending http post request. The google gcm server will send
the message to all users whose registration id is mentioned in http
request.
The android mobile will receive a notification from gcm server as response
which will be handled by GCMBroadcastReceiver.
Now NotificationService class will be invoked which will extent
IntentService.
In this class ,
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty() &&
GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
showNotification(intent.getStringExtra("Message"));
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
This method is calling "showNotification" method which has a string
parameter.
Use this message and show in notification using NotificationManager.
Hope this helps :)
Start logging the response that the server is getting after sending the notification payload to google servers. If there is a problem with the device token, you will get a detailed error like "Not Registered".
If the there is no problem in token, google server will respond you with success and message id.
Once you are assured that there is no problem with the device token, then we can think about the issues in the device code.
Other probable issue I can think of is that the SHA hash that you have added in the google developer console is not matching with the SHA hash of the keystore that you have signed the app with.
Add the SHA hash of debug.keystore as well as the production signing keystore.
I am facing an issue while start service for push notifications.
On Lollipop my app is crashing on start service for notifications receiver.
My start service code is.
Intent registrationIntent = new Intent(
"com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app",
PendingIntent.getBroadcast(this, 0, new Intent(), 0));
registrationIntent.putExtra("sender", "KEY");
SplashScreen.this.startService(registrationIntent);
Menifest.xml Code
<receiver
android:name="com.example.notifications.C2DMReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<!-- Receive the actual message -->
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.app.example" />
</intent-filter>
<!-- Receive the registration id -->
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.app.example" />
</intent-filter>
</receiver>
I faced same problem in my app.
Follow this link
I hope you will solve this problem.
And little bit explanation regarding your issue.
Download and add gcm.jar in your project lib folder.
And Add below code in your java class where you want to register.
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
// Check if regid already presents
if (regId.equals("")) {
// Register with GCM
GCMRegistrar.register(this, "SENDERKEY");
} else {
// Device is already registered on GCM Server
if (GCMRegistrar.isRegisteredOnServer(this)) {
String df = "dfd";
} else {
GCMRegistrar.register(this, "SENDERKEY");
}
}
Now you create a class GCMIntentService.java and below code in it.
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService ";
private static Context mContext;
public GCMIntentService() {
super("SENDERKEY");
}
#Override
protected void onRegistered(Context context, String registrationId) {
Debuger.e(TAG, "Device registered: regId = " + registrationId);
}
#Override
protected void onUnregistered(Context context, String registrationId) {
Debuger.e(TAG, "Device unregistered");
}
#Override
protected void onMessage(Context context, Intent intent) {
Debuger.e(TAG, "Received message");
mContext = context;
String message = intent.getExtras().getString("message");
if (message != null) {
Debuger.e(TAG + "onMessage", "message = " + message);
} else {
message = "";
}
}
#Override
protected void onDeletedMessages(Context context, int total) {
// Debuger.e(TAG, "Received deleted messages notification");
}
#Override
public void onError(Context context, String errorId) {
// Debuger.i(TAG, "Received error: " + errorId);
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
// Debuger.e(TAG, "Received recoverable error: " + errorId);
return super.onRecoverableError(context, errorId);
}
}
And in your AndroidMenifest.xml file add below
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<permission
android:name="com.example.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<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.example.gcm" />
</intent-filter>
</receiver>
<service android:name="com.example.gcm.GCMIntentService" />