Hi in the below code I am getting the regId showing empty.but username and password values working perfectly.But I am not getting why that device id was showing empty.
after clicking the register button it's showing registered with GCM.
class
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 username;
public static String password;
#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();
username = i.getStringExtra("username");
password = i.getStringExtra("password");
// 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, username, password, 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();
}
}
logcat
04-22 04:05:46.389: E/UnRegister Receiver Error(2355): > Receiver not registered: com.google.android.gcm.GCMBroadcastReceiver#4175aa98
Creating a new project using google's console with the same name as application's name in eclipse helped me to solve this problem.
Try This... Fisrt Check google play service
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
mRegistrationId = getRegistrationId(mContext);
if (mRegistrationId.isEmpty()) {
try {
registerInBackground(senderId);
} catch (Exception e) {
Toast.makeText(mContext, "Unsupported for this device", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("TAG", mRegistrationId);
}
} else {
Log.i(TAG, "No valid Google Play Services found.");
}
Checking google play service
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
Toast.makeText(mContext, "This device is not supported.", Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
Get RegistrationId is here
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
assert registrationId != null;
if (registrationId.isEmpty()) {
//Log.i(TAG, "Registration not found.");
return "";
}
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
And here is registerInBackground Async Task
private void registerInBackground(final String senderID) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... voids) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(mContext);
}
try {
mRegistrationId = gcm.register(senderID);
} catch (UnsupportedOperationException e) {
Toast.makeText(mContext, "Unsupported", Toast.LENGTH_SHORT).show();
}
msg = "Device registered, registration ID=" + mRegistrationId;
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String s) {
Log.d(TAG, s);
}
}.execute(null, null, null);
}
This is working for me. Hope It will help you.
Related
I am new to Android and this is first time I am doing push notification and I am getting Registration Id from cloud server in my Log System.out.println("Registration ID: " + registrationId); GCMIntentService Class but I am not able to send it to backend as a param with URL on my Login Screen. I am posting my code here. please help me guys.
CommonUtilities.java
public final class CommonUtilities {
/**
* Base URL
*/
public static final String SERVER_URL ="";
/**
* Google API project id registered to use GCM.
*/
// date 16 april 2015
public static final String SENDER_ID = "332948388069";
// API_Key=AIzaSyCBpVn9J2TWxPZDqyilCssUh5dbphQQtWE
/**API_Key=AIzaSyDsAQ_ynBJNPCOstGcDjAwRReDWF5uYsc0
* Tag used on log messages.
*/
public static final String TAG = "Sample";
/**
* Intent used to display a message in the screen.
*/
public static final String DISPLAY_MESSAGE_ACTION = "com.xxxxxxxx.DISPLAY_MESSAGE";
/**
* Intent's extra that contains the message to be displayed.
*/
public static final String EXTRA_MESSAGE = "message";
/**
* Notifies UI to display a message.
* <p>
* This method is defined in the common helper because it's used both by the
* UI and the background service.
*
* #param context
* application's context.
* #param message
* message to be displayed.
*/
public static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
}
GCMIntentService.java
import static com.xxxxxx.CommonUtilities.SENDER_ID;
import static com.xxxxxx.CommonUtilities.displayMessage;
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");
ServerUtilities.register(context, 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.mipmap.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = "Testing";
Intent notificationIntent = new Intent(context, Home_Screen.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);
}
}
Login.java
public class Login extends AppCompatActivity {
EditText edit_email, edit_password;
String email, password;
Button btn_submit;
ProgressDialog dialog;
TextView tv_count, attempt;
String value, url = "http://xxxxxxxxxxx.php?caseid=5",
forget_url = "http://xxxxxxxxxx.php?caseid=7";
Parser parser = new Parser();
TextView txt_signup, forgot_password;
String emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
int count = 3;
String devicetype = "android",deviceid,regid;
AsyncTask<Void, Void, Void> mRegisterTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
attempt = (TextView) findViewById(R.id.attempt);
attempt.setVisibility(View.GONE);
tv_count = (TextView) findViewById(R.id.count);
tv_count.setVisibility(View.GONE);
forgot_password = (TextView) findViewById(R.id.forgot_password);
edit_email = (EditText) findViewById(R.id.edit_email);
edit_password = (EditText) findViewById(R.id.edit_password);
btn_submit = (Button) findViewById(R.id.btn_submit);
txt_signup = (TextView) findViewById(R.id.txt_signup);
txt_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Login.this, SignUp.class));
finish();
}
});
deviceid = Secure.getString(Login.this.getContentResolver(), Secure.ANDROID_ID);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cm.getActiveNetworkInfo();
if (nf != null && nf.isConnected() == true)
{
checkNotNull(CommonUtilities.SERVER_URL, "SERVER_URL");
checkNotNull(CommonUtilities.SENDER_ID, "SENDER_ID");
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
//Register Device on GCM Server
registerReceiver(mHandleMessageReceiver,new IntentFilter(CommonUtilities.DISPLAY_MESSAGE_ACTION));
regid = GCMRegistrar.getRegistrationId(this);
if (regid.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, CommonUtilities.SENDER_ID);
} else {
// Device is already registered on GCM, check server.
// if (GCMRegistrar.isRegisteredOnServer(this)) {
// // Skips registration.
// } 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.
// 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, regid);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
// }
}
} else {
// do nothing
}
btn_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginTask().execute();
});
}
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(
getString(R.string.error_config, name));
}
}
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(CommonUtilities.EXTRA_MESSAGE);
}
};
public class LoginTask extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Login.this);
dialog.setIndeterminate(false);
dialog.setMessage("Please Wait....");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected JSONObject doInBackground(String... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("deviceid", deviceid));
nameValuePairs.add(new BasicNameValuePair("devicetype",devicetype));
nameValuePairs.add(new BasicNameValuePair("regid", regid));
System.out.println("email: "+email+" deviceid: "+deviceid+" devicetype: "+devicetype+" regisid: "+regid);
JSONObject json = parser.getJSONFromUrl(url, nameValuePairs);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
dialog.dismiss();
try {
int result = json.getInt("udata");
if (result == 1) {
SaveSharedPreference.setUserEmail(Login.this, email);
Intent intent = new Intent(Login.this, Home_Screen.class);
startActivity(intent);
finish();
}
if (result == 2) {
Toast toast = Toast.makeText(getApplicationContext(), "Email id or password not correct", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
tv_count.setVisibility(View.VISIBLE);
attempt.setVisibility(View.VISIBLE);
// tv_count.setBackgroundColor(Color.RED);
count--;
tv_count.setText(Integer.toString(count));
if (count == 0) {
btn_submit.setEnabled(false);
}
}
if (count == 0) {
Toast.makeText(Login.this,"something went wrong",Toast.LENGTH_SHORT).show();
btn_submit.setEnabled(false);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Exception", "" + e.toString());
}
}
}
ServerUtilities.java
import static com.xxxxxx.CommonUtilities.SERVER_URL;
import static com.xxxxxx.CommonUtilities.displayMessage;
public class ServerUtilities {
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLI_SECONDS = 2000;
private static final Random random = new Random();
/**
* Register this account/device pair within the server.
*
*/
static void register(final Context context, final String regId) {
Log.e("registering(regId = ", "" + regId + ")");
String serverUrl = SERVER_URL;
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
// Once GCM returns a registration id, we need to register on our server
// As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
Log.d("Attempt #","" + i + " to register");
try {
displayMessage(context, context.getString(
R.string.server_registering, i, MAX_ATTEMPTS));
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, true);
String message = context.getString(R.string.server_registered);
CommonUtilities.displayMessage(context, message);
return;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
Log.e("Failed to register" ,""+ i + ":" + e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
Log.d("Sleeping for ","" + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
Log.d("Thread interrupted:","");
Thread.currentThread().interrupt();
return;
}
// increase backoff exponentially
backoff *= 2;
}
}
String message = context.getString(R.string.server_register_error,
MAX_ATTEMPTS);
CommonUtilities.displayMessage(context, message);
}
/**
* Unregister this account/device pair within the server.
*/
static void unregister(final Context context, final String regId) {
Log.i("unregistering(regId = ","" + regId + ")");
String serverUrl = SERVER_URL + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
String message = context.getString(R.string.server_unregistered);
CommonUtilities.displayMessage(context, message);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
String message = context.getString(R.string.server_unregister_error,
e.getMessage());
CommonUtilities.displayMessage(context, message);
}
}
/**
* Issue a POST request to the server.
*
* #param endpoint POST address.
* #param params request parameters.
*
* #throws IOException propagated from POST.
*/
private static void post(String endpoint, String params)throws IOException {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
connection_respones_String = new WebResponseClass();
HttpResponse httpResponse;
InputStream inputStream;
HttpConnectionParams.setConnectionTimeout(defaultHttpClient.getParams(), 180000);
HttpPost httpPost = new HttpPost(endpoint);
HttpEntity entity;
List<NameValuePair> params_post = new ArrayList<NameValuePair>();
params_post.add(new BasicNameValuePair("regId", params));
try {
entity = new UrlEncodedFormEntity(params_post);
} catch (final UnsupportedEncodingException e) {
// this should never happen.
throw new AssertionError(e);
}
// StringEntity se = new StringEntity(params_post);
// System.out.println("StringEntityyyyyyyyyy"+se);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type",
"application/x-www-form-urlencoded");
httpResponse = defaultHttpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
// connection_respones_String =
// convertInputStreamToString(inputStream);
connection_respones_String.setStrData(convertInputStreamToString(inputStream));
connection_respones_String.setResponse(httpResponse);
//if (httpResponse.getStatusLine().getStatusCode() == 200) {
//Jsonloginset set = Utill
//.getAuthenticationFromJson(connection_respones_String
//.getStrData());
//connection_respones_String.setData(set);
//}
System.out.println("result>>>>>>>>>>>>>>>"+connection_respones_String.getStrData());
}
// else
// connection_respones_String = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
e.printStackTrace();
}
System.out.println("qqqqqqqqqqq"
+ connection_respones_String.getStrData());
}
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
You are facing this problem at your Login because your are getting and sending the Reg_Id on the same screen so quickly it needs some some to get generated from the cloud server sometimes it not able to get and your param remains null. Try one thing get it on Splash Screen and save it to your SharedPreference and then send it on your Dashboard Screen.
make sure you enabled gcm in google play services in your project
I am using push notification in my project and it's working fine but it is not working when my app is not running. It show only when my app s open.
Here my GCMIntentService.java:
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) {
Toast.makeText(getApplicationContext(), "on res", 11).show();
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, "Your device "+registrationId);
ServerUtilities.register(context, "", "", registrationId);
}
/**
* Method called on device un registred
* */
#Override
protected void onUnregistered(Context context, String registrationId) {
Toast.makeText(getApplicationContext(), "on fail", 11).show();
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);
PowerManager.WakeLock sWakeLock;
//int pm = PowerManager.FromContext(context);
// sWakeLock = pm.NewWakeLock(WakeLockFlags.Partial, "GCM Broadcast Reciever Tag");
//sWakeLock.Acquire();
WakeLocker.acquire(getApplicationContext());
displayMessage(context, message);
/*if (extras.getString("message").length() != 0) {
createNotification(context, extras);
}*/
generateNotification(context, message);//registration id on gcm device registratio
// notifies user
WakeLocker.release();
}
/**
* 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, Login.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;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
And here my broadcast class:-
public class Login extends ActionBarActivity {
Button login;
JSONParserwithdata jsonParser = new JSONParserwithdata();
public static String RegId ="";
public static String deviceid ="";
public database db;
ConnectionDetector conDetector;
Boolean shutDown = false;
Boolean netStatus=false;
EditText school_id,mobile,password;
String user_id;
AsyncTask<Void, Void, Void> mRegisterTask;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Connection detector
ConnectionDetector cd;
String school_id_db,mobileno_db,pssword_db,device_id_db;
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
final AlertDialog ad=new AlertDialog.Builder(this).create();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
///code for push notification device registered
try{
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(Login.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.
Toast.makeText(getApplicationContext(), "id "+regId, Toast.LENGTH_LONG).show();
/*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);*/
}
}
}
catch(Exception e)
{
ad.setMessage(e.getMessage());
ad.show();
}
//end for device registration
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#66BF77")));
conDetector= new ConnectionDetector(this);
school_id=(EditText)findViewById(R.id.school_id);
password=(EditText)findViewById(R.id.password);
mobile=(EditText)findViewById(R.id.mobile_no);
login=(Button)findViewById(R.id.sign_in);
db=new database(this);
TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
device_id_db = tm.getDeviceId();
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//final AlertDialog ad=new AlertDialog.Builder(this).create();
String VRegId=RegId;
RegId=RegId.replace("Your device ", "");
int pos2=RegId.indexOf("Trying");
if(pos2>0)
RegId=RegId.substring(0,pos2);
if(mobile.getText().toString().length()!=0)
{
if(school_id.getText().toString().length()!=0)
{
if(password.getText().toString().length()!=0)
{
netStatus=conDetector.isConnectingToInternet();
if(netStatus)
{
AttemptLogin task = new AttemptLogin();
task.execute();
}
else
{
Toast.makeText(getBaseContext(), "Internet connection problem", Toast.LENGTH_LONG).show();
}
}
else
{
password.setError("Please enter password");
}
}
else
{
school_id.setError("Please enter school id");
}
}
else
{
mobile.setError("Please enter mobile number");
}
}
});
}
class AttemptLogin extends AsyncTask<String, String, String> {
String success_response;
int postpg=0;
String type;
String sc_id;
String logo_url;
String actionbar_title,target_data;
JSONArray targetrarry,userArray;
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setCanceledOnTouchOutside(false);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mobileno",mobile.getText().toString()));
params.add(new BasicNameValuePair("uid", school_id.getText().toString()));
params.add(new BasicNameValuePair("pass", password.getText().toString()));
params.add(new BasicNameValuePair("regid", RegId));
params.add(new BasicNameValuePair("deviceid", deviceid));
JSONArray mainjson = jsonParser.makeHttpRequest(
"http://ddlindialtd.com/webservice/service1.asmx/getSchool", "POST", params);
for(int i=0; i<mainjson.length(); i++)
{
JSONObject mainobj=mainjson.getJSONObject(i);
success_response=mainobj.getString("status");
JSONArray resultjsonarray = mainobj.getJSONArray("result");
for(int j=0; j<resultjsonarray.length(); j++)
{
JSONObject innerobj=resultjsonarray.getJSONObject(j);
type=innerobj.getString("Usertype");
logo_url=innerobj.getString("schoolLogo");
actionbar_title=innerobj.getString("schoolTitle");
sc_id=innerobj.getString("id");
targetrarry=innerobj.getJSONArray("targetdata");
userArray=innerobj.getJSONArray("userdata");
for(int k=0;k<userArray.length();k++)
{
JSONObject userjsonobj=userArray.getJSONObject(k);
user_id=userjsonobj.getString("vfromid");
}
}
}
} catch (Exception e) {
success_response = getBaseContext().getString(R.string.error)+","+e.getMessage();
}
return success_response;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if(file_url.equals("404 server error"))
{
Toast.makeText(getBaseContext(), file_url, Toast.LENGTH_LONG).show();
}
else
{
if(file_url.equals("success"))
{
if(type.equals("parent"))
{
mobileno_db=mobile.getText().toString();
school_id_db=school_id.getText().toString();
pssword_db=password.getText().toString();
db.store(user_id,type,mobileno_db,school_id_db,pssword_db,device_id_db,RegId,deviceid);
Intent intent=new Intent(Login.this,ListofClass.class);
intent.putExtra("Logo", logo_url);
intent.putExtra("Title", actionbar_title);
intent.putExtra("JSON", targetrarry.toString());
overridePendingTransition(R.animator.acitivity_transation, R.animator.activity_animation_2);
startActivity(intent);
}
else
{
mobileno_db=mobile.getText().toString();
school_id_db=school_id.getText().toString();
pssword_db=password.getText().toString();
db.store(user_id,type,mobileno_db,school_id_db,pssword_db,device_id_db,RegId,deviceid);
Intent intent=new Intent(Login.this,ListofClass.class);
intent.putExtra("Logo", logo_url);
intent.putExtra("Title", actionbar_title);
intent.putExtra("JSON", targetrarry.toString());
overridePendingTransition(R.animator.acitivity_transation, R.animator.activity_animation_2);
startActivity(intent);
}
}
else
{
Toast.makeText(getBaseContext(), "Unaouthorised Access", Toast.LENGTH_LONG).show();
}
}
}
}
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//ComponentName comp=new ComponentName(context.getPackageName(),GCMIntentService.class.getName());
//startWakefulService(context, intent.setComponent(comp));
//WakeLocker.acquire(getApplicationContext());
//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: " + newMessage, Toast.LENGTH_LONG).show();
//if(RegId.equals(""))
RegId=RegId+newMessage;
// 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();
}
}
Try to give WAKE_LOCK permission in Android Manifest file
<uses-permission android:name="android.permission.WAKE_LOCK" />
It will make CPU awake if phone goes to sleep
I have added the module GCM and it works with APPENGINE correcty. I've done the documentation says to register and receive messages from Endpoint.
Now I wan't to unregister a device and I don't know how do it....
Any idea ?
I have tested gcm.unregister() and regService.unregister(Idphone).execute() but it doesn't work
I've tried to do a new AsyncTask class GcmUnRegistrationAsyncTask extends AsyncTask {
private static Registration regService = null;
private GoogleCloudMessaging gcm;
private Context context;
private static final String SENDER_ID = "892982546498";
public GcmUnRegistrationAsyncTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(Void... params) {
if (regService == null) {
Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://myproject.appspot.com/_ah/api/");
regService = builder.build();
}
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
String regId = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regId;
MainActivity.token=regId;
regService.unregister(regId).execute();
gcm.unregister();
} catch (IOException ex) {
ex.printStackTrace();
msg = "Error: " + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
// Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
Logger.getLogger("unREGISTRATION").log(Level.INFO, msg);
Toast.makeText(context, MainActivity.token, Toast.LENGTH_LONG).show();
}
}
I would like to show all devices too......
I would like to register/unregister the BroadcastReceiver which I am using to receive messages from GCM. I have declared and initialised the BroadcastReceiver.class in my onResume(), but after I unregister inside onPause() next time my app launches it wont send messages any more, only if I send the regId again and register with the GCM server as well.
Can the BroadcastReceiver be responsible for not sending the messages? Or is it essential to have the BroadcastReceiver registered in the Manifest file??
I would be really grateful for any suggestion.
UPDATE:
Interestingly if I register the BroadcastReceiver programatically, the GCM server gives a new regId all the time when registering the device itself on the GCM server, when the BroadcastReceiver is registered in the Manifest, the GCM server gives the same regId. WHY??
Methods for registering/unregistering:
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
receiver = new GcmBroadcastReceiver();
filter.addAction("com.google.android.c2dm.intent.RECEIVE");
filter.addAction("com.google.android.c2dm.intent.REGISTRATION");
filter.addCategory("com.taxidirectdriver");
registerReceiver(receiver, filter, "com.google.android.c2dm.permission.SEND", null);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Full MainActivity:
public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
private static final String PROPERTY_APP_VERSION = "appVersion";
GoogleCloudMessaging gcm;
String regid;
Context context;
AtomicInteger msgId = new AtomicInteger();
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleMap mMap;
public SharedPreferences pref;
public static String DNAME = "dname";
public static final String REGID="regid";
String driverName;
private static final float DEFAULTZOOM = 15;
private static final String TAG = null;
private static long locRefresh = 300000;
private static long fastestRefresh = 120000;
LocationClient mLocationClient;
Marker marker;
Geocoder geocoder;
List<Address> addresses;
ArrayList<Double> drivers = new ArrayList<Double>();
Map<String,Double> nameAndDistance = new HashMap<String, Double>();
String address;
OrdersDBHelper dbHelper;
private GcmBroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isOnline()){
pref = getSharedPreferences("SETTINGS_PREF", MODE_PRIVATE);
driverName = pref.getString(DNAME, "none");
if(driverName == null || driverName == "none") {
Intent i = new Intent(this, Registration.class);
startActivity(i);
} else {
// GCM startup
gcm = GoogleCloudMessaging.getInstance(this);
context = getApplicationContext();
regid = getRegistrationId(context);
pref = getSharedPreferences("SETTINGS_PREF", MODE_PRIVATE);
regid = pref.getString(REGID, "");
if (regid == null || regid.equals("")){
registerInBackground();
}
} // end of else statement
// Initiate Map if services exists
if (servicesOK() && isOnline() && isLocationOn()) {
setContentView(R.layout.map_activity);
if (initMap()) {
//Toast.makeText(this, "Ready To map!", Toast.LENGTH_SHORT).show();
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
}
else {
Toast.makeText(this, "Map Not Available!", Toast.LENGTH_SHORT).show();
}
}
else {
Intent conInt = new Intent(this, ConnDependencies.class);
conInt.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(conInt);
}
} else {
Intent conInt = new Intent(this, ConnDependencies.class);
conInt.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(conInt);
} //end is online
}
#Override
protected void onResume() {
super.onResume();
locRefresh = 300000;
fastestRefresh = 120000;
Log.i(TAG, "Resfresh interval set to "+ locRefresh + " millis");
/*
//experimental receiver registration
IntentFilter filter = new IntentFilter();
receiver = new GcmBroadcastReceiver();
filter.addAction("com.google.android.c2dm.intent.RECEIVE");
filter.addAction("com.google.android.c2dm.intent.REGISTRATION");
filter.addCategory("com.taxidirectdriver");
registerReceiver(receiver, filter, "com.google.android.c2dm.permission.SEND", null);
*/
if(isOnline() && isLocationOn()){
Log.i(TAG, "Location and internet ok!");
} else {
Intent conInt = new Intent(this, ConnDependencies.class);
conInt.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(conInt);
}
}
#Override
protected void onPause() {
super.onPause();
locRefresh = 21600000;
fastestRefresh = 21600000;
Log.i(TAG, "Resfresh interval set to "+ locRefresh + "(6 hours) millis");
//unregisterReceiver(receiver);
}
public void exitApp (){
Intent inn = new Intent(this, DialogAlert.class);
startActivity(inn);
//unregisterReceiver(receiver);
Log.i(TAG, "Receiver unregistered!");
finish();
}
public boolean isLocationOn(){
LocationManager locman = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(locman.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
return true;
}
return false;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
public void showOrders(View view) {
Intent intent = new Intent(this, ClientDetails.class);
startActivity(intent);
}
// Check for Play Services
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
}
else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
}
else {
Toast.makeText(this, "Cant Connect to Google Play services", Toast.LENGTH_SHORT).show();
}
return false;
}
// Initializing map
private boolean initMap(){
if (mMap == null){
SupportMapFragment mapFrag =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFrag.getMap();
}
return (mMap != null);
}
// My Location
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
//Toast.makeText(this, "Connected to current location service", Toast.LENGTH_SHORT).show();
LocationRequest request = LocationRequest.create();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setInterval(locRefresh);
request.setFastestInterval(fastestRefresh);
mLocationClient.requestLocationUpdates(request, this);
//Marking users location
Location currentLocation = mLocationClient.getLastLocation();
LatLng ll = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, DEFAULTZOOM);
mMap.animateCamera(update);
if (marker != null){
marker.remove();
}
MarkerOptions options = new MarkerOptions()
.title(driverName)
.position(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.driver_marker));
marker = mMap.addMarker(options);
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, DEFAULTZOOM);
mMap.animateCamera(update);
if (marker != null){
marker.remove();
}
MarkerOptions options = new MarkerOptions()
.title(driverName)
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.driver_marker));
//.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
marker = mMap.addMarker(options);
final int DEFAULT_TIMEOUT = 20 * 1000;
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(DEFAULT_TIMEOUT);
if (location.getLatitude() != 0) {
RequestParams params = new RequestParams();
params.put("NAME", driverName);
params.put("REGID", regid);
params.put("LAT", String.valueOf(location.getLatitude()));
params.put("LNG", String.valueOf(location.getLongitude()));
client.post("http://edmondvarga.com/android_dev/taxidirect/update_coor.php", params, new AsyncHttpResponseHandler() {
#Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
//Toast.makeText(getApplicationContext(), "ERROR UPDATING POSITION!", Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
Log.d("HTTP", "onSuccess, coordinates sent!");
}
});
}
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and the app versionCode in the application's
* shared preferences.
*/
private void registerInBackground()
{
new AsyncTask<Void, Void, String>()
{
#Override
protected String doInBackground(Void... params)
{
String msg = "";
try
{
if (gcm == null)
{
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(Globals.GCM_SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over
// HTTP, so it can use GCM/HTTP or CCS to send messages to your app.
sendRegistrationIdToBackend();
// For this demo: we use upstream GCM messages to send the
// registration ID to the 3rd party server
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
}
catch (IOException ex)
{
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
#Override
protected void onPostExecute(String msg)
{
//Toast.makeText(getApplicationContext(), "regId is: " + regid, Toast.LENGTH_SHORT).show();
}
}.execute(null, null, null);
}
/**
* Store regid and the app version in SETTINGS_PREF
*
*/
private void storeRegistrationId(Context context, String regid) {
int appVersion = getAppVersion(context);
pref = getSharedPreferences("SETTINGS_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(REGID,regid);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
/**
* Sends the registration ID to the 3rd party server via an upstream
* GCM message. Ideally this would be done via HTTP to guarantee success or failure
* immediately, but it would require an HTTP endpoint.
*/
private void sendRegistrationIdToBackend()
{
String name = driverName;
Log.d(Globals.TAG, "Driver name is: " + driverName + " " + "REGISTER USERID: " + regid);
new AsyncTask<String, Void, String>()
{
#Override
protected String doInBackground(String... params)
{
String msg = "";
try
{
Bundle data = new Bundle();
data.putString("name", params[0]);
data.putString("action", "com.taxidirect.gcmdemo.REGISTER");
String id = Integer.toString(msgId.incrementAndGet());
gcm.send(Globals.GCM_SENDER_ID + "#gcm.googleapis.com", id, Globals.GCM_TIME_TO_LIVE, data);
msg = "Sent registration";
}
catch (IOException ex)
{
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg)
{
//Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
}.execute(name);
}
/**
* Gets the current registration ID for application on GCM service, if there
* is one.
* <p>
* If result is empty, the app needs to register.
*
* #return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context)
{
pref = getSharedPreferences("SETTINGS_PREF", MODE_PRIVATE);
String registrationId = pref.getString(REGID, "");
if (registrationId == null || registrationId.equals(""))
{
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = pref.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion)
{
Log.i(Globals.TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* #return Application's version code from the {#code PackageManager}.
*/
private static int getAppVersion(Context context)
{
try
{
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
}
catch (NameNotFoundException e)
{
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.exitApp:
exitApp();
return true;
}
return super.onOptionsItemSelected(item);
}
}
RegIds for the same phone after 4 registering attempts on the GCM Server:
Records are: D1 : APA91bEYZYdKgdngfbxYIjyvhtWm-1ncGOBz1OUER8lM_BfnAwU8IwFAOkawMCgyETGTnHgTOUETKcfYUXUeRvDbEOEoSLexKNh6T9vo4FnBLD7ZajJ0FjahrTNTLrMIafzz0VPw3E5ApK4uCoUM6ibwETQrkDo2RQ
Records are: D2 : APA91bETu7NDrbBGhx4iSUB3YbYq3SG4ZitS_MFFL94CSk13hY_WhOf7HEwyshSnlb2iEmHja3T_qPq1PKfTPre1UGKHkGCpg3xW02HTwBhgp18kQoqUp-MEChN-BJqlDtnDh8A-dHXhGdCRYdd0ou_HYY-MQvOkxA
Records are: 3 : APA91bF2BM3UIg9eLk8Jkj3PwFTsvRD5-1p3CQ3QkFKkhfUm8rfbuchdfwITdErx4p8_L2XWu5f1dU6ZSn9L1uyjqNY6ZMvHsn4kXS2J6Csf1sdjGct444xZZl8P56bIqUaX5Deotm-4eUCD-RBEIHhBK24RTBvtuQ
Records are: 6 : APA91bFYWdORwtUP8b02RZjnL7UBrdBTk3_RRn818F1RV2kMF9T7eQvrGfjmg7qy61drJTlnFqORDmcxKnLiIGC13Gve9qYmO1xd2ZhJX72Llskpm_AWE8bSth7D_9iS6m-BSXcTe25vG4AMxOOmryfSbwR2VmwA-Q
If you dynamically register the receiver, it isn't helpful if you receive a message when the app is not running. See this post:
Dynamic register of C2DM receiver using registerReceiver
If you want to ignore messages when the app is not active, you can set flags. But it seems like dynamic registration is not a good plan either way.
Hi In My Application I used this site for sending push notification using gcm concept androidhive.info . I am testing in localhost to server that one its working fine and no of devices also it showing after detecting the emulator registration id and then sending notification.Now that details also stored in local database.
Now My problem I am receiving any push notifications from server.
can anyone please help me and reslove it
AlertDialogManager.java:
public class AlertDialogManager {
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
}
CommonUtilities.java
public final class CommonUtilities {
// give your server registration url here
static final String SERVER_URL = "http://10.0.2.2/gcm_server_php/register.php";
// Google project id
static final String SENDER_ID = "907381889394";
static final String TAG = "AndroidHive GCM";
static final String DISPLAY_MESSAGE_ACTION =
"com.androidhive.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);
}
}
ConnectionDetector.java:
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
GCMIntentService.java:
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(SENDER_ID);
}
#Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, "Your device registred with GCM");
Log.d("NAME", MainActivity.name);
ServerUtilities.register(context, MainActivity.name, MainActivity.email, registrationId);
}
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
ServerUtilities.unregister(context, registrationId);
}
#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);
}
#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);
}
#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);
}
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;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
MainActivity.java:
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);
}
}
}
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();
}
}
RegisterActivity.java:
public class RegisterActivity extends Activity {
// alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Internet detector
ConnectionDetector cd;
// UI elements
EditText txtName;
EditText txtEmail;
// Register button
Button btnRegister;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(RegisterActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if GCM configuration is set
if (SERVER_URL == null || SENDER_ID == null || SERVER_URL.length() == 0
|| SENDER_ID.length() == 0) {
// GCM sernder id / server url is missing
alert.showAlertDialog(RegisterActivity.this, "Configuration Error!",
"Please set your Server URL and GCM Sender ID", false);
// stop executing code by return
return;
}
txtName = (EditText) findViewById(R.id.txtName);
txtEmail = (EditText) findViewById(R.id.txtEmail);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Read EditText dat
String name = txtName.getText().toString();
String email = txtEmail.getText().toString();
// Check if user filled the form
if(name.trim().length() > 0 && email.trim().length() > 0){
// Launch Main Activity
Intent i = new Intent(getApplicationContext(), MainActivity.class);
// Registering user on our server
// Sending registraiton details to MainActivity
i.putExtra("name", name);
i.putExtra("email", email);
startActivity(i);
finish();
}else{
// user doen't filled that data
// ask him to fill the form
alert.showAlertDialog(RegisterActivity.this, "Registration Error!", "Please enter your details", false);
}
}
});
}
}
public final class ServerUtilities {
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLI_SECONDS = 2000;
private static final Random random = new Random();
static void register(final Context context, String name, String email, final String regId) {
Log.i(TAG, "registering device (regId = " + regId + ")");
String serverUrl = SERVER_URL;
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
params.put("name", name);
params.put("email", email);
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
// Once GCM returns a registration id, we need to register on our server
// As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
Log.d(TAG, "Attempt #" + i + " to register");
try {
displayMessage(context, context.getString(
R.string.server_registering, i, MAX_ATTEMPTS));
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, true);
String message = context.getString(R.string.server_registered);
CommonUtilities.displayMessage(context, message);
return;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
Log.d(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return;
}
// increase backoff exponentially
backoff *= 2;
}
}
String message = context.getString(R.string.server_register_error,
MAX_ATTEMPTS);
CommonUtilities.displayMessage(context, message);
}
static void unregister(final Context context, final String regId) {
Log.i(TAG, "unregistering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
String message = context.getString(R.string.server_unregistered);
CommonUtilities.displayMessage(context, message);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
String message = context.getString(R.string.server_unregister_error,
e.getMessage());
CommonUtilities.displayMessage(context, message);
}
}
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
Log.e("URL", "> " + url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
WakeLocker.java:
public abstract class WakeLocker {
private static PowerManager.WakeLock wakeLock;
public static void acquire(Context context) {
if (wakeLock != null) wakeLock.release();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "WakeLock");
wakeLock.acquire();
}
public static void release() {
if (wakeLock != null) wakeLock.release(); wakeLock = null;
}
}
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" />
<uses-permission android:name="android.permission.ACCESS_WIFI_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.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>
A couple of points for you to check out:
Make sure your emulator's Target API is one of the Google APIs *** -- not just Android ***
Make sure you have a Google account logged in on the emulator