简体   繁体   中英

Android - Using received push notification

I've been trying out the push notifications from Parse.com on my Android application. I also write a PHP file to send notifications and so far its working well. Now I would like to know how to use the message received in my Android app as a variable.

My PHP file is this:

<?php 
$APPLICATION_ID = "xxxxx";
$REST_API_KEY = "xxxxx";
$MESSAGE = "Test 123";


$url = 'https://api.parse.com/1/push';
$data = array(
    'where' => '{}',   
    'expiry' => 1451606400,
    'data' => array(
        'alert' => $MESSAGE,
    ),
);
$_data = json_encode($data);
$headers = array(
    'X-Parse-Application-Id: ' . $APPLICATION_ID,
    'X-Parse-REST-API-Key: ' . $REST_API_KEY,
    'Content-Type: application/json',
    'Content-Length: ' . strlen($_data),
);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $_data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_exec($curl);
?>


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Send Push</title>
</head>
<body>
    <?php if (isset($response)) {
        echo '<h2>Response from Parse API</h2>';
        echo '<pre>' . htmlspecialchars($response) . '</pre>';
        echo '<hr>';
    } elseif ($_POST) {
        echo '<h2>Error!</h2>';
        echo '<pre>';
        var_dump($APPLICATION_ID, $REST_API_KEY, $MESSAGE);
        echo '</pre>';
    } ?>

    <h2>Send Message to Parse API</h2>
    <form id="parse" action="" method="post" accept-encoding="UTF-8">
        <p>
            <label for="app">APPLICATION_ID</label>
            <input type="text" name="app" id="app" value="<?php echo htmlspecialchars($APPLICATION_ID); ?>">
        </p>
        <p>
            <label for="api">REST_API_KEY</label>
            <input type="text" name="api" id="api" value="<?php echo htmlspecialchars($REST_API_KEY); ?>">
        </p>
        <p>
            <label for="api">MESSAGE</label>
            <textarea name="body" id="body"><?php echo htmlspecialchars($MESSAGE); ?></textarea>
        </p>
        <p>
            <input type="submit" value="send">
        </p>
    </form>
</body>
</html>

and on my Android app I have this declared on my main activity:

Parse.initialize(this, "xxxxx", "xxxxxx"); 
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
ParseAnalytics.trackAppOpened(getIntent());

and this on my manifest, with the permissions.

<receiver android:name="com.parse.ParseBroadcastReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.USER_PRESENT" />
    </intent-filter>
</receiver>

So bottom line I want to be able to do something like

btn1.setText(msg);

where msg would be the message received in the push notification

I can tell you how I have done, hopefully it will be easy to translate to your usage:

First off, I have registered a regular BroadcastReceiver in my manifest:

    <receiver android:name="com.parse.ParseBroadcastReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.USER_PRESENT" />
    </intent-filter>
    </receiver>
    <receiver android:name="mypackage.ParseSMSReceiver" >
        <intent-filter>
            <action android:name="mypackage.INCOMMING_PARSESMS" />
        </intent-filter>
    </receiver>

Now, the ParseSMSReceiver is suppose to handle push notifications with some data. Here is how I extract some of the data I receive:

JSONObject json = new JSONObject(intent
        .getExtras().getString(
                "com.parse.Data"));

String sms = (String) json
        .get(Constants.EXTRA_MESSAGE);
String sender = (json
        .has(Constants.EXTRA_SENDER)) ? (String) json
        .get(Constants.EXTRA_SENDER) : null;

Finally, here is how I send a notification so that they will be received by ParseSMSReceiver containing the expected data:

JSONObject data = new JSONObject();
//this is the action matching my BroadcastReceiver
data.put("action", "mypackage.INCOMMING_PARSESMS");
data.put(Constants.EXTRA_SENDER, sender);
data.put(Constants.EXTRA_MESSAGE, message);
data.put(Constants.EXTRA_CHANNELS, new JSONArray(channels));

ParsePush androidPush = new ParsePush();
androidPush.setQuery(query);
androidPush.setData(data);
androidPush.setExpirationTimeInterval(tenminutes);
androidPush.sendInBackground();

As you perhaps can see, I send push messages directly from my app but the concept should apply just as well to you, using PHP.

Hope this helps

edit:

You can test the code on android without relying on your PHP code. The dashboard at parse.com lets you send JSON push notifications directly. The JSON message you would like to send should be something like:

{ "action": "yourpackage.YOURACTIONSTRING", "msg" : "the message to be received" }

yourpackage.YOURACTIONSTRING should match the action android:name of your receiver in the manifest.

Also, to verify the ability to receive regular push messages, try sending a normal message from the dashboard.

edit2

Reviewed your code, and there is no need to register for the broadcast when defined in the manifest. Here is an example of what you should do using ParseSMSReceiver from earlier:

public class ParseSMSReceiver extends BroadcastReceiver {

private static final String TAG = ParseSMSReceiver.class.getName();

@Override
public void onReceive(final Context context, final Intent intent) {

        Bundle extras = intent.getExtras();
        String message = extras != null ? extras
                .getString("com.parse.Data") : "";
        JSONObject jObject;
        try {
            jObject = new JSONObject(message);
            Log.d("Log",
                    jObject.getString("msg")
                            + jObject.getString("action"));
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

}
}

The ParseSMSReceiver should reside in the correct package to match the receiver android:name in the manifest.

This receiver will automatically listen for whatever action string you have defined in the intent-filter part.

Changed "alert" to "msg", as that is what I use in the example above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM