Skip to content

Commit

Permalink
Added push notifications.
Browse files Browse the repository at this point in the history
  • Loading branch information
GleasonK committed Jul 15, 2015
1 parent 1355d02 commit a6117a5
Show file tree
Hide file tree
Showing 10 changed files with 315 additions and 36 deletions.
4 changes: 3 additions & 1 deletion app/build.gradle
@@ -1,4 +1,5 @@
apply plugin: 'com.android.application'
//apply plugin: 'com.google.gms.google-services'

android {
compileSdkVersion 21
Expand All @@ -21,5 +22,6 @@ android {

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.pubnub:pubnub:3.7.2'
compile 'com.pubnub:pubnub-android:3.7.4'
compile 'com.google.android.gms:play-services:7.5.0'
}
1 change: 1 addition & 0 deletions app/google-services.json
@@ -0,0 +1 @@
{"project_info":{"project_id":"pubchat-123df","project_number":"709361095668","name":"PubChat"},"client":[{"client_info":{"client_id":"android:me.kevingleason.pubnubchat","client_type":1,"android_client_info":{"package_name":"me.kevingleason.pubnubchat"}},"oauth_client":[],"services":{"analytics_service":{"status":1},"cloud_messaging_service":{"status":2,"apns_config":[]},"appinvite_service":{"status":1,"other_platform_oauth_client":[]},"google_signin_service":{"status":1},"ads_service":{"status":1}}}],"ARTIFACT_VERSION":"1"}
17 changes: 15 additions & 2 deletions app/src/main/AndroidManifest.xml
Expand Up @@ -3,9 +3,10 @@
package="me.kevingleason.pubnubchat" >

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="your.package.name.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="your.package.name.permission.C2D_MESSAGE" />

<application
android:allowBackup="true"
Expand All @@ -27,6 +28,18 @@
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden">
</activity>
<receiver
android:name=".gcm.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="your.package.name" />
</intent-filter>
</receiver>
<service android:name=".gcm.GcmIntentService" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</application>

</manifest>
7 changes: 7 additions & 0 deletions app/src/main/java/me/kevingleason/pubnubchat/Constants.java
Expand Up @@ -12,6 +12,7 @@ public class Constants {

public static final String CHAT_PREFS = "me.kevingleason.SHARED_PREFS";
public static final String CHAT_USERNAME = "me.kevingleason.SHARED_PREFS.USERNAME";
public static final String CHAT_ROOM = "me.kevingleason.CHAT_ROOM";

public static final String JSON_GROUP = "groupMessage";
public static final String JSON_DM = "directMessage";
Expand All @@ -20,4 +21,10 @@ public class Constants {
public static final String JSON_TIME = "chatTime";

public static final String STATE_LOGIN = "loginTime";

public static final String GCM_REG_ID = "gcmRegId";
public static final String GCM_SENDER_ID = "709361095668"; // Get this from
public static final String GCM_POKE_FROM = "gcmPokeFrom"; // Get this from
public static final String GCM_CHAT_ROOM = "gcmChatRoom"; // Get this from
public final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
}
212 changes: 183 additions & 29 deletions app/src/main/java/me/kevingleason/pubnubchat/MainActivity.java
Expand Up @@ -2,26 +2,31 @@

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.pubnub.api.Callback;
import com.pubnub.api.PnGcmMessage;
import com.pubnub.api.PnMessage;
import com.pubnub.api.Pubnub;
import com.pubnub.api.PubnubError;
import com.pubnub.api.PubnubException;
Expand All @@ -30,6 +35,7 @@
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
Expand All @@ -51,21 +57,31 @@ public class MainActivity extends ListActivity {
private ChatAdapter mChatAdapter;
private SharedPreferences mSharedPrefs;

public Callback basicCallback;
private String username;
private String channel = "MainChat";

private GoogleCloudMessaging gcm;
private String gcmRegId;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mSharedPrefs = getSharedPreferences(Constants.CHAT_PREFS,MODE_PRIVATE);
mSharedPrefs = getSharedPreferences(Constants.CHAT_PREFS, MODE_PRIVATE);
if (!mSharedPrefs.contains(Constants.CHAT_USERNAME)){
Intent toLogin = new Intent(this, LoginActivity.class);
startActivity(toLogin);
return;
}

Bundle extras = getIntent().getExtras();
if (extras != null){
Log.d("Main-bundle",extras.toString() + " Has Chat: " + extras.getString(Constants.CHAT_ROOM));
if (extras.containsKey(Constants.CHAT_ROOM)) this.channel = extras.getString(Constants.CHAT_ROOM);
}

this.username = mSharedPrefs.getString(Constants.CHAT_USERNAME,"Anonymous");
this.mListView = getListView();
this.mChatAdapter = new ChatAdapter(this, new ArrayList<ChatMessage>());
Expand Down Expand Up @@ -104,18 +120,20 @@ public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_here_now) {
hereNow(true);
return true;
}
if (id == R.id.action_sign_out) {
signOut();
return true;
}
if (id == R.id.action_settings) {
return true;
switch(id){
case R.id.action_here_now:
hereNow(true);
return true;
case R.id.action_sign_out:
signOut();
return true;
case R.id.action_gcm_register:
gcmRegister();
return true;
case R.id.action_gcm_unregister:
gcmUnregister();
return true;
}

return super.onOptionsItemSelected(item);
}

Expand All @@ -138,8 +156,8 @@ protected void onStop() {
* history.
*/
@Override
protected void onResume() {
super.onResume();
protected void onRestart() {
super.onRestart();
if (this.mPubNub==null){
initPubNub();
} else {
Expand All @@ -164,6 +182,18 @@ protected void onDestroy() {
* Finally, populate the listview with past messages from history
*/
private void initPubNub(){
this.basicCallback = new Callback() {
@Override
public void successCallback(String channel, Object response) {
Log.d("PUBNUB", response.toString());
}

@Override
public void errorCallback(String channel, PubnubError error) {
Log.d("PUBNUB", error.toString());
}
};

this.mPubNub = new Pubnub(Constants.PUBLISH_KEY, Constants.SUBSCRIBE_KEY);
this.mPubNub.setUUID(this.username);
subscribeWithPresence();
Expand All @@ -182,18 +212,7 @@ public void publish(String type, JSONObject data){
json.put("data", data);
} catch (JSONException e) { e.printStackTrace(); }

Callback callbacks = new Callback() {
@Override
public void successCallback(String channel, Object response) {
Log.d("PUBNUB",response.toString());
}

@Override
public void errorCallback(String channel, PubnubError error) {
Log.d("PUBNUB",error.toString());
}
};
this.mPubNub.publish(this.channel, json, callbacks);
this.mPubNub.publish(this.channel, json, this.basicCallback);
}

/**
Expand Down Expand Up @@ -438,7 +457,7 @@ private void setupListView(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ChatMessage chatMsg = mChatAdapter.getItem(position);
getStateLogin(chatMsg.getUsername());
sendNotification(chatMsg.getUsername());
}
});
}
Expand Down Expand Up @@ -532,4 +551,139 @@ public void onClick(DialogInterface dialog, int id) {
alertDialog.show();
}

/**
* GCM Functionality
*/

private void gcmRegister() {
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
try {
gcmRegId = getRegistrationId();
} catch (Exception e) {
e.printStackTrace();
}

if (gcmRegId.isEmpty()) {
registerInBackground();
} else {
Toast.makeText(this,"Registration ID already exists: " + gcmRegId,Toast.LENGTH_SHORT).show();
}
} else {
Log.e("GCM-register", "No valid Google Play Services APK found.");
}
}

private void gcmUnregister() {
new UnregisterTask().execute();
}

private void removeRegistrationId() {
SharedPreferences prefs = getSharedPreferences(Constants.CHAT_PREFS, Context.MODE_PRIVATE);

SharedPreferences.Editor editor = prefs.edit();
editor.remove(Constants.GCM_REG_ID);
editor.apply();
}

public void sendNotification(String toUser) {
PnGcmMessage gcmMessage = new PnGcmMessage();
JSONObject json = new JSONObject();
try {
json.put(Constants.GCM_POKE_FROM, this.username);
json.put(Constants.GCM_CHAT_ROOM, this.channel);
gcmMessage.setData(json);

PnMessage message = new PnMessage(
this.mPubNub,
toUser,
this.basicCallback,
gcmMessage);
message.put("pn_debug",true); // Subscribe to yourchannel-pndebug on console for reports
message.publish();
}
catch (JSONException e) { e.printStackTrace(); }
catch (PubnubException e) { e.printStackTrace(); }
}

private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, Constants.PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.e("GCM-check", "This device is not supported.");
finish();
}
return false;
}
return true;
}

private void registerInBackground() {
new RegisterTask().execute();
}

private void storeRegistrationId(String regId) {
SharedPreferences prefs = getSharedPreferences(Constants.CHAT_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constants.GCM_REG_ID, regId);
editor.apply();
}


private String getRegistrationId() {
SharedPreferences prefs = getSharedPreferences(Constants.CHAT_PREFS, Context.MODE_PRIVATE);
return prefs.getString(Constants.GCM_REG_ID, "");
}

private void sendRegistrationId(String regId) {
this.mPubNub.enablePushNotificationsOnChannel(this.username, regId, basicCallback);
}

private class RegisterTask extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... params) {
String msg="";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(MainActivity.this);
}
gcmRegId = gcm.register(Constants.GCM_SENDER_ID);
msg = "Device registered, registration ID: " + gcmRegId;

sendRegistrationId(gcmRegId);

storeRegistrationId(gcmRegId);
Log.i("GCM-register", msg);
} catch (IOException e){
e.printStackTrace();
}
return msg;
}
}

private class UnregisterTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(MainActivity.this);
}

// Unregister from GCM
gcm.unregister();

// Remove Registration ID from memory
removeRegistrationId();

// Disable Push Notification
mPubNub.disablePushNotificationsOnChannel(username, gcmRegId);

} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
@@ -0,0 +1,22 @@
package me.kevingleason.pubnubchat.gcm;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;


/**
* Created by GleasonK on 7/14/15.
*/
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("GCM-receiver","GCM Message Received!");
ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}

0 comments on commit a6117a5

Please sign in to comment.