php - GCM Downstream Android Notification -


i have created android app registration id gcm , receive downstream notification. registration part working here. (regid sent me opening email , i'm hard cording in 3rd party server.) thing when send message server app never receives it. following code..

notificationmainactivity - (registers app in gcm successfully)

public class notificationmainactivity extends activity {  	  	public static final string extra_message = "message";  	public static final string property_reg_id = "registration_id";  	private static final string property_app_version = "appversion";  	private final static int play_services_resolution_request = 9000;  	      string sender_id = "1030512389658";        static final string tag = "kanrich gcm notification";        public textview mdisplay;      googlecloudmessaging gcm;      atomicinteger msgid = new atomicinteger();      sharedpreferences prefs;      context context;        string regid;  	      @override      public void oncreate(bundle savedinstancestate) {          super.oncreate(savedinstancestate);                   setcontentview(r.layout.activity_notification_main);          mdisplay = (textview) findviewbyid(r.id.regid);          context = getapplicationcontext();            // check device play services apk. if check succeeds, proceed          //  gcm registration.          if (checkplayservices()) {              gcm = googlecloudmessaging.getinstance(this);              regid = getregistrationid(context);                            system.out.println("**********play ******************************************************");                if (regid.isempty()) {                  registerinbackground();              }          } else {              log.i(tag, "no valid google play services apk found.");          }      }            @override      protected void onresume(){      	super.onresume();      	checkplayservices();      }        @override      public boolean oncreateoptionsmenu(menu menu) {          // inflate menu; adds items action bar if present.          getmenuinflater().inflate(r.menu.notification_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();          if (id == r.id.action_settings) {              return true;          }          return super.onoptionsitemselected(item);      }           //get registratiom id if exists..      private string getregistrationid(context context) {          final sharedpreferences prefs = getgcmpreferences(context);          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 registration id not guaranteed work          // new app version.          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;      }            //get app version..(to know weather app updated.. if yes reg.id isempty,.)      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 package name: " + e);          }      }                  //register in background..      private void registerinbackground() {   	      	new asynctask<void, void, string>() {       		              @override              protected string doinbackground(void... voids) {              	string msg = "";              	              	try{              		if (gcm == null) {                          gcm = googlecloudmessaging.getinstance(context);                      }                      regid = gcm.register(sender_id);                      msg = "device registered, registration id=" + regid;                      system.out.println(msg);                                            storeregistrationid(context, regid);              	}              	catch(ioexception ex){                      msg = "error :" + ex.getmessage();                                 	}              	                  return msg;              }                @override              protected void onpostexecute(string result) {              	mdisplay.append(result + "\n");              }          }.execute();      	      }                   //check 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 not supported.");                  finish();              }              return false;          }          return true;      }          //shared preferences...      private sharedpreferences getgcmpreferences(context context) {          return getsharedpreferences(notificationmainactivity.class.getsimplename(),                  context.mode_private);      }            private void storeregistrationid(context context, string regid) {          final sharedpreferences prefs = getgcmpreferences(context);          int appversion = getappversion(context);          log.i(tag, "saving regid on app version " + appversion);          sharedpreferences.editor editor = prefs.edit();          editor.putstring(property_reg_id, regid);          editor.putint(property_app_version, appversion);          editor.commit();      }            public void sendregid(view v){ 	      	try{      		final intent intent = new intent(intent.action_send);              intent.settype("text/plain");              intent.putextra(intent.extra_email, new string[]{"chinthakau@kanrich.lk"});              intent.putextra(intent.extra_subject, "gcm reg id");              intent.putextra(intent.extra_text, regid);              notificationmainactivity.this.startactivity(intent);      	}      	catch(exception e){      		system.out.println("###-attach gmail error-- "+e.tostring());      	}      }  }

gcmbroadcastreceiver.java

package com.example.kanrichgcmnotification;    import android.app.activity;  import android.content.componentname;  import android.content.context;  import android.content.intent;  import android.support.v4.content.wakefulbroadcastreceiver;    public class gcmbroadcastreceiver extends wakefulbroadcastreceiver {  		  	@override  	public void onreceive(context context, intent intent) {  		// todo auto-generated method stub  		// explicitly specify gcmintentservice handle intent.          componentname comp = new componentname(context.getpackagename(),                  gcmintentservice.class.getname());          // start service, keeping device awake while launching.          startwakefulservice(context, (intent.setcomponent(comp)));          setresultcode(activity.result_ok);  	}    }

gcmintentservice.java

package com.example.kanrichgcmnotification;    import com.google.android.gms.gcm.googlecloudmessaging;    import android.app.intentservice;  import android.app.notificationmanager;  import android.app.pendingintent;  import android.content.context;  import android.content.intent;  import android.os.bundle;  import android.os.systemclock;  import android.support.v4.app.notificationcompat;  import android.util.log;    public class gcmintentservice extends intentservice {  	  	public static final int notification_id = 1;      private notificationmanager mnotificationmanager;      notificationcompat.builder builder;  	  	static final string tag = "kanrich gcm notification";  	  	public gcmintentservice() {          super("gcmintentservice");      }    	@override  	protected void onhandleintent(intent intent) {  			  		bundle extras = intent.getextras();          googlecloudmessaging gcm = googlecloudmessaging.getinstance(this);          // getmessagetype() intent parameter must intent received          // in broadcastreceiver.          string messagetype = gcm.getmessagetype(intent);            if (!extras.isempty()) {  // has effect of unparcelling bundle              /*               * filter messages based on message type. since gcm               * extended in future new message types, ignore               * message types you're not interested in, or don't               * recognize.               */              if (googlecloudmessaging.                      message_type_send_error.equals(messagetype)) {                  sendnotification("send error: " + extras.tostring());              } else if (googlecloudmessaging.                      message_type_deleted.equals(messagetype)) {                  sendnotification("deleted messages on server: " +                          extras.tostring());              // if it's regular gcm message, work.              } else if (googlecloudmessaging.                      message_type_message.equals(messagetype)) {                  // loop represents service doing work.                  (int i=0; i<5; i++) {                      log.i(tag, "working... " + (i+1)                              + "/5 @ " + systemclock.elapsedrealtime());                      try {                          thread.sleep(5000);                      } catch (interruptedexception e) {                      }                  }                  log.i(tag, "completed work @ " + systemclock.elapsedrealtime());                  // post notification of received message.                  sendnotification("received: " + extras.tostring());                  log.i(tag, "received: " + extras.tostring());              }          }          // release wake lock provided wakefulbroadcastreceiver.          gcmbroadcastreceiver.completewakefulintent(intent);		  	}  		  	 private void sendnotification(string msg) {  	        mnotificationmanager = (notificationmanager)  	                this.getsystemservice(context.notification_service);    	        pendingintent contentintent = pendingintent.getactivity(this, 0,  	                new intent(this, notificationmainactivity.class), 0);    	        notificationcompat.builder mbuilder =  	                new notificationcompat.builder(this)  	        //.setsmallicon(r.drawable.ic_stat_gcm)  	        .setcontenttitle("gcm notification")  	        .setstyle(new notificationcompat.bigtextstyle()  	        .bigtext(msg))  	        .setcontenttext(msg);    	        mbuilder.setcontentintent(contentintent);  	        mnotificationmanager.notify(notification_id, mbuilder.build());  	    }  }

and here manifest.xml file. (with i'm not sure have insert properly.)

<?xml version="1.0" encoding="utf-8"?>  <manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.example.kanrichgcmnotification"      android:versioncode="1"      android:versionname="1.0" >        <uses-sdk          android:minsdkversion="11"          android:targetsdkversion="21" />            <uses-permission android:name="android.permission.internet" />      <uses-permission android:name="android.permission.get_accounts" />      <uses-permission android:name="android.permission.wake_lock" />      <uses-permission android:name="com.google.android.c2dm.permission.receive" />            <permission android:name="com.example.gcm.permission.c2d_message"          android:protectionlevel="signature" />      <uses-permission android:name="com.example.gcm.permission.c2d_message" />        <application          android:allowbackup="true"          android:icon="@drawable/ic_launcher"          android:label="@string/app_name"          android:theme="@style/apptheme" >                    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />                              <activity              android:name=".notificationmainactivity"              android:label="@string/app_name" >              <intent-filter>                  <action android:name="android.intent.action.main" />                    <category android:name="android.intent.category.launcher" />              </intent-filter>          </activity>                    <receiver              android:name=".gcmbroadcastreceiver"              android:permission="com.google.android.c2dm.permission.send" >              <intent-filter>                  <action android:name="com.google.android.c2dm.intent.receive" />                  <category android:name="com.example.kanrichgcmnotification" />              </intent-filter>          </receiver>          <service android:name=".gcmintentservice" />                </application>     </manifest>
++++++++++ later edit : here php script sends message.(it working 3rd party app receives json gcm messages.)

<?php    // api access key google api's console  define( 'api_access_key', 'aizasybfhnkfdyolmyaooyoid_pwz4ojfjkaszg' );      $registrationid = array('apa91bemd2sikqari7jkvq5dw_wz566x-ijkl6ptmdyj_ukezchlrrw5-bop8msaq0mwjih-ubqshvhrk6tg2iyolalbno4z2krocmkiwzdombkmibgmqjvttulxjz0h7v3tv8mlnrbwsdh2xpb63fdks7obs_mukaz0pkbfdioxdyzm5ft8ao4');    // prep bundle    $msg = array  (  	'message' 	=> 'here message. message',  	'title'		=> 'this title. title',  	'subtitle'	=> 'this subtitle. subtitle',  	'tickertext'	=> 'ticker text here...ticker text here...ticker text here',  	'vibrate'	=> 1,  	'sound'		=> 1,  	'largeicon'	=> 'large_icon',  	'smallicon'	=> 'small_icon'  );    //$msg = "please note this..";    $fields = array  (  	'registration_ids' 	=> $registrationid,  	'data'			=> $msg  );     $headers = array  (  	'authorization: key=' . api_access_key,  	'content-type: application/json',          'delay_while_idle: true',  );     try{      $ch = curl_init();  curl_setopt( $ch,curlopt_url, 'https://android.googleapis.com/gcm/send' );  curl_setopt( $ch,curlopt_post, true );  curl_setopt( $ch,curlopt_httpheader, $headers );  curl_setopt( $ch,curlopt_returntransfer, true );  curl_setopt( $ch,curlopt_ssl_verifypeer, false );  curl_setopt( $ch,curlopt_postfields, json_encode( $fields ) );  $result = curl_exec($ch );  curl_close( $ch );    echo $result;    }  catch(exception $e){      echo $e;      echo "inside catch";  }

++++++++++ thank , spending valuable time me..!

replace com.example.gcm in manifest.xml package name.
or change package name com.example.gcm


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -