Push notifications from Python to Android using Google's API

Display memo of PUSH to Android device and notification to status bar using Google API

Client (Android)

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.

Server (Python)

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

Push notifications from Python to Android using Google's API
Push notification from Python server to Android
Run Ansible from Python using API
From Python to using MeCab (and CaboCha)
How to get followers and followers from python using the Mastodon API
I tried using UnityCloudBuild API from Python
API explanation to touch mastodon from python
Connect to coincheck's Websocket API from Python
Detect Japanese characters from images using Google's Cloud Vision API in Python
How to display Map using Google Map API (Android)
Procedure to use TeamGant's WEB API (using python)
I want to email from Gmail using Python.
Send push notifications to iOS apps in Python
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
MessagePack-Call Python (or Python to Ruby) methods from Ruby using RPC
Copy S3 files from Python to GCS using GSUtil
Query from python to Amazon Athena (using named profile)
A little bit from Python using the Jenkins API
Flatten using Python yield from
Post from Python to Slack
Cheating from PHP to Python
Anaconda updated from 4.2.0 to 4.3.0 (python3.5 updated to python3.6)
Post to Twitter using Python
Start to Selenium using python
Switch from python2.7 to python3.6 (centos7)
Connect to sqlite from python
Use e-Stat API from Python
Convert from Pandas DataFrame to System.Data.DataTable using Python for .NET
I tried to create API list.csv in Python from swagger.yaml
Predict gender from name using Gender API and Pykakasi in Python
Tweet Now Playing to Twitter using the Spotify API. [Python]
Output product information to csv using Rakuten product search API [Python]
Send push notifications to iOS apps with Python2 (with sample code)
Call Matlab from Python to optimize
How to install python using anaconda
Using Rstan from Python with PypeR
Create folders from '01' to '12' with python
[Python3] Google translate google translate without using api
Notes on using MeCab from Python
Post from python to facebook timeline
[Lambda] [Python] Post to Twitter from Lambda!
Try using Pleasant's API (python / FastAPI)
Connect to utf8mb4 database from python
Using Cloud Storage from Python3 (Introduction)
Python (from first time to execution)
Use kabu Station® API from Python
View Mac desktop notifications from Python
Post images from Python to Tumblr
Make a request from Device Farm (appium python) to API Gateway
How to use OpenPose's Python API
Use the Flickr API from Python
Implementation of desktop notifications using Python
[Python] Conversation using OpenJTalk and Talk API (up to voice output)
Get upcoming weather from python weather api
Try using Python argparse's action API
Let's touch Google's Vision API from Python for the time being
How to access wikipedia from python
Python to switch from another language
Get Android notifications to speak slowly
Regularly upload files to Google Drive using the Google Drive API in Python