Android GCM Registration Device - android

I am developing an application where i have to register my device with GCM but it is not registering my device. i have granted all permissions to the applications in the menifest
my log is here
Method to register onGCM is
public void register()
{
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
if (GCMRegistrar.isRegistered(this))
{
Log.d("info", GCMRegistrar.getRegistrationId(this));
}
final String regId = GCMRegistrar.getRegistrationId(this);
System.out.println("registration ID is " + regId);
if (regId.equals(""))
{
System.out.println("registration ID is " + regId);
GCMRegistrar.register(this, CommonUtilities.SENDER_ID);
Log.d("info", GCMRegistrar.getRegistrationId(this));
System.out.println("Get Reg ID: " + GCMRegistrar.getRegistrationId(this));
}
else
{
Log.d("info", "already registered as" + regId);
}
}
and my GCM service is
public class GCMService extends GCMBaseIntentService
{
public GCMService()
{
super(CommonUtilities.SENDER_ID);
}
public void generateNotification(Context context, String message)
{
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, OffersActivity.class);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS;
notificationManager.notify(0, notification);
}
#Override
protected void onError(Context arg0, String arg1)
{
}
#Override
protected void onMessage(Context arg0, Intent arg1)
{
Log.d("GCM", "RECIEVED A MESSAGE");
generateNotification(arg0, "New Offers Are Available");
}
#Override
protected void onRegistered(Context arg0, String arg1)
{
}
#Override
protected void onUnregistered(Context arg0, String arg1)
{
}
}
and my menifest is
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<!-- Map Location permissions -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Notification permissions -->
<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="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.READ_OWNER_DATA" />
<permission
android:name="myPackage.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<!-- Storage permissions -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Internet permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Call Phone permissions -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="cmyPackage.SplashScreen"
android:label="AppName"
android:theme="#android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="myPackage.CatagoriesActivity"
android:configChanges="keyboardHidden|orientation|keyboard"
android:theme="#android:style/Theme.NoTitleBar" >
</activity>
<activity
android:name="myPackage.OffersActivity"
android:configChanges="keyboardHidden|orientation|keyboard"
android:theme="#android:style/Theme.NoTitleBar" >
</activity>
<activity
android:name="myPackage.SettingsActivity"
android:configChanges="keyboardHidden|orientation|keyboard"
android:theme="#android:style/Theme.NoTitleBar" >
</activity>
<activity
android:name="myPackage.OfferDetailsAtivity"
android:configChanges="keyboardHidden|orientation|keyboard"
android:theme="#android:style/Theme.NoTitleBar" >
</activity>
<activity
android:name="myPackage.DealInfoActivity"
android:configChanges="keyboardHidden|orientation|keyboard"
android:theme="#android:style/Theme.NoTitleBar" >
</activity>
<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="myPackage" />
</intent-filter>
</receiver>
<service android:name=".GCMService" />
<uses-library android:name="com.google.android.maps" />
</application>
I/System.out(17369): Registering
D/GCMRegistrar(17369): resetting backoff for packageName
V/GCMRegistrar(17369): Registering app packageName of sendersID xxxxxxxxxxxxxx
registration id Still Empty
(17369): Not yet registered
i have multiple packages in my application
public final class CommonUtilities
{
public static final String SENDER_ID = "xxxxxxxxxxxxx";
static final String TAG = "AndroidHive GCM";
public static final String DISPLAY_MESSAGE_ACTION = "myPackage.pushNotifications.DISPLAY_MESSAGE";
static final String EXTRA_MESSAGE = "message";
static void displayMessage(Context context, String message)
{
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
}

You should include your log output so that we know what happens when you run your app. You should also take a look at the GCM demo and use that as your base because you seem to be missing some important code: http://code.google.com/p/gcm/source/browse/samples/gcm-demo-client/src/com/google/android/gcm/demo/app/DemoActivity.java
If you get your registration ID from GCM then you are registered with GCM (are you getting a registration ID?) and the next step is to register with your server. This should happen in the else of the following If block:
if (regId.equals(""))
And in onRegistered in your GCM service as well. That is the callback that will be triggered when your app is successfully registered with GCM. Getting the registration ID right after attempting to register will not output anything since the registration with GCM is asynchronous.

If it is not already resolved .. I guess This could be the cause of problem... add this
<uses-permission android:name="my_app_package.permission.C2D_MESSAGE" />
to your android manifest xml.
Hope it helps.

You have to enter your unique_ID(i.e. of 12 character) CommonUtilities.java
/**
* Google API project id registered to use GCM.
*/
static final String SENDER_ID = 123456789012; <----

Related

Push notification not coming when the app kills from the tab(Recent apps)?

I am searching for this from many days.but i could not get any solution.Notification is coming properly when the app in running or foreground state. but when the app kills from the recents apps tab(Task Manager) the notification would not arrive. i am so much frusted because of this problem. can anyone tell me what should i do for this.
This is my GcmBroadcastReceiver class :-
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{ ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
This is GcmIntentService class by which i send the notification :-
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
private final static String TAG = "GcmIntentService";
private Context mContext;
public GcmIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
Log.d(TAG, "Notification Data Json :" + extras.getString("message"));
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)) {
// This loop represents the service doing some work.
for (int i = 0; i < 5; i++) {
Log.d(TAG, " Working... " + (i + 1) + "/5 # "
+ SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
sendNotification(extras.getString("message"));
}
} // Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
} // Put the message into a notification and post it.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("KEY","aman");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setContentTitle("Telepoh")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
mBuilder.setContentIntent(contentIntent);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
mBuilder.setAutoCancel(true);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
private int getNotificationIcon() {
boolean useWhiteIcon = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.gcm : R.drawable.push_icon;
}
}
And This is my Manifest :-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="package_name"
android:versionCode="2"
android:versionName="1.2">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<permission android:name="android.permission.GET_ACCOUNTS" />
<permission android:name="android.permission.CAMERA" />
<permission
android:name="com.google.android.gcm.demo.app.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.google.android.gcm.demo.app.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:screenOrientation="portrait"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:icon">
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="API_KEY" />
<activity
android:name=".WelcomeActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:theme="#style/AppTheme.NoActionBar"></activity>
<activity
android:name=".LoginActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".RegisterActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".ForgetPasswordActivity" />
<activity android:name="pacahe_name.controller.GalleryUtil" />
<activity android:name="nl.changer.polypicker.ImagePickerActivity" />
<receiver
android:name="package_name.GCM.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name=package_name" />
</intent-filter>
</receiver>
<service android:name="package_name.GCM.GcmIntentService" />
<activity
android:name="com.facebook.FacebookActivity"
android:screenOrientation="portrait" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/fb_id" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
My problem is push notification working fine when the app in the run state and in the foreground state. But when app clean from the recents apps(Tab) then the notification is not coming.I tried package restarted but it does not working.If anyone know what i am doing wrong then please tell me.

