├── libs
├── gcm.jar
└── android-support-v4.jar
├── ic_launcher-web.png
├── .gitignore
├── res
├── drawable-hdpi
│ └── ic_launcher.png
├── drawable-mdpi
│ └── ic_launcher.png
├── drawable-xhdpi
│ └── ic_launcher.png
├── drawable-xxhdpi
│ └── ic_launcher.png
├── values-sw600dp
│ └── dimens.xml
├── values
│ ├── dimens.xml
│ ├── styles.xml
│ └── strings.xml
├── menu
│ └── main.xml
├── values-sw720dp-land
│ └── dimens.xml
├── values-v11
│ └── styles.xml
└── layout
│ └── activity_main.xml
├── gcm-server.py
├── src
└── com
│ └── dhruvb
│ └── myapplication
│ ├── CommonUtilities.java
│ ├── AlertDialogManager.java
│ ├── GCMIntentService.java
│ └── MainActivity.java
├── README.md
└── AndroidManifest.xml
/libs/gcm.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rockyzsu/android_gcm/master/libs/gcm.jar
--------------------------------------------------------------------------------
/ic_launcher-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rockyzsu/android_gcm/master/ic_launcher-web.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .classpath
2 | .project
3 | gen/*
4 | bin/*
5 | proguard-project.txt
6 | project.properties
7 |
--------------------------------------------------------------------------------
/libs/android-support-v4.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rockyzsu/android_gcm/master/libs/android-support-v4.jar
--------------------------------------------------------------------------------
/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rockyzsu/android_gcm/master/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rockyzsu/android_gcm/master/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rockyzsu/android_gcm/master/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rockyzsu/android_gcm/master/res/drawable-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/values-sw600dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
--------------------------------------------------------------------------------
/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/res/menu/main.xml:
--------------------------------------------------------------------------------
1 |
7 |
--------------------------------------------------------------------------------
/res/values-sw720dp-land/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 128dp
5 |
6 |
--------------------------------------------------------------------------------
/res/values-v11/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/gcm-server.py:
--------------------------------------------------------------------------------
1 | from gcm import GCM
2 | import argparse
3 |
4 | # API Key for your Google OAuth project
5 | API_KEY = ''
6 |
7 |
8 | def send_push_notification(registration_id, message):
9 | gcm = GCM(API_KEY)
10 | resp = gcm.plaintext_request(registration_id=registration_id,
11 | data={'message': message})
12 |
13 |
14 | if __name__ == '__main__':
15 | parser = argparse.ArgumentParser()
16 | parser.add_argument('-r', '--reg-id', dest='registration_id', required=True)
17 | parser.add_argument('-m', '--message', dest='message', required=True)
18 | args = parser.parse_args()
19 | send_push_notification(args.registration_id, args.message)
20 |
21 |
--------------------------------------------------------------------------------
/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
14 |
15 |
16 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/src/com/dhruvb/myapplication/CommonUtilities.java:
--------------------------------------------------------------------------------
1 | package com.dhruvb.myapplication;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 |
6 |
7 | public final class CommonUtilities {
8 |
9 | // Google project id
10 | static final String SENDER_ID = "";
11 |
12 | /**
13 | * Tag used on log messages.
14 | */
15 | static final String TAG = "GCM -> ";
16 |
17 | static final String DISPLAY_MESSAGE_ACTION =
18 | "com.dhruvb.myapplication.DISPLAY_MESSAGE";
19 |
20 | static final String EXTRA_MESSAGE = "message";
21 |
22 | /**
23 | * Notifies UI to display a message.
24 | *
25 | * This method is defined in the common helper because it's used both by
26 | * the UI and the background service.
27 | *
28 | * @param context application's context.
29 | * @param message message to be displayed.
30 | */
31 | static void displayMessage(Context context, String message) {
32 | Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
33 | intent.putExtra(EXTRA_MESSAGE, message);
34 | context.sendBroadcast(intent);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Android GCM
2 | -----------
3 |
4 | **Caution:** Project is very hacky at the moment.
5 |
6 | This is just a sample Android application having push notifications. It shows a toast message and notification when it receives the push notification.
7 |
8 | The file gcm_server.py can be used to send messages to the application.
9 |
10 |
11 | HOWTO
12 | =====
13 |
14 | 1. Configure the application in your editor (preferably Eclipse), add libs/gcm.jar to your buildpath
15 | 2. Change the SENDER_ID attribute in src/com/dhruvb/myapplication/CommonUtilities.java to your Google OAuth project id. Its usually in the URL `https://code.google.com/apis/console/?pli=1#project::access`
16 | 3. Start the application in debug mode, the logcat output will print a device registration id, this id is used by the gcm server to send messages.
17 | 4. Do a `pip install python-gcm`
18 | 5. Change the API_KEY attribute in gcm-server.py.
19 | 6. Run the script as `python gcm-server.py -r -m ''`
20 |
21 | Refer: https://developer.android.com/google/gcm/gs.html for more clear instructions to get SENDER_ID and API_KEY
22 |
23 |
--------------------------------------------------------------------------------
/src/com/dhruvb/myapplication/AlertDialogManager.java:
--------------------------------------------------------------------------------
1 | package com.dhruvb.myapplication;
2 |
3 | import android.app.AlertDialog;
4 | import android.content.Context;
5 | import android.content.DialogInterface;
6 |
7 | public class AlertDialogManager {
8 | /**
9 | * Function to display simple Alert Dialog
10 | * @param context - application context
11 | * @param title - alert dialog title
12 | * @param message - alert message
13 | * @param status - success/failure (used to set icon)
14 | * - pass null if you don't want icon
15 | * */
16 | public void showAlertDialog(Context context, String title, String message,
17 | Boolean status) {
18 | AlertDialog alertDialog = new AlertDialog.Builder(context).create();
19 |
20 | // Setting Dialog Title
21 | alertDialog.setTitle(title);
22 |
23 | // Setting Dialog Message
24 | alertDialog.setMessage(message);
25 |
26 | // Setting OK Button
27 | alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
28 | public void onClick(DialogInterface dialog, int which) {
29 | }
30 | });
31 |
32 | // Showing Alert Message
33 | alertDialog.show();
34 | }
35 | }
--------------------------------------------------------------------------------
/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | My Application
5 | Hello world!
6 | Settings
7 | Push Notifications
8 | Please set the %1$s constant and recompile the app.
9 | Device is already registered on server.
10 | From GCM: device successfully registered!
11 | From GCM: device successfully unregistered!
12 | From GCM: you got message!
13 | From GCM: error (%1$s).
14 | From GCM: recoverable error (%1$s).
15 | From GCM: server deleted %1$d pending messages!
16 | Trying (attempt %1$d/%2$d) to register device on Demo Server.
17 | From Demo Server: successfully added device!
18 | From Demo Server: successfully removed device!
19 | Could not register device on Demo Server after %1$d attempts.
20 | Could not unregister device on Demo Server (%1$s).
21 | Register
22 | Unregister
23 | Clear
24 | Exit
25 |
26 |
--------------------------------------------------------------------------------
/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
19 |
20 |
21 |
22 |
23 |
28 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/src/com/dhruvb/myapplication/GCMIntentService.java:
--------------------------------------------------------------------------------
1 | package com.dhruvb.myapplication;
2 |
3 | import android.app.Notification;
4 | import android.app.NotificationManager;
5 | import android.app.PendingIntent;
6 | import android.content.Context;
7 | import android.content.Intent;
8 | import android.util.Log;
9 |
10 | import com.google.android.gcm.GCMBaseIntentService;
11 |
12 | import static com.dhruvb.myapplication.CommonUtilities.SENDER_ID;
13 | import static com.dhruvb.myapplication.CommonUtilities.displayMessage;
14 |
15 |
16 | public class GCMIntentService extends GCMBaseIntentService {
17 |
18 | private static final String TAG = "GCMIntentService";
19 |
20 | public GCMIntentService() {
21 | super(SENDER_ID);
22 | }
23 |
24 | /**
25 | * Method called on device registered
26 | **/
27 | @Override
28 | protected void onRegistered(Context context, String registrationId) {
29 | Log.i(TAG, "Device registered: regId = " + registrationId);
30 | displayMessage(context, "Your device registered with GCM");
31 | }
32 |
33 | /**
34 | * Method called on device un registred
35 | * */
36 | @Override
37 | protected void onUnregistered(Context context, String registrationId) {
38 | Log.i(TAG, "Device unregistered");
39 | displayMessage(context, getString(R.string.gcm_unregistered));
40 | }
41 |
42 | /**
43 | * Method called on Receiving a new message
44 | * */
45 | @Override
46 | protected void onMessage(Context context, Intent intent) {
47 | Log.i(TAG, "Received message");
48 | String message = intent.getExtras().getString("message");
49 |
50 | displayMessage(context, message);
51 | // notifies user
52 | generateNotification(context, message);
53 | }
54 |
55 | /**
56 | * Method called on receiving a deleted message
57 | * */
58 | @Override
59 | protected void onDeletedMessages(Context context, int total) {
60 | Log.i(TAG, "Received deleted messages notification");
61 | String message = getString(R.string.gcm_deleted, total);
62 | displayMessage(context, message);
63 | // notifies user
64 | generateNotification(context, message);
65 | }
66 |
67 | /**
68 | * Method called on Error
69 | * */
70 | @Override
71 | public void onError(Context context, String errorId) {
72 | Log.i(TAG, "Received error: " + errorId);
73 | displayMessage(context, getString(R.string.gcm_error, errorId));
74 | }
75 |
76 | @Override
77 | protected boolean onRecoverableError(Context context, String errorId) {
78 | // log message
79 | Log.i(TAG, "Received recoverable error: " + errorId);
80 | displayMessage(context, getString(R.string.gcm_recoverable_error,
81 | errorId));
82 | return super.onRecoverableError(context, errorId);
83 | }
84 |
85 | /**
86 | * Issues a notification to inform the user that server has sent a message.
87 | */
88 | private static void generateNotification(Context context, String message) {
89 | int icon = R.drawable.ic_launcher;
90 | long when = System.currentTimeMillis();
91 | NotificationManager notificationManager = (NotificationManager)
92 | context.getSystemService(Context.NOTIFICATION_SERVICE);
93 | Notification notification = new Notification(icon, message, when);
94 |
95 | String title = context.getString(R.string.app_name);
96 |
97 | Intent notificationIntent = new Intent(context, MainActivity.class);
98 | // set intent so it does not start a new activity
99 | notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
100 | Intent.FLAG_ACTIVITY_SINGLE_TOP);
101 | PendingIntent intent =
102 | PendingIntent.getActivity(context, 0, notificationIntent, 0);
103 | notification.setLatestEventInfo(context, title, message, intent);
104 | notification.flags |= Notification.FLAG_AUTO_CANCEL;
105 |
106 | // Play default notification sound
107 | notification.defaults |= Notification.DEFAULT_SOUND;
108 |
109 | // Vibrate if vibrate is enabled
110 | notification.defaults |= Notification.DEFAULT_VIBRATE;
111 | notificationManager.notify(0, notification);
112 |
113 | }
114 |
115 | }
--------------------------------------------------------------------------------
/src/com/dhruvb/myapplication/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.dhruvb.myapplication;
2 | import static com.dhruvb.myapplication.CommonUtilities.DISPLAY_MESSAGE_ACTION;
3 | import static com.dhruvb.myapplication.CommonUtilities.EXTRA_MESSAGE;
4 | import static com.dhruvb.myapplication.CommonUtilities.SENDER_ID;
5 | import android.app.Activity;
6 | import android.content.BroadcastReceiver;
7 | import android.content.Context;
8 | import android.content.Intent;
9 | import android.content.IntentFilter;
10 | import android.os.AsyncTask;
11 | import android.os.Bundle;
12 | import android.util.Log;
13 | import android.widget.TextView;
14 | import android.widget.Toast;
15 |
16 | import com.google.android.gcm.GCMRegistrar;
17 |
18 |
19 | public class MainActivity extends Activity {
20 | // label to display gcm messages
21 | TextView lblMessage;
22 |
23 | // Asyntask
24 | AsyncTask mRegisterTask;
25 |
26 | // Alert dialog manager
27 | AlertDialogManager alert = new AlertDialogManager();
28 |
29 | public static String name;
30 | public static String email;
31 |
32 | @Override
33 | public void onCreate(Bundle savedInstanceState) {
34 | super.onCreate(savedInstanceState);
35 | setContentView(R.layout.activity_main);
36 |
37 | // Getting name, email from intent
38 | Intent i = getIntent();
39 |
40 | name = i.getStringExtra("name");
41 | email = i.getStringExtra("email");
42 |
43 | // Make sure the device has the proper dependencies.
44 | GCMRegistrar.checkDevice(this);
45 |
46 | // Make sure the manifest was properly set - comment out this line
47 | // while developing the app, then uncomment it when it's ready.
48 | GCMRegistrar.checkManifest(this);
49 |
50 | lblMessage = (TextView) findViewById(R.id.lblMessage);
51 |
52 | registerReceiver(mHandleMessageReceiver, new IntentFilter(
53 | DISPLAY_MESSAGE_ACTION));
54 |
55 | // Get GCM registration id
56 | final String regId = GCMRegistrar.getRegistrationId(this);
57 |
58 | // Check if regid already presents
59 | if (regId.equals("")) {
60 | // Registration is not present, register now with GCM
61 | GCMRegistrar.register(this, SENDER_ID);
62 | } else {
63 | // Device is already registered on GCM
64 | if (GCMRegistrar.isRegisteredOnServer(this)) {
65 | // Skips registration.
66 | Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
67 | } else {
68 | // Try to register again, but not in the UI thread.
69 | // It's also necessary to cancel the thread onDestroy(),
70 | // hence the use of AsyncTask instead of a raw thread.
71 | final Context context = this;
72 | mRegisterTask = new AsyncTask() {
73 |
74 | @Override
75 | protected Void doInBackground(Void... params) {
76 | // Register on our server
77 | // On server creates a new user
78 | return null;
79 | }
80 |
81 | @Override
82 | protected void onPostExecute(Void result) {
83 | mRegisterTask = null;
84 | }
85 |
86 | };
87 | mRegisterTask.execute(null, null, null);
88 | }
89 | }
90 | }
91 |
92 | /**
93 | * Receiving push messages
94 | * */
95 | private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
96 | @Override
97 | public void onReceive(Context context, Intent intent) {
98 | String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
99 | // Waking up mobile if it is sleeping
100 |
101 | /**
102 | * Take appropriate action on this message
103 | * depending upon your app requirement
104 | * For now i am just displaying it on the screen
105 | * */
106 |
107 | // Showing received message
108 | lblMessage.append(newMessage + "\n");
109 | Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
110 |
111 | }
112 | };
113 |
114 | @Override
115 | protected void onDestroy() {
116 | if (mRegisterTask != null) {
117 | mRegisterTask.cancel(true);
118 | }
119 | try {
120 | unregisterReceiver(mHandleMessageReceiver);
121 | GCMRegistrar.onDestroy(this);
122 | } catch (Exception e) {
123 | Log.e("UnRegister Receiver Error", "> " + e.getMessage());
124 | }
125 | super.onDestroy();
126 | }
127 |
128 | }
--------------------------------------------------------------------------------