Push Notification is not showing when app is not running in android - android

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

Related

Unable to Send Register Id(GCM) with the web service on Login Acticity

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

how to start or call an onCreate in android in the same way or manner of VB6's Form_Load

my android app has let's say activity A and B. what i need is to start my activity B at startup without showing it and of course show activity A because it is the main activity.
here's my MainActivity code:
public class MainActivity extends Activity {
private static final String PROJECT_ID = "api-project-xxxxxxxxxxxxx";
AsyncTask<Void, Void, Void> mRegisterTask;
AlertDialogManager adm = new AlertDialogManager();
ConnectionDetector cd;
public static String billName;
public static String emailAdd;
public static String accntNum;
Button addDevice, showDevice, showDialog, register;
Switch swiGCM;
TextView txtRegStatusResult, txtBroadcastMsg;
private String registrationStatus = "Not yet registered";
private String broadcastMessage = "No broadcast message";
String[] arrContentTxt;
final Context ctx = this;
int notifCount = 0;
int x = 0;
int contentTxtLength;
Handler notifLauncher, notifStopper;
String contentTxt;
GlobalVariables gv = new GlobalVariables();
int delay = gv.reminderDelay;
int stopDelay = delay - (delay / 5);
Handler hand;
IntentFilter gcmFilter;
//new set of variables for billCompute
//for bill compute
int totalWatt;
int timerFirstRun;
int totalHour = 1;
double wattHourPerDay;
double kiloWattPerDay;
double kiloWattPerMonth;
//bill
int id;
int watt;
int stat;
String name;
//also for bill compute
double billPerMonth;
Double res;
//global variables
double costPerMonth = gv.costPerMonth;
Handler handler;
Handler adapter;
//end new variables
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addDevice = (Button)findViewById(R.id.btnAddDevice);
showDevice = (Button)findViewById(R.id.btnShowDevice);
showDialog = (Button)findViewById(R.id.btnShowDialog);
register = (Button)findViewById(R.id.btnMainRegister);
swiGCM = (Switch)findViewById(R.id.switchGCM);
txtRegStatusResult = (TextView)findViewById(R.id.txtStatus);
txtBroadcastMsg = (TextView)findViewById(R.id.txtBroadCastMsg);
txtRegStatusResult = (TextView) findViewById(R.id.lblStatus);
Log.d("Batelec", "initiating lblBillVal");
//ListViewForm.lblBillVal.setText("");
Log.d("Batelec", "initiated lblBillVal");
Intent i = getIntent();
billName = i.getStringExtra(billName);
emailAdd = i.getStringExtra(emailAdd);
accntNum = i.getStringExtra(accntNum);
//for local notif
Resources res = getResources();
arrContentTxt = res.getStringArray(R.array.notifContentText);
contentTxtLength = arrContentTxt.length;
Log.d("Batelec", "content txt length: "+contentTxtLength);
Log.d("Batelec", "starting ListViewForm activity");
startActivity(new Intent(MainActivity.this, ListViewForm.class));
showDialog.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
/*DialogFragment diag = new SwitchCheckChange();
diag.show(getFragmentManager(), "cbo Click");*/
showNotif();
}
});
gcmFilter = new IntentFilter();
gcmFilter.addAction("GCM_RECEIVED_ACTION");
useNotifLauncher();
//useNotifStopper();
//BillComputer.useHandler();
swiGCM.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Log.d("Batelec", "inside switch GCM");
if(swiGCM.isChecked()){
connectToGCMServer();
}
}
});
}
//connect to gcm
public void connectToGCMServer(){
//try{
Log.d("Batelec", "start gcm client");
//start gcm
cd = new ConnectionDetector(getApplicationContext());
Log.d("Batelec", "loaded connection detector");
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
adm.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to a working Internet connection", false);
// stop executing code by return
Log.d("Batelec", "not connecting to internet");
return;
}
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(ctx);
Log.d("Batelec", "device checked");
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(ctx);
Log.d("Batelec", "manifest checked");
registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
Log.d("Batelec", "registered receiver");
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(ctx);
Log.d("Batelec", "acquire registration id");
try{
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(this, SENDER_ID);
Log.d("Batelec", "registration id is null, registering device");
}
else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
Log.d("Batelec", "device already registered");
} 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.
Log.d("Batelec", "registering again using AsyncTask");
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, billName, emailAdd, accntNum, regId);
Log.d("Batelec", "registering user to server");
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}//end gcm
}catch(Exception e){
Log.d("Batelec", "GCM Client Err: "+e);
}
}
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
txtRegStatusResult.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);
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver Error", "> " + e.getMessage());
}
super.onDestroy();
}
public void registerClick(View v){
Intent i = new Intent(this, RegisterActivity.class);
startActivity(i);
}
//start countdown for showing local notif
public void useNotifLauncher(){
notifLauncher = new Handler(){
#Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
String string = bundle.getString("myKey");
Log.d("Batelec", "in handler string val: "+string);
try{
ListViewForm.lblBillVal.setText(string);
}
catch(Exception e){
Log.d("Batelec", "handler err: "+e);
}
gv.billVal = string;
Log.d("Batelec", "main gv.billVal: "+gv.billVal);
}
};
notifLauncher.postDelayed(runNotif, delay);
}
public Runnable runNotif = new Runnable(){
#Override
public void run() {
showNotif();
billCompute();
notifLauncher.postDelayed(runNotif, delay);
}
};
public void useNotifStopper(){
notifStopper = new Handler();
notifStopper.postDelayed(stopNotif, stopDelay);
}
//destroy local notif
public Runnable stopNotif = new Runnable(){
#Override
public void run() {
cancelNotification(x);
notifStopper.postDelayed(stopNotif, stopDelay);
}
};
// If the user changes the orientation of his phone, the current activity
// is destroyed, and then re-created. This means that our broadcast message
// will get wiped out during re-orientation.
// So, we save the broadcastmessage during an onSaveInstanceState()
// event, which is called prior to the destruction of the activity.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("BroadcastMessage", broadcastMessage);
}
// When an activity is re-created, the os generates an onRestoreInstanceState()
// event, passing it a bundle that contains any values that you may have put
// in during onSaveInstanceState()
// We can use this mechanism to re-display our last broadcast message.
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
broadcastMessage = savedInstanceState.getString("BroadcastMessage");
txtBroadcastMsg.setText(broadcastMessage);
}
// If our activity is paused, it is important to UN-register any
// broadcast receivers.
#Override
protected void onPause() {
unregisterReceiver(mHandleMessageReceiver);
super.onPause();
}
// When an activity is resumed, be sure to register any
// broadcast receivers with the appropriate intent
#Override
protected void onResume() {
super.onResume();
registerReceiver(mHandleMessageReceiver, gcmFilter);
}
//add device button
public void addClick(View v){
Intent i = new Intent(this, AddDeviceForm.class);
startActivity(i);
}
//show device button
public void showClick(View v){
Toast.makeText(getBaseContext(), "Please wait...", Toast.LENGTH_LONG).show();
Intent i = new Intent(this, ListViewForm.class);
startActivity(i);
}
//show local notif
public void showNotif(){
contentTxt = arrContentTxt[notifCount];
Log.d("Batelec", "main notifCount: "+notifCount);
Bundle b = new Bundle();
b.putInt("notifCountNum", notifCount);
Uri notifSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent i = new Intent(MainActivity.this, NotifReceiver.class);
i.putExtras(b);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, (int)(Math.random()*100), i, 0);
Notification notif = new Notification.Builder(this)
.setContentTitle("MyPower Reminder")
.setContentText(contentTxt)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pi)
.setSound(notifSound)
.addAction(0, "View Full Reminder", pi)
.build();
NotificationManager notifMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notifMgr.notify(0, notif);
notifCount++;
if(notifCount == contentTxtLength){
notifCount = 0;
}
}
//destroy local notif
public void cancelNotification(int notificationId){
if (Context.NOTIFICATION_SERVICE!=null) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
nMgr.cancel(notificationId);
}
}
public void billCompute(){
TodoItemDatabase td = new TodoItemDatabase(ctx);
Cursor cur = td.getActiveDevice();
if(timerFirstRun == 0){
timerFirstRun++;
Log.d("batelec", "timer = 0");
}
else{
try{
if(cur != null){
Toast.makeText(ctx, "1 hour elapsed", Toast.LENGTH_LONG).show();
cur.moveToFirst();
for(int x = 1; x <= cur.getCount(); x++){
id = cur.getInt(cur.getColumnIndex("_id"));
name = cur.getString(cur.getColumnIndex("deviceName"));
watt = cur.getInt(cur.getColumnIndex("deviceWattage"));
stat = cur.getInt(cur.getColumnIndex("deviceStatus"));
totalWatt = totalWatt + watt;
Log.d("batelec", "id: " + id + " name: " + name + " watt: " + watt + " status: " + stat);
cur.moveToNext();
}
//totalWatt = 125;
Log.d("batelec", "total watt: "+totalWatt);
wattHourPerDay = totalWatt;//all active device wattage
Log.d("batelec", "wattPerHour: "+wattHourPerDay+" (totalWatt)");
kiloWattPerDay = wattHourPerDay / 1000;//all device watts divided by 1000 watts = 1 kW
Log.d("batelec", "kilowatt per day: "+kiloWattPerDay+" (wattPerHour / 1000)");
kiloWattPerMonth = (wattHourPerDay * 30) / 1000;//watts per month
Log.d("batelec", "kiloWatt per month: "+kiloWattPerMonth+" ((wattPerHour * 30) / 1000)");
billPerMonth = kiloWattPerMonth * costPerMonth;//estimated bill per month
Log.d("batelec", "bill per month: "+billPerMonth+" (kiloWattPerMonth * costPerMonth)");
//Double res;
DecimalFormat df = new DecimalFormat("#.##");
res = Double.valueOf(df.format(billPerMonth));
Log.d("batelec", "new bill: "+res);
//ListViewForm.lblBillVal.setText(String.valueOf(res));
Message msg = notifLauncher.obtainMessage();
Bundle bundle = new Bundle();
Log.d("Batelec", "res val: "+String.valueOf(res));
bundle.putString("myKey", String.valueOf(res));
msg.setData(bundle);
notifLauncher.sendMessage(msg);
}
}catch(Exception e){
Log.d("batelec", "MainErr: "+e);
}
}
}
}
as you can see i already used startActivity in my app. but as what i have said earlier, i just want to start activity B and not show it, like how we can call a Form_Load in VB6. if their is a way to hide activity B if it starts, can you teach me how in the most detailed way possible. i'll appreciate it

