Display memo of PUSH to Android device and notification to status bar using Google API
Preparations for PUSH notification on Android are described in http://dev.classmethod.jp/smartphone/android/gcm/. .. It was really helpful.
From here on, the changes and additions from the link above.
The procedure in the Google Developers Console has changed slightly, so I will explain it.
First, go to https://console.developers.google.com/project and select an existing project or "CREATE PROJECT".
Create or select a project to open the project page. Make a note of the "Project Number" at the top of the page. Then, turn on the STATUS of "Google Cloud Messaging for Android" from "APIs & auth"> "APIs" on the left side menu. The official document is here.
Next, go to "APIs & auth"> "Credentials" and select "CREATE NEW KEY" under "Public API access" to get a new API key. In the dialog that opens, select "Server Key" and enter 0.0.0.0 as the IP address. Change here if necessary. If it is for testing, 0.0.0.0 is fine. Perhaps.
GcmBroadcastReceiver.java will use the one linked above as it is. Then rewrite GcmIntentService.java for notification.
GcmIntentService.java
public class GcmIntentService extends IntentService {
private static final String TAG = GcmIntentService.class.getSimpleName();
private Notification notification;
private NotificationManager nm;
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.v(TAG, "onHandleIntent");
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
Log.d(TAG, "messageType: " + messageType + ",body:" + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
Log.d(TAG,"messageType: " + messageType + ",body:" + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
Log.d(TAG,"messageType: " + messageType + ",body:" + extras.toString());
}
}
//Up to here http://dev.classmethod.jp/smartphone/android/gcm/Almost the same as
//extras contains data from the server
//Here, everything is stored as a character string
Log.v(TAG, extras.toString());
int userId = Integer.parseInt(extras.getString("user_id"));
String text = extras.getString("text");
//Make MainActivity visible when you open a notification
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
i.setType("notification");
i.putExtra("user_id", userId);
i.putExtra("text", text);
//If the 4th argument is set to 0, only the extras of the Intent will not be updated, and the notification text will be different, but the extras will be the same.
//In the situation where you can only get the same value when you get extras in MainActivity of Intent destination
PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder notificationBuilder =
new Notification.Builder(getApplicationContext())
.setContentIntent(pi)
.setSmallIcon(R.drawable.icon_small)
.setTicker("I got a notification") //The text that appears in the status bar when a notification comes
.setContentTitle("Notification title") //The title that appears when you open the notification bar
.setContentText("Notification text") //Text displayed below the title
.setWhen(System.currentTimeMillis()); //When is the notification displayed?
long[] vibrate_ptn = {0, 100, 300, 1000}; //Vibration pattern (appropriate)
notification = notificationBuilder.build();
notification.vibrate = vibrate_ptn;
notification.defaults |= Notification.DEFAULT_LIGHTS; //Set default LED blinking pattern
notification.flags = Notification.FLAG_ONGOING_EVENT;
//Get an instance of NotificationManager
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(R.string.app_name, notification); //Notify the set Notification
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
nm.cancel(R.string.app_name);
}
}
Next, it is the Main Activity that is activated as the operation when you tap the notification. The link above is fine, but add the following code to ʻonCreate`.
MainActivity.java
//notification display relation
Intent intent = getIntent();
String intentType = intent.getType();
if (intentType != null && intentType.equals("notification")) {
Log.v(TAG + " extras", intent.getExtras().toString());
//GcmIntentService from extras.Extract the data entered in java
int user_id = intent.getIntExtra("user_id", 0);
String text = intent.getStringExtra("text");
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//Display dialog
Toast.makeText(this, text, Toast.LENGTH_LONG);
}
Make a note of the registrationId displayed in Log cat by registerInBackground ()
.
If you implement it as an application, pass this ID to the server and save it.
From python, use requests
to send requests to Google.
api.py
import requests
import json
def push_notificate(user_id, text):
'''If an error occurs, an error message will be entered in r
Calling this will notify Android
'''
gcm_url = 'https://android.googleapis.com/gcm/send'
#RegistrationId and API key noted above
regid = REGID
key = "key=" + APIKEY
headers = {'content-type': 'application/json', 'Authorization': key}
#The data to pass is appropriate.
#Match the dict key with the Android extras key
params = json.dumps(\
{'registration_ids': [regid], \
'data': {'id': user_id, 'text': text}})
r = requests.post(gcm_url, data=params, headers=headers)
print r.text
return
To clear basic authentication with requests
, pass ʻauth = (username, password)` as an argument, but this time pass it in headers.
I think this is okay.
Recommended Posts