In push notification when user clear the app from the task manager the notification is not coming?

I am using push notification in my app. it is working fine when the app is running or in the foreground state.but when the user clean the app from the task manager/tab then the notification is not coming. I tried many method like package restart and all. but i could not get the solution. if anyone know what i am doing wrong. please tell me.
This is my GcmBroadcastReceiver class :-
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{ ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
This is GcmIntentService class by which i send the notification :-
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
private final static String TAG = "GcmIntentService";
private Context mContext;
public GcmIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
Log.d(TAG, "Notification Data Json :" + extras.getString("message"));
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)) {
// This loop represents the service doing some work.
for (int i = 0; i < 5; i++) {
Log.d(TAG, " Working... " + (i + 1) + "/5 # "
+ SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
sendNotification(extras.getString("message"));
}
} // Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
} // Put the message into a notification and post it.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("KEY","aman");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setContentTitle("Telepoh")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
mBuilder.setContentIntent(contentIntent);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
mBuilder.setAutoCancel(true);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
private int getNotificationIcon() {
boolean useWhiteIcon = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.gcm : R.drawable.push_icon;
}
}
And This is my Manifest :-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="package_name"
android:versionCode="2"
android:versionName="1.2">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<permission android:name="android.permission.GET_ACCOUNTS" />
<permission android:name="android.permission.CAMERA" />
<permission
android:name="com.google.android.gcm.demo.app.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.google.android.gcm.demo.app.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:screenOrientation="portrait"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:icon">
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="API_KEY" />
<activity
android:name=".WelcomeActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:theme="#style/AppTheme.NoActionBar"></activity>
<activity
android:name=".LoginActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".RegisterActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".ForgetPasswordActivity" />
<activity android:name="pacahe_name.controller.GalleryUtil" />
<activity android:name="nl.changer.polypicker.ImagePickerActivity" />
<receiver
android:name="package_name.GCM.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name=package_name" />
</intent-filter>
</receiver>
<service android:name="package_name.GCM.GcmIntentService" />
<activity
android:name="com.facebook.FacebookActivity"
android:screenOrientation="portrait" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/fb_id" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
The push notification working fine when the app in the run state and in the foreground state. But My problem is when app clean from the task manager then the notification is not coming.I tried package restarted but it does not working.If anyone know what i am doing wrong then please tell me.

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);
}

GCMRegistrar.register does not work

