I follow this tutorial http://androidsrc.net/android-push-notification-using-google-cloud-messaging-gcm-part-1/ And after some change (because I’m using android studio) it works fine ^_^
I can successfully register my devices in the database and receive the notification from my php server...
The problem is when the device receives the notification it appear in the notification bar...but I want to receive the notification inside my application... because according to the message (in the notification) my app will do some action... (For example if the message "fire" alarm will be lunched ...etc)
How can I do that? Receiving the notification in the application?
Here is the client side... (The app)
public class MainActivity extends Activity {
// Resgistration Id from GCM
private static final String PREF_GCM_REG_ID = "PREF_GCM_REG_ID";
private SharedPreferences prefs;
// Your project number and web server url. Please change below.
private static final String GCM_SENDER_ID = "MY_PROJECT_ID";
private static final String WEB_SERVER_URL = "WEB_PAGE";
GoogleCloudMessaging gcm;
Button registerBtn;
TextView regIdView;
EditText test;
private static final int ACTION_PLAY_SERVICES_DIALOG = 100;
protected static final int MSG_REGISTER_WITH_GCM = 101;
protected static final int MSG_REGISTER_WEB_SERVER = 102;
protected static final int MSG_REGISTER_WEB_SERVER_SUCCESS = 103;
protected static final int MSG_REGISTER_WEB_SERVER_FAILURE = 104;
private String gcmRegId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerBtn = (Button) findViewById(R.id.register_gcmserver);
registerBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Check device for Play Services APK.
if (isGoogelPlayInstalled()) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
// Read saved registration id from shared preferences.
gcmRegId = getSharedPreferences().getString(PREF_GCM_REG_ID, "");
if (TextUtils.isEmpty(gcmRegId)) {
handler.sendEmptyMessage(MSG_REGISTER_WITH_GCM);
}else{
regIdView.setText(gcmRegId);
test.setText(gcmRegId);
Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_SHORT).show();
}
}
}
});
regIdView = (TextView) findViewById(R.id.regId);
test = (EditText) findViewById(R.id.editText);
}
private boolean isGoogelPlayInstalled() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
ACTION_PLAY_SERVICES_DIALOG).show();
} else {
Toast.makeText(getApplicationContext(),
"Google Play Service is not installed",
Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
private SharedPreferences getSharedPreferences() {
if (prefs == null) {
prefs = getApplicationContext().getSharedPreferences(
"AndroidSRCDemo", Context.MODE_PRIVATE);
}
return prefs;
}
public void saveInSharedPref(String result) {
// TODO Auto-generated method stub
Editor editor = getSharedPreferences().edit();
editor.putString(PREF_GCM_REG_ID, result);
editor.commit();
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MSG_REGISTER_WITH_GCM:
new GCMRegistrationTask().execute();
break;
case MSG_REGISTER_WEB_SERVER:
new WebServerRegistrationTask().execute();
break;
case MSG_REGISTER_WEB_SERVER_SUCCESS:
Toast.makeText(getApplicationContext(),
"registered with web server", Toast.LENGTH_LONG).show();
break;
case MSG_REGISTER_WEB_SERVER_FAILURE:
Toast.makeText(getApplicationContext(),
"registration with web server failed",
Toast.LENGTH_LONG).show();
break;
}
};
};
private class GCMRegistrationTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
if (gcm == null && isGoogelPlayInstalled()) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
try {
gcmRegId = gcm.register(GCM_SENDER_ID);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return gcmRegId;
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
Toast.makeText(getApplicationContext(), "registered with GCM",
Toast.LENGTH_LONG).show();
regIdView.setText(result);
saveInSharedPref(result);
handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER);
}
}
}
private class WebServerRegistrationTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
URL url = null;
try {
url = new URL(WEB_SERVER_URL);
} catch (MalformedURLException e) {
e.printStackTrace();
handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_FAILURE);
}
Map<String, String> dataMap = new HashMap<String, String>();
dataMap.put("regId", gcmRegId);
StringBuilder postBody = new StringBuilder();
Iterator iterator = dataMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry param = (Entry) iterator.next();
postBody.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
postBody.append('&');
}
}
String body = postBody.toString();
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
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");
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
int status = conn.getResponseCode();
if (status == 200) {
// Request success
handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_SUCCESS);
} else {
throw new IOException("Request failed with error code "
+ status);
}
} catch (ProtocolException pe) {
pe.printStackTrace();
handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_FAILURE);
} catch (IOException io) {
io.printStackTrace();
handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_FAILURE);
} finally {
if (conn != null) {
conn.disconnect();
}
}
return null;
}
}
}
class GCMBroadcastReceiver
public class GCMBroadcastReceiver extends WakefulBroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// Attach component of GCMIntentService that will handle the intent in background thread
ComponentName comp = new ComponentName(context.getPackageName(),
GCMIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
class GCMIntentService
public class GCMIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1000;
NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GCMIntentService() {
super(GCMIntentService.class.getName());
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
if (!extras.isEmpty()) {
// read extras as sent from server
String message = extras.getString("message");
String serverTime = extras.getString("timestamp");
sendNotification("Message: " + message + "\n" + "Server Time: "
+ serverTime);
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GCMBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Notification from GCM")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
And here the php file that sent the message...
device_sendmsg.php
<?php
if (isset($_POST["regId"]) && isset($_POST["message"])) {
$regId = $_POST["regId"];
$message = $_POST["message"];
include_once './gcm_sendmsg.php';
$gcm = new GCM_SendMsg();
$registatoin_ids = array($regId);
$message = array("message"=>$message, "timestamp"=>"04-01-2016");
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
?>
gcm_sendmsg.php
<?php
class GCM_SendMsg {
function __construct() {
}
/**
* send push notification
*/
public function send_notification($registatoin_ids, $message) {
include_once './config.php';
// Set POST request variable
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// disable SSL certificate support
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
hope someone can help me ^_^