java - Gcm Notification only comes in my own device -


i new in gcm , want send notification using gcm spacific users of app notification comes in own device

here code

mainactivity.java

public class mainactivity extends actionbaractivity {      private googlecloudmessaging gcm;     string regid;     checkbox isdriver;     httppost httppost;     stringbuffer buffer;     httpresponse response;     httpclient httpclient;     list<namevaluepair> namevaluepairs;     string user_name = "";     private final static int play_services_resolution_request = 9000;     string tag = "mainactivity";     string sender_id = "224163385438";     string api_key = "aizasycl3rek_onegldhcp8giso_5p6xwe3guva";     utils utils;     private context context = mainactivity.this;     private progressdialog pb;     private edittext username;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_main);         utils = new utils(this);         isdriver = (checkbox) findviewbyid(r.id.isdriver);      }      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(sender_id);                     msg = "device registered, registration id=" + regid;                  } catch (ioexception ex) {                     msg = ex.getmessage();                 }                 return msg;             }              @override             protected void onpostexecute(string msg) {                 log.i(tag, "onpostexecute : " + msg);                  if (!msg.equalsignorecase("service_not_available")) {                      message msgobj = handler.obtainmessage();                     bundle b = new bundle();                     b.putstring("server_response", msg);                     msgobj.setdata(b);                     handler.sendmessage(msgobj);                  } else {                      utils.showtoast("error : " + msg                             + "\nplease check internet connection");                      hidepb();                  }             }              // define handler receives messages thread ,             // update progress             private final handler handler = new handler() {                  public void handlemessage(message msg) {                      string aresponse = msg.getdata().getstring(                             "server_response");                      if ((null != aresponse)) {                          log.i(tag, "    sendregistrationidtobackend();");                          sendregistrationidtobackend();                      } else {                      }                  }             };         }.execute(null, null, null);     }      /**      * sends registration id server on http, can use      * gcm/http or ccs send messages app. not needed demo      * since device sends upstream messages server echoes      * message using 'from' address in message.      */     public void sendregistrationidtobackend() {          log.i(tag, "sendregistrationidtobackend");          thread thread = new thread() {             @override             public void run() {                 try {                     httpclient = new defaulthttpclient();                      // yahan reg id ki server webserivcice dalegi                      httppost = new httppost("http://www.test5.luminativesolutions.com/cabbooking/ws/gcmdemo/save_reg_id.php");                     namevaluepairs = new arraylist<namevaluepair>(1);                     namevaluepairs.add(new basicnamevaluepair("username",                             user_name));                     namevaluepairs.add(new basicnamevaluepair("reg_id", regid));                     httppost.setentity(new urlencodedformentity(namevaluepairs));                     responsehandler<string> responsehandler = new basicresponsehandler();                     final string response = httpclient.execute(httppost,                             responsehandler);                     log.i(tag, "response : " + response);                      if (response != null) {                          if (response                                 .equalsignorecase("username registered")) {                              utils.showtoast("username registered");                              hidepb();                            } else {                             if (response                                     .equalsignorecase("new device registered successfully")) {                                  utils.savepreferences(utils.username, user_name);                                 // persist regid - no need register                                 // again.                                 utils.storeregistrationid(regid);                                  utils.showtoast("device registration successful");                              }                         }                      }                  } catch (exception e) {                      hidepb();                     log.d(tag, "exception : " + e.getmessage());                 }             }         };          thread.start();      }      public void onclick(view view) {          if (view.getid() == r.id.btnsave) {             username = (edittext) findviewbyid(r.id.username);             user_name = username.gettext().tostring().trim();             if (user_name.length() > 0) {                  log.d(tag, "startregistration");                  showpb("registering device");                  startregistration();                 /*if(isdriver.ischecked()){                     log.i(tag,"driver reg id");                     log.d(tag, utils.getfrompreferences(user_name));                  }*/                 intent = new intent(mainactivity.this,bookingactivity.class);                 i.putextra("username",user_name);                 i.putextra("regid",regid);                 startactivity(i);              } else {                  log.d(tag, "username empty");              }         }     }      void startregistration() {          if (checkplayservices()) {             // if check succeeds, proceed normal processing.             // otherwise, prompt user valid play services apk.             log.i(tag, "google play services ok");             gcm = googlecloudmessaging.getinstance(this);             regid = utils.getregistrationid();             /*if(isdriver.ischecked()){                 utils.savepreferences(user_name, regid);                 log.d(tag,utils.getfrompreferences(user_name));             }*/             system.out.println(regid);             if (regid.isempty()) {                 registerinbackground();             } else {                 log.i(tag, "reg id not empty");             }         } else {             log.i(tag, "no valid google play services apk found.");         }      }      private boolean checkplayservices() {         int resultcode = googleplayservicesutil                 .isgoogleplayservicesavailable(this);         if (resultcode != connectionresult.success) {             if (googleplayservicesutil.isuserrecoverableerror(resultcode)) {                 log.i(tag, "no google play services...get store.");                 googleplayservicesutil.geterrordialog(resultcode, this,                         play_services_resolution_request).show();             } else {                 log.i(tag, "this device not supported.");                 finish();             }             return false;         }         return true;     }      void showpb(final string message) {          runonuithread(new runnable() {              @override             public void run() {                 pb = new progressdialog(mainactivity.this);                 pb.setmessage(message);                 pb.show();             }         });      }      void hidepb() {          runonuithread(new runnable() {              @override             public void run() {                 if (pb != null && pb.isshowing())                     pb.dismiss();             }         });      }      @override     public boolean oncreateoptionsmenu(menu menu) {         // inflate menu; adds items action bar if present.         getmenuinflater().inflate(r.menu.menu_main, menu);         return true;     }      @override     public boolean onoptionsitemselected(menuitem item) {         // handle action bar item clicks here. action bar         // automatically handle clicks on home/up button, long         // specify parent activity in androidmanifest.xml.         int id = item.getitemid();          //noinspection simplifiableifstatement         if (id == r.id.action_settings) {             return true;         }          return super.onoptionsitemselected(item);     } } 