regId giving empty in android gcm

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.

How to make notification appear only in top?

So I have this code
public class notif extends Activity {
private static final int NOTIFY_ME_ID=1337;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final NotificationManager mgr=(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification note=new Notification(R.drawable.icon,"New Problem ",System.currentTimeMillis());
note.flags|=Notification.FLAG_AUTO_CANCEL;
PendingIntent i=PendingIntent.getActivity(this, 0,new Intent(this,list.class), 0);
note.setLatestEventInfo(this,"Problem Occured","Click to see the problem",i);
mgr.notify(NOTIFY_ME_ID,note);
}
This code is about making notifications but i want it to just appear on my notification on top an not opening any page at first so it's like the notification can appear in the main menu without opening any page at first like.the sms notification that appear on top only without having to see the entire sms until we click the notification so can someone help me with this? :)
Create a class NotificationAlert and paste the code below there:
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
public class NotificationAlert extends Activity {
private static final int NOTIFY_ME_ID=1337;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification_alert);
/*********** Create notification ***********/
final NotificationManager mgr=
(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification note=new Notification(R.drawable.stat_notify_chat,
"Android Example Status message!",
System.currentTimeMillis());
// This pending intent will open after notification click
PendingIntent i=PendingIntent.getActivity(this, 0,
new Intent(this, NotifyMessage.class),
0);
note.setLatestEventInfo(this, "Android Example Notification Title",
"This is the android example notification message", i);
//After uncomment this line you will see number of notification arrived
//note.number=2;
mgr.notify(NOTIFY_ME_ID, note);
}
}
Create a class NotifyMessage and paste the code below there:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class NotifyMessage extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView txt=new TextView(this);
txt.setText("Activity after click on notification");
setContentView(txt);
}
}
I think I know now that i have to use service and this is the code for making that service hope it helps other
public class servicenotif extends Service {
private static final String TAG = "servicenotif";
private static final int NOTIFY_ME_ID=1337;
private String url="Your URL";
SharedPreferences mPrefs;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
//Untuk bikin alarm yang ngecek ke database setiap 30 detik
Log.d(TAG, "onCreate");
Intent i = new Intent(this, servicenotif.class);
PendingIntent pintent = PendingIntent.getService(this, 0, i,0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30*1000, pintent);
}
#Override
public void onStart(Intent intent, int startId) {
//buat preference
new LoginAsyncTask().execute();
//Note: You can start a new thread and use it for long background processing from here.
}
class LoginAsyncTask extends AsyncTask<String, Integer, String> {
String response = "";
ProgressDialog dialog;
//step2
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
//publishProgress(190);
mPrefs = getSharedPreferences("Preference", Context.MODE_PRIVATE);
//ngambil data preference
String txtTransID=mPrefs.getString("tid", "");
if(txtTransID.equals("")){
txtTransID="0";
}
int t=Integer.valueOf(txtTransID);
//membuat notifikasi yang muncul apabila ada problem dan hanya muncul lagi apabila ada problem baru
JSONObject json = JSONfunctions.getJSONfromURL("Your URL");
JSONObject js = JSONfunctions.getJSONfromURL("Your URL");
JSONObject j = JSONfunctions.getJSONfromURL("Your URL");
try{
JSONArray makanan = json.getJSONArray("makanan");
for(int i=0;i<makanan.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonobj = makanan.getJSONObject(i);
map.put("id",jsonobj.getString("Status"));
//mengecek status yang berubah dari nol menjadi 1
if(jsonobj.getString("Status").equals("1")){
JSONArray aku=js.getJSONArray("makanan");
for(int a=0;a<aku.length();a++)
{
HashMap<String, String> mp = new HashMap<String, String>();
JSONObject jsb = aku.getJSONObject(a);
mp.put("take", jsb.getString("Taken"));
//mengecek Taken yang belum diambil
if(jsb.getString("Taken").equals("null")){
JSONArray tid=j.getJSONArray("makanan");
for(int Ti=0;Ti<tid.length();Ti++){
HashMap<String,String> trans=new HashMap<String, String>();
JSONObject jo=tid.getJSONObject(Ti);
trans.put("trans", jo.getString("Trans_ID"));
int TID;
//mengecek Trans_ID yang ditambahkan apa ada yang baru atau tidak
if(jo.getString("Trans_ID").equals("")){
TID=0;
}
else{
TID=Integer.valueOf(jo.getString("Trans_ID"));
}
if(t<TID){
Editor editor = mPrefs.edit();
editor.putString("tid", jo.getString("Trans_ID"));
editor.commit();
map.put("nama", jsonobj.getString("Andon_Type"));
map.put("harga", jsonobj.getString("Line"));
String andon=jsonobj.getString("Andon_Type");
String line=jsonobj.getString("Line");
NotificationManager mgr=(NotificationManager)servicenotif.this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification note=new Notification(R.drawable.icon,"New Problem ",System.currentTimeMillis());
note.flags|=Notification.FLAG_AUTO_CANCEL;
PendingIntent b=PendingIntent.getActivity(servicenotif.this, 0,new Intent(servicenotif.this,list2.class),PendingIntent.FLAG_ONE_SHOT);
note.setLatestEventInfo(servicenotif.this,"Problem Occured","Click to see the list of problem",b);
note.defaults=Notification.DEFAULT_ALL;
mgr.notify(NOTIFY_ME_ID,note);
}
//membuat notifikasi muncul lagi apabila data di reset
else if(t>TID){
Editor editor = mPrefs.edit();
editor.putString("tid", "");
editor.commit();
}
}
}
}
}
}
}
catch(JSONException e){
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
publishProgress(190);
return null;
}
//last step
#Override
protected void onPostExecute(String result) {
//dialog.cancel();
}
private void onCreate(Object object) {
// TODO Auto-generated method stub
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
// biasanya untuk progress download
int nilai = values[0];
// didapat dari publish progress
}
//step1
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
// buat bikin dialog loading
/*dialog = ProgressDialog.show(list.this, "Loading",
"Please wait..");*/
super.onPreExecute();
}
public void write(String fileName){
BufferedWriter bw=null;
try{
bw=new BufferedWriter(new OutputStreamWriter(openFileOutput(fileName,Context.MODE_PRIVATE)));
}
catch(Exception e){
}
}
}
private void getRequest(String Url2) {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
} catch (Exception ex) {
Toast.makeText(this, "Penghandelan Gagal !", Toast.LENGTH_SHORT)
.show();
}
}
private String request(HttpResponse response) {
// TODO Auto-generated method stub
String result = "";
try {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
in.close();
result = str.toString();
} catch (Exception ex) {
result = "Error";
}
return result;
}
#Override
//untuk logout mematikan notifikasi dan alarm supaya tidak menjalankan service lagi
public void onDestroy() {
NotificationManager mgr=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mgr.cancelAll();
Toast.makeText(this, "Log out successfull", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
PendingIntent i=PendingIntent.getService(this, 0,new Intent(this,servicenotif.class), 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.cancel(i);
}
Hope this will help

Not receiving push notifications in android

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

Categories

Resources