I am Trying to use GCM on my app, but GCMRegistrar.register always returns empty string. Here is my Manifest :
<?xml version="1.0" encoding="utf-8"?>
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="net.andromedya.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="net.andromeya.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" />
<permission
android:name="net.andromedya.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<permission
android:name="net.andromedya.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true" />
<application
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Sherlock.Light" >
<activity
android:name="net.andromedya.activities.MainActivity"
android:hardwareAccelerated="true"
android:launchMode="singleTask"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="net.andromedya.activities.AcBuEkrani"
android:label="Example App"
android:screenOrientation="portrait"
android:theme="#style/Theme.Sherlock.Light.NoActionBar" >
<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.maps.v2.API_KEY"
android:value="AIza--------------------------AmmWJmePg" />
<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="net.andromedya.activities" />
</intent-filter>
</receiver>
<service android:name="net.andromedya.activities.GCMIntentService" />
</application>
Here is my broadcast receiver :
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(getActivity());
Toast.makeText(getActivity(), "New Message: " + newMessage,
Toast.LENGTH_LONG).show();
// Releasing wake lock
WakeLocker.release();
}
};
And intent service :
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, "gcm aliko", "gcm aliko#a.com",
registrationId);
}
/**
* 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.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
Here is my logcat : (there is no error or warning about this.)
onReceive: com.google.android.c2dm.intent.REGISTRATION
GCM IntentService class: net.andromedya.GCMIntentService
Acquiring wakelock
You are using "com.google.android.gcm.GCMBroadcastReceiver" for your broadcast receiver. That broadcast receiver expects the intent service class to be in the main package of your app, which I assume is net.andromedya, but your intent service is actually in net.andromedya.activities.
You should either move your GCMIntentService class to net.andromedya or override GCMBroadcastReceiver and specify the location of your GCMIntentService class.
Other problems in your manifest :
<uses-permission android:name="net.andromeya.permission.C2D_MESSAGE" />
should be
<uses-permission android:name="net.andromedya.permission.C2D_MESSAGE" />
and in your broadcast receiver declaration:
<category android:name="net.andromedya.activities" />
should be
<category android:name="net.andromedya" />
Note that if you are using a new version of Android, GCM may work without those two fixes, but it won't work on older versions.
Simply keep GCMIntentService and BroadcastReceiver classes in same package. it worked for me.

GCM: register the device [GCMRegistrar.register(this, SENDER_ID)]

I have a important delivery, i hope you can help me.
I have to use GCM.
I am using the file in the official guide in http://developer.android.com/guide/google/gcm/demo.html
I did "Setting Up the Server Using App Engine for Java" and it work.
My problem is the android application .Exactly I don't recive the id from GCM and so anytime my application try the registration.
Thanks a lot....
public class DemoActivity extends Activity {
TextView mDisplay;
AsyncTask<Void, Void, Void> mRegisterTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkNotNull(SERVER_URL, "SERVER_URL");
checkNotNull(SENDER_ID, "SENDER_ID");
// 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);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
registerReceiver(mHandleMessageReceiver,
new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
....
}
CommonUtilities
public final class CommonUtilities
{
static final String SERVER_URL = "http://127.0.0.1:8888/gcmdemo4/home";
static final String SENDER_ID = "843761346XXX";
...
}
GCMIntentService
public class GCMIntentService extends GCMBaseIntentService {
#SuppressWarnings("hiding")
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(SENDER_ID);
}
#Override
public void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, getString(R.string.gcm_registered));
ServerUtilities.register(context, registrationId);
}
.....
MY manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.registrazionegcm"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<permission
android:name="com.example.registrazionegcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.registrazionegcm.permission.C2D_MESSAGE" />
<!-- App receives GCM messages. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- GCM connects to Google 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" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="DemoActivity"
android:label="#string/app_name" >
<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.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="com.example.registrazionegcm" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
could you supply your code of "registerReceiver".
I had the same problem, when my SENDER_ID was wrong.
Try to check it again, and check your package too: com.example.registrazionegcm.GCMIntentService
Put some breakpoint in onError and onRegistered
For me, this code works:
#Override
public void run() {
GCMRegistrar.checkDevice(mContext);
GCMRegistrar.checkManifest(mContext);
String deviceToken = GCMRegistrar.getRegistrationId(mContext);
if (deviceToken.equals("")) {
GCMRegistrar.register(mContext, "XXXXXXXXXXXXXXX");
deviceToken = GCMRegistrar.getRegistrationId(mContext);
if(!deviceToken.equals("")){
GCMRegistrar.setRegisteredOnServer(mContext, true);
// register deviceToken on CommNotes srv
RequestMaker req = new RequestMaker(Constant.REQ_REGISTER_GCM, mContext);
//if unsuccessful, try again 5 times
for(int i = 0; i<5; i++){
Log.d("ComNotes", "registration id"+deviceToken);
if(req.doRequest(deviceToken) == ReturnCode.CODE_OK){
break;
}
}
}
//TODO manage unsuccess: display error : "No PUSH available"
} else {
Log.v("CommunityNotes", "Already registered "+deviceToken);
}
}

Categories

Resources