bookingactivity.java

public class bookingactivity extends actionbaractivity {      httppost httppost;     stringbuffer buffer;     httpresponse response;     httpclient httpclient;     list<namevaluepair> namevaluepairs;     utils utils;     intent i;     static string tag = "gcm demo";     string user_name;     string regid;      string sender_id = "224163385438";     string api_key = "aizasycl3rek_onegldhcp8giso_5p6xwe3guva";        @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_booking);          = getintent();          registerreceiver(broadcastreceiver, new intentfilter(                 "chat_message_received"));     }      broadcastreceiver broadcastreceiver = new broadcastreceiver() {         @override         public void onreceive(context context, intent intent) {              bundle b = intent.getextras();              string message = b.getstring("message");              log.i(tag, " received in activity " + message + ", name = "                     + i.getstringextra("username"));           }     };      public void onclick(final view view) {          if (view == findviewbyid(r.id.booking)) {              sendmessage();              //clearmessagetextbox();          }      }      public void sendmessage() {          final string messagetosend = "driver booked by: "+i.getstringextra("username");          if (messagetosend.length() > 0) {              log.i(tag, "sendmessage");              thread thread = new thread() {                 @override                 public void run() {                     try {                         httpclient = new defaulthttpclient();                         httppost = new                                 httppost("http://www.test5.luminativesolutions.com/cabbooking/ws/gcmdemo/gcm_engine.php");                         namevaluepairs = new arraylist<namevaluepair>(1);                         namevaluepairs.add(new basicnamevaluepair("message",                                 messagetosend));                         namevaluepairs.add(new basicnamevaluepair(                                 "registrationids", i.getstringextra("regid")));                         namevaluepairs.add(new basicnamevaluepair("apikey",                                 api_key));                          httppost.setentity(new urlencodedformentity(                                 namevaluepairs));                         responsehandler<string> responsehandler = new basicresponsehandler();                         final string response = httpclient.execute(httppost,                                 responsehandler);                         log.i(tag, "response : " + response);                         if (response.trim().isempty()) {                             log.d(tag, "message not sent");                         }                      } catch (exception e) {                         log.d(tag, "exception : " + e.getmessage());                     }                 }             };              thread.start();          }      }      @override     public boolean oncreateoptionsmenu(menu menu) {         // inflate menu; adds items action bar if present.         getmenuinflater().inflate(r.menu.menu_booking, menu);         return true;     }      @override     public boolean onoptionsitemselected(menuitem item) {         // handle action bar item clicks here. action bar         // automatically handle clicks on home/up button, long         // specify parent activity in androidmanifest.xml.         int id = item.getitemid();          //noinspection simplifiableifstatement         if (id == r.id.action_settings) {             return true;         }          return super.onoptionsitemselected(item);     } } 

utils.java

public class utils {      static context context;     public static final string tag = "utils";     public static final string username = "username";      public static final string property_reg_id = "registration_id";     private static final string property_app_version = "appversion";      public utils(context context) {         utils.context = context;     }      public sharedpreferences getgcmpreferences() {         return context.getsharedpreferences(((actionbaractivity) context)                 .getclass().getsimplename(), context.mode_private);     }      public void savepreferences(string key, string value) {         final sharedpreferences prefs = getgcmpreferences();         log.i(tag, key + " : " + value);         sharedpreferences.editor editor = prefs.edit();         editor.putstring(key, value);         editor.commit();     }      public string getfrompreferences(string key) {         final sharedpreferences prefs = getgcmpreferences();         string value = prefs.getstring(key, "");         if (value.isempty()) {             log.i(tag, key + " not found.");             return "";         }         return value;     }      string getregistrationid() {         final sharedpreferences prefs = getgcmpreferences();         string registrationid = prefs.getstring(property_reg_id, "");         if (registrationid.isempty()) {             log.i(tag, "registration not found.");             return "";         }         // check if app updated; if so, must clear registration id         // since existing regid not guaranteed work new         // app version.         int registeredversion = prefs.getint(property_app_version,                 integer.min_value);         int currentversion = getappversion();         if (registeredversion != currentversion) {             log.i(tag, "app version changed.");             return "";         }         return registrationid;     }      static int getappversion() {         try {             packageinfo packageinfo = context.getpackagemanager()                     .getpackageinfo(context.getpackagename(), 0);             return packageinfo.versioncode;         } catch (namenotfoundexception e) {             // should never happen             throw new runtimeexception("could not package name: " + e);         }     }      public void storeregistrationid(string regid) {         final sharedpreferences prefs = getgcmpreferences();         int appversion = utils.getappversion();         log.i(tag, "saving regid on app version " + appversion);         log.i(tag, "reg id : " + regid);         sharedpreferences.editor editor = prefs.edit();         editor.putstring(property_reg_id, regid);         editor.putint(property_app_version, appversion);         editor.commit();     }      public string getcurrentipaddress() {         return "http://192.168.0.101/";     }      public void showtoast(final string txt) {         ((activity) context).runonuithread(new runnable() {             public void run() {                 toast.maketext(context, txt, toast.length_long).show();             }         });      }  } 

in app user login simple user or login driver if user login , register gcm , press booked button notification send specific driver

it because calling own device id notified,please check out backend , registered users must have own device id's . make sure different device id generated while new registration happens.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -