Android Programming: GCMIntentService Stuck at WakeLock - android

I had read the various solutions about WakeLock found here, such as adding Permission in the AndroidManifest.xml as well as ensuring the Constructor of GCMIntentService is set to public.
However, my code is still stuck at "Acquiring Wakelock"
The exact same code works seperately as an individual Android Application.
I am only encountering this error AFTER I integrate it into my Main Application.
The following are my code for GCM Intent Service:
package com.mp2012.ieatishootipostanalyzer.notifications;
import static com.mp2012.ieatishootipostanalyzer.notifications.CommonUtilities.SENDER_ID;
import static com.mp2012.ieatishootipostanalyzer.notifications.CommonUtilities.displayMessage;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
import com.mp2012.ieatishootipostanalyzer.R;
import com.mp2012.ieatishootipostanalyzer.notifications.MainActivity2;
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", MainActivity2.name);
ServerUtilities.register(context, MainActivity2.name, MainActivity2.email, 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, MainActivity2.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);
}
}
MainActivity
package com.mp2012.ieatishootipostanalyzer.notifications;
import static com.mp2012.ieatishootipostanalyzer.notifications.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.mp2012.ieatishootipostanalyzer.notifications.CommonUtilities.EXTRA_MESSAGE;
import static com.mp2012.ieatishootipostanalyzer.notifications.CommonUtilities.SENDER_ID;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gcm.GCMRegistrar;
import com.mp2012.ieatishootipostanalyzer.R;
public class MainActivity2 extends Activity {
// label to display gcm messages
TextView lblMessage;
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Connection detector
ConnectionDetector cd;
public static String name;
public static String email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity2.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Getting name, email from intent
Intent i = getIntent();
name = i.getStringExtra("name");
email = i.getStringExtra("email");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
lblMessage = (TextView) findViewById(R.id.lblMessage);
registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(context, name, email, regId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
/**
* Receiving push messages
* */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
/**
* Take appropriate action on this message
* depending upon your app requirement
* For now i am just displaying it on the screen
* */
// Showing received message
lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
WakeLocker.release();
}
};
#Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver Error", "> " + e.getMessage());
}
super.onDestroy();
}
}
The following is the code for AndroidManifest xml file
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="14" />
<!-- GCM connects to Internet Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="com.mp2012.ieatishootipostanalyzer.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.mp2012.ieatishootipostanalyzer.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- Network State Permissions to detect Internet status -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".login.DashboardActivity"
android:label="IEatIShootIPost" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".login.RegisterActivity"
android:label="IEatIShootIPost"
/>
<activity
android:name=".login.LogoutActivity"
android:label="IEatIShootIPost"
/>
<activity
android:name=".login.SuccessRegister"
android:label="IEatIShootIPost"
/>
<activity
android:name=".login.LoginActivity"
android:label="IEatIShootIPost"
/>
<activity
android:name=".login.CalorieProgressActivity"
android:label="IEatIShootIPost"
/>
<activity
android:name=".login.CalculateDRCIActivity"
android:label="IEatIShootIPost"
/>
<activity
android:name=".login.WIETActivity"
android:label="IEatIShootIPost"
/>
<activity
android:name=".login.NewFoodActivity"
android:label="IEatIShootIPost"
/>
<activity
android:name=".login.PieChartActivity"
android:label="IEatIShootIPost"
/>
<activity
android:name="org.achartengine.GraphicalActivity"
android:label="IEatIShootIPost"
/>
<activity
android:name=".facebook.MainActivity"
android:label="IEatIShootIPost"
/>
<activity
android:name=".notifications.MainActivity2"
android:configChanges="orientation|keyboardHidden"
android:label="IEatIShootIPost"
/>
<activity
android:name=".notifications.RegisterActivity"
android:label="IEatIShootIPost"
/>
<activity
android:name=".login.DashboardBurnCalorieActivity"
android:label="IEatIShootIPost"
/>
<activity
android:name=".login.ProgressBurnCalorieActivity"
android:label="IEatIShootIPost"
/>
<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.mp2012.ieatishootipostanalyzer" />
</intent-filter>
</receiver>
<service android:name=".notifications.GCMIntentService" />
</application>
Last but not least, the error from logcat
Registering app com.mp2012.ieatishootipostanalyzer of senders 74463753470
onReceive: com.google.android.com.c2dm.intent.REGISTRATION
GCM IntentService class: com.mp2012.ieatishootipostanalyzer.GCMIntentService
Acquiring wakelock
and it hangs....
Thanks !

Keep all the GCM related class in the main package, i.e where u r calling gcm registration. like this in your project package name com.mp2012.ieatishootipostanalyzer.

It may be the case that there are lot more packages under the main package and the GCM code need to put under another package. For example com.mp2012.ieatishootipostanalyzer.notification. This also can be done but you need to edit the GCM code provided by google cloud message system. This is in the GCMBroadcastReceiver:
protected String getGCMIntentServiceClassName(Context context)
{
String className = context.getPackageName() +".notification"+DEFAULT_INTENT_SERVICE_CLASS_NAME;
return className;
}
The the system will work.

Related

Android Push Notification service not start on Lollipop

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" />

Sending Push Notification From QuickBlox in Android

I've used the quickblox chat sample and it worked fine, But I wanted to use push notifications in it.. So I followed some tutorials and read the sample and just done like it.. But when I push notification from QuickBlox Admin Panel: Messages no thing happens in my application.. No Logs, No Notifications.. No Thing..!
I'm sure that the project number and api key are correct..
Here's the manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.quickblox.sample.chat"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="19" />
<permission
android:name="com.quickblox.sample.chat.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.quickblox.sample.chat.permission.C2D_MESSAGE" />
<!-- 5. Add the following permissions: -->
<!-- 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" />
<!-- Access to device info -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".ApplicationSingleton"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".ui.activities.SplashActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="#string/app_name"
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=".ui.activities.NewDialogActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait" />
<activity
android:name="com.quickblox.sample.chat.DialogsActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait" />
<activity
android:name=".ui.activities.ChatActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize" />
<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" />
<category android:name="com.quickblox.sample.chat" />
</intent-filter>
</receiver>
<!-- 2. Add the following intent service: -->
<service android:name=".GCMIntentService" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
GcmBroadcastReceiver :
package com.quickblox.sample.chat;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
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.
Log.d("Login", "Receiver - Received Message!");
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
GCMIntentService :
package com.quickblox.sample.chat;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.quickblox.sample.chat.definitions.Consts;
public class GCMIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private static final String TAG = GCMIntentService.class.getSimpleName();
private NotificationManager notificationManager;
public GCMIntentService() {
super(Consts.GCM_INTENT_SERVICE);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "new push");
Bundle extras = intent.getExtras();
GoogleCloudMessaging googleCloudMessaging = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = googleCloudMessaging.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
processNotification(Consts.GCM_SEND_ERROR, extras);
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
processNotification(Consts.GCM_DELETED_MESSAGE, extras);
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// Post notification of received message.
processNotification(Consts.GCM_RECEIVED, extras);
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
WakefulBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void processNotification(String type, Bundle extras) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
final String messageValue = extras.getString("message");
Intent intent = new Intent(this, DialogsActivity.class);
intent.putExtra(Consts.EXTRA_MESSAGE, messageValue);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(Consts.GCM_NOTIFICATION)
.setStyle(
new NotificationCompat.BigTextStyle()
.bigText(messageValue))
.setContentText(messageValue);
mBuilder.setContentIntent(contentIntent);
notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
I have the following code for registration in activity :
gcm = GoogleCloudMessaging.getInstance(this);
regId = getRegisterationId(this);
Log.d("Login", "ID: " + regId);
if (regId.isEmpty()) {
new Thread(new Runnable() {
#Override
public void run() {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(DialogsActivity.this);
}
regId = gcm.register(Consts.PROJECT_NUMBER);
Log.d("Login", "Registered! ID: " + regId);
runOnUiThread(new Runnable() {
#Override
public void run() {
subscribeToPushNotifications(regId);
}
});
} catch (Exception e) {
Log.d("Login", "Reg e: " + e);
}
}
}).start();
} else {
Log.d("Login", "Already Exist");
subscribeToPushNotifications(regId);
} gcm = GoogleCloudMessaging.getInstance(this);
regId = getRegisterationId(this);
Log.d("Login", "ID: " + regId);
if (regId.isEmpty()) {
new Thread(new Runnable() {
#Override
public void run() {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(DialogsActivity.this);
}
regId = gcm.register(Consts.PROJECT_NUMBER);
Log.d("Login", "Registered! ID: " + regId);
runOnUiThread(new Runnable() {
#Override
public void run() {
subscribeToPushNotifications(regId);
}
});
} catch (Exception e) {
Log.d("Login", "Reg e: " + e);
}
}
}).start();
} else {
Log.d("Login", "Already Exist");
subscribeToPushNotifications(regId);
}
public void subscribeToPushNotifications(String regId) {
String deviceId = ((TelephonyManager) getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
QBMessages.subscribeToPushNotificationsTask(regId, deviceId,
QBEnvironment.DEVELOPMENT,
new QBEntityCallbackImpl<ArrayList<QBSubscription>>() {
#Override
public void onSuccess(ArrayList<QBSubscription> result,
Bundle params) {
Log.d("Login", "Successfully Registered");
}
#Override
public void onError(List<String> errors) {
Log.d("Login", "e : " + errors);
}
});
}
private String getRegisterationId(Context context) {
SharedPreferences prefs = getGCMPreferences(context);
String registerationId = prefs.getString(PROPERTY_REG_ID, "");
if (registerationId.isEmpty()) {
Log.d("Login", "Not registered!");
return "";
}
return registerationId;
}
private SharedPreferences getGCMPreferences(Context context) {
return getSharedPreferences(DialogsActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
private void storeRegisterationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.commit();
}
And I get that registration done successfully.. :S
I've been searching for the solution for 2 days now :/ Any help will be appreciated.. Thanks.
I don't have enough reputation to comment, so I am putting this as a possible answer -
I have been working through the same for the last couple of days, and here are a couple of things to check:
When you set up the GCM API key, did you set any IPs? You should leave this blank to accept all.
When you say the registration is done successfully, do you mean you get the onSuccess Log message from subscribeToPushNotificationsTask? Check your device id; I was getting null for deviceId from:
String deviceId = ((TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
So instead I had to use
String deviceId = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
What options were you selecting in the Quickblox Admin Panel > Messages? Be sure you are selecting "GCM (Android Push)" under the channel option.
Lastly, make sure you are using all production or all development for your environments (QBEnvironment.DEVELOPMENT). I somehow ended up with a mix, and switched them all to production now.
My push notifications are now working, so perhaps I can help out more if you have specific questions.

Not receiving push notification from local server

I really need a help figure it out what really is wrong with my code. I am a newbie in android.
really no message from gcm to my android device. I cannot really receive any push notification. No activity in my logcat when i try to send a message from my local server as stated from androidhive tutorial. Please help.
Here some of the code:
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidhive.pushnotifications"
android:versionCode="1"
android:versionName="1.0" >
<!-- GCM requires Android SDK version 2.2 (API level 8) or above. -->
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<!-- GCM connects to Internet Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="com.androidhive.pushnotifications.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.androidhive.pushnotifications.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- Network State Permissions to detect Internet status -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />
<!-- Main activity. -->
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<!-- Register Activity -->
<activity
android:name=".RegisterActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Main Activity -->
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name" >
</activity>
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.androidhive.pushnotifications" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService"/>
</application>
</manifest>
Main Activity:
package com.androidhive.pushnotifications;
import static com.androidhive.pushnotifications.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.androidhive.pushnotifications.CommonUtilities.EXTRA_MESSAGE;
import static com.androidhive.pushnotifications.CommonUtilities.SENDER_ID;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gcm.GCMRegistrar;
public class MainActivity extends Activity {
// label to display gcm messages
TextView lblMessage;
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Connection detector
ConnectionDetector cd;
public static String name;
public static String email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Getting name, email from intent
Intent i = getIntent();
name = i.getStringExtra("name");
email = i.getStringExtra("email");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
lblMessage = (TextView) findViewById(R.id.lblMessage);
registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(context, name, email, regId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
/**
* Receiving push messages
* */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
/**
* Take appropriate action on this message
* depending upon your app requirement
* For now i am just displaying it on the screen
* */
// Showing received message
lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
WakeLocker.release();
}
};
#Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver Error", "> " + e.getMessage());
}
super.onDestroy();
}
}

Push Notification not Received in android

I am new to push notifications and I'm trying to send a push notification to a particular device which has already been registered to GCM service. I implemented my app according to this example
and modified accordingly in my program. However, I am not able to receive push notifications on the device.
Here is my code:
package com.markattendence.activites;
import static com.markattendence.activites.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.markattendence.activites.CommonUtilities.EXTRA_MESSAGE;
import static com.markattendence.activites.CommonUtilities.SENDER_ID;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gcm.GCMRegistrar;
import com.markattendence.activites.MainActivity.YourAsyncTaskLogin;
import com.markattendence.markattendence.R;
public class NotificationActivity extends Activity {
// label to display gcm messages
TextView lblMessage;
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Connection detector
ConnectionDetector cd;
private String userFName;
private String latitude;
private String longitude;
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_FNAME = "fname";
private static String KEY_EMAIL = "email";
private static String KEY_LNAME = "lname";
UserFunctions userFunction;
private JSONObject json;
public static String name;
public static String email;
SharedPreferences prefs;
public static final String MyPREFERENCES = "MyPrefs";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
cd = new ConnectionDetector(getApplicationContext());
prefs = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (prefs.contains("message")) {
lblMessage.setText(prefs.getString("message", ""));
}
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(NotificationActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Getting name, email from intent
Intent i = getIntent();
name = i.getStringExtra("uFName");
userFName = i.getStringExtra("uFName");
email = i.getStringExtra("email");
latitude = i.getStringExtra("latitude");
longitude = i.getStringExtra("longitude");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
lblMessage = (TextView) findViewById(R.id.lblMessage);
registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(),
"Already registered with GCM", Toast.LENGTH_LONG)
.show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(context, name, email, regId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
if(name != null){
userFunction = new UserFunctions();
new YourAsyncTaskLogin().execute();
}
}
/**
* Receiving push messages
* */
private final WakefulBroadcastReceiver mHandleMessageReceiver = new WakefulBroadcastReceiver() {
#Override
public void onReceive(Context context, Intent 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);
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
/**
* Take appropriate action on this message depending upon your app
* requirement For now i am just displaying it on the screen
* */
// Showing received message
lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(),
"New Message: asd" + newMessage, Toast.LENGTH_LONG).show();
prefs = context.getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("message", lblMessage.getText().toString());
editor.commit();
// Releasing wake lock
WakeLocker.release();
}
};
#Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver Error", "> " + e.getMessage());
}
super.onDestroy();
}
class YourAsyncTaskLogin extends AsyncTask<Void, Void, Void> {
private ProgressDialog _ProgressDialog;
private String userId;
#Override
protected void onPreExecute() {
// show your dialog here
_ProgressDialog = ProgressDialog.show(NotificationActivity.this,
"", "Loading", true);
}
#Override
protected Void doInBackground(Void... params) {
try {
json = userFunction.sendMessage(userFName,
" has marked attendence of ", "CheckIN", latitude,
longitude);
/*
* HttpClient Client = new DefaultHttpClient(); String
* SetServerString = "";
*
* // Create Request to server and get response
*
* HttpGet httpget = new HttpGet(
* "http://wibman.com/pnt/send_message.php?message=" + name +
* "checked in&Latitude=" + latitude + "&Longitude=" +
* longitude); ResponseHandler<String> responseHandler = new
* BasicResponseHandler(); SetServerString =
* Client.execute(httpget, responseHandler);
*/
// Show response on activity
// content.setText(SetServerString);
} catch (Exception ex) {
ex.printStackTrace();
// content.setText("Fail!");
}
return null;
}
protected void onPostExecute(Void result) {
try {
Log.e("aaaaaaaaaaaaaaaaaaaaaaaaaaa",
json.getString(KEY_SUCCESS));
if (json.getString(KEY_SUCCESS) != null) {
// loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
/*userId = json.getString(KEY_UID);
userFName = json.getString(KEY_FNAME);
userFName.replace("\"", "");
userId.replace("\"", "");
Log.e("uid=aaa", userId);
Log.e("nameuser", userFName);*/
Intent dashboard = new Intent(getApplicationContext(),
MainActivity.class);
// Close all views before launching
// Dashboard
startActivity(dashboard);
// Close Login Screen
finish();
} else {
// Error in login
// loginErrorMsg.setText("Incorrect username/password");
_ProgressDialog.cancel();
alert.showAlertDialog(NotificationActivity.this,
"Attendence Failed..",
"Mark Attendence Failed.", false);
// loginStatusTxtView.setText("Incorrect username/password");
}
} else {
// Error in login
// loginErrorMsg.setText("Incorrect username/password");
_ProgressDialog.cancel();
alert.showAlertDialog(NotificationActivity.this,
"Attendence Failed..", "Mark Attendence Failed.",
false);
// loginStatusTxtView.setText("Incorrect username/password");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", e.getMessage());
}
_ProgressDialog.dismiss();
}
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.markattendence.markattendence"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="com.markattendence.markattendence.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.markattendence.markattendence.permission.C2D_MESSAGE" />
<uses-permission android:name="com.markattendence.activites.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- Network State Permissions to detect Internet status -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature
android:name="android.hardware.camera.front"
android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/mmes_logo"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.markattendence.markattendence.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:name="com.markattendence.markattendence.MarkAttendenceActivity" >
</activity>
<activity android:name="com.markattendence.markattendence.NotificationActivity" >
</activity>
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.markattendence.markattendence" />
</intent-filter>
</receiver>
<service android:name="com.markattendence.markattendence.GCMIntentService" />
</application>
I am having a problem in receiving the notification. Server side code is working correctly.
My log cat says:
{"multicast_id":5884981605957538237,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1393495991926450%978fee92f9fd7ecd"}]}
The major problem is that, if device has the example app it get notification in that application rather than my customized application. And if I remove that application i don't get any notification. So i am confused that notification has to be received in my app rather than that of androidhive application but push notification is displayed in androidhive application. Please help me to solve this issue. Thanks in advance.
For sending the push to a specific device. First of all you need to pick the token from the FCM :
String token = FirebaseInstanceId.getInstance().getToken();
Then this unique token is used to send the push request from server post request. Please find the headers of the post request along with required structure of the body.
Headers
Content-Type 'application/json'
Authorization 'key=(server-key)'
Note: Not other than these values are allowed in headers. And here the 'server-key' is your browser key provide from FCM console.
Body For Push Request
{
"data": {
"NotificationDetailsID": 1131,
"MessageGroup": "HR",
"Message": "this is notification"
},
"to": "firebase-token-of-androidDevice"
}
This is the server side implementation and this will definitely work. As we have tested at our end. You will receive the push while the app is even closed.
You have some errors in your manifest that only cause problems on old Android versions :
Your packagge name is com.markattendence.markattendence.
Therefore you should change this :
<permission android:name="com.markattendence.markattendence.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
To this:
<permission android:name="com.markattendence.markattendence.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.markattendence.markattendence.permission.C2D_MESSAGE" />
And this:
<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.markattendence.activites" />
</intent-filter>
</receiver>
To this:
<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.markattendence.markattendence" />
</intent-filter>
</receiver>
IF you could send a notification and configure a GCM so the problem should be with network. Try to look if your ports are not blocked for notification (I had similar problem - I could send but not receive notification after unlocking ports I received notifications).

GCM register didnot work on my emulator

I had use GCM service on my app , I did my code after more resarches also from stack overflow members , and when I try to test the code on my emulator I didn't find any regiser info that tell me that my emulator is registered .Also I created my account on Google API to recienve any reports but I didn't find any thing. So I need your help on:
1- please check my code and till my when the error I will feedback you with complete example :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.elarabygroup"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<permission
android:name="com.example.elarabygroup.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.elarabygroup.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".ElarabyGroup"
android:label="#string/title_activity_elaraby_group" >
<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.elarabygroup" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
<!--
android:name=".GCMIntentService"
android:enabled="true" />
-->
</application>
</manifest>
package com.example.elarabygroup;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import com.google.android.gcm.GCMRegistrar;
public class ElarabyGroup extends Activity {
private String TAG;
private String SENDER_ID = "222874571774";
private WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_elaraby_group);
try {
Intent registrationIntent = new Intent(
"com.google.android.c2dm.intent.REGISTER");
/* Registering for GCM /An Android application needs to register with GCM servers before it can receive messages*/
registrationIntent.putExtra("app",
PendingIntent.getBroadcast(this, 0, new Intent(), 0));
registrationIntent.putExtra("sender", SENDER_ID);
startService(registrationIntent);
Log.i(TAG, "[checkNotifRegistration] checkDevice");
GCMRegistrar.checkDevice(this);
Log.i(TAG, "[checkNotifRegistration] checkManifest");
GCMRegistrar.checkManifest(this);
if (GCMRegistrar.isRegistered(this)) {
Log.i(TAG,
"[checkNotifRegistration] reg id : "
+ GCMRegistrar.getRegistrationId(this));
}
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
// SENDER_ID is my project id into google account url
GCMRegistrar.register(this, SENDER_ID);
Log.i(TAG,
"[checkNotifRegistration] reg id : "
+ GCMRegistrar.getRegistrationId(this));
} else {
Log.i(TAG, "[checkNotifRegistration] already registered as : "
+ regId);
}
} catch (Exception e) {
Log.e(TAG, "[checkNotifRegistration] Exception : " + e.getMessage());
e.printStackTrace();
}
/*
* GCMRegistrar.checkDevice(this); GCMRegistrar.checkManifest(this);
*
*
* final String regId = GCMRegistrar.getRegistrationId(this); if
* (regId.equals("")) { GCMRegistrar.register(this, "1111111111"); }
* else { Log.v(TAG, "Already registered"); }
*/
try {
ConnectivityManager con = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (con.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
&& con.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("No Internet connection");
AlertDialog alert = builder.create();
alert.show();
} else
{
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://m.elarabygroup.com");
}
} catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(e.getMessage().toString());
AlertDialog alert = builder.create();
String url = "http://m.elarabygroup.com/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
}
/*
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public final void onReceive(Context context, Intent intent) {
GCMIntenetService.runIntentInService(context, intent);
setResult(Activity.RESULT_OK, null, null);
}
}
*/
}
/*
* #Override public boolean onCreateOptionsMenu(Menu menu) {
* getMenuInflater().inflate(R.menu.activity_elaraby_group, menu); return true;
* } }
*/
package com.example.elarabygroup;
import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMRegistrar;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.provider.Settings.Secure;
import android.util.Log;
public class GCMIntenetService extends GCMBaseIntentService {
private static String GCM_SENDER_ID = "1111111111111";
public GCMIntenetService() {
super();
}
#Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
GCMRegistrar.setRegisteredOnServer(context, true);
}
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
if (GCMRegistrar.isRegisteredOnServer(context)) {
String regId = "";
Log.i(TAG, "unregistering device (regId = " + regId + ")");
GCMRegistrar.setRegisteredOnServer(context, false);
} else {
// This callback results from the call to unregister made on
// ServerUtilities when the registration to the server failed.
Log.i(TAG, "Ignoring unregister callback");
}
}
#Override
protected void onError(Context context, String errorId) {
// push error processing
}
#Override
protected void onMessage(Context arg0, Intent arg1) {
Log.i(TAG, "Received message");
Log.i(TAG, "EXTRAS" + arg1.getExtras());
// String message = getString(R.string.gcm_message);
generateNotification(arg0,
arg1.getStringExtra("Please download our new updates"));
// notifies user about message
}
private void generateNotification(Context arg0, String stringExtra) {
// TODO Auto-generated method stub
}
public static void registerInGCMService(Context context) {
GCM_SENDER_ID = Secure.getString(context.getContentResolver(),
Secure.ANDROID_ID);
if (!checkIsGCMServiceAvailable(context)) {
return;
}
final String regId = GCMRegistrar.getRegistrationId(context);
if (regId.equals("")) {
try {
GCMRegistrar.register(context, GCM_SENDER_ID);
} catch (Exception ex) {
}
} else {
// Already registered
}
}
public static boolean checkIsGCMServiceAvailable(Context context) {
try {
GCMRegistrar.checkDevice(context);
GCMRegistrar.checkManifest(context);
return true;
} catch (Throwable th) {
return false;
}
}
}
I had attached my log cat message
2- what about status in my Google API account
Service Status
Google Cloud Messaging for Android No known issues
first set your emulator target to Google API and add an google account to your emulator.
add google account to your emulator:
setting->account&sync-> Add account (from #curious_mind comment)
If the emulator is running Android 4.0.4 or later, this step is optional as GCM does not require an account from this version on.
for me it fixed the problem.
just you can use this emulator and test your application in this emulator i think it will work fine.
You can use an emulator for GCM functionality but you need to track some points as your emulator version should be 2.2 or above and contains Google API(must). Once you created this emulator AVD then follow the followig steps in emulator:
1.) goto Settings --> Accounts & Sync,
2.) then add a Google account and sync is on.
3.) Define internet permission in manifest file
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
4.) Define GCM related permissions in manifest
Once this is done, you should be ready to register for GCM and receive messages from it.
Go to your android SDK folder and open SDK Manager and install Google Cloud Messaging for Android Library under Extras section. (If you don’t see Google Cloud Messaging for Android Library update your SDK manager to latest version)
After installing the library it will create gcm.jar file in your Andoird_SDK_Folder\extras\google\gcm\gcm-client\dist. Later you need to add this .jar file to your android project.
First set your emulator target to Google API.
After launching emulator press Menu button goto Settings. Select Accounts & Sync. And then press Add Account button and add a Google account
Finally Test your Application on Simulator.

Categories

Resources