我正在使用Parse.com的推送通知服务。根据{{3}}:
覆盖onPushReceive以触发“无声”的后台操作 推
我找到了onPushOpen()doc的源代码,但现在我必须重写onPushReceive()来自定义声音和振动的行为。我不知道我应该在onPushReceive()中做什么,是否有任何示例代码可以帮助我找出onPushReceive()中的逻辑?感谢。
答案 0 :(得分:18)
创建一个扩展ParsePushBroadcastReceiver的新类:
public class MyPushBroadcastReceiver extends ParsePushBroadcastReceiver {
public static final String PARSE_DATA_KEY = "com.parse.Data";
@Override
protected Notification getNotification(Context context, Intent intent) {
// deactivate standard notification
return null;
}
@Override
protected void onPushOpen(Context context, Intent intent) {
// Implement
}
@Override
protected void onPushReceive(Context context, Intent intent) {
JSONObject data = getDataFromIntent(intent);
// Do something with the data. To create a notification do:
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle("Title");
builder.setContentText("Text");
builder.setSmallIcon(R.drawable.ic_notification);
builder.setAutoCancel(true);
// OPTIONAL create soundUri and set sound:
builder.setSound(soundUri);
notificationManager.notify("MyTag", 0, builder.build());
}
private JSONObject getDataFromIntent(Intent intent) {
JSONObject data = null;
try {
data = new JSONObject(intent.getExtras().getString(PARSE_DATA_KEY));
} catch (JSONException e) {
// Json was not readable...
}
return data;
}
}
在你的Manifest中添加:
<receiver
android:name=".MyPushBroadcastReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
更多信息:http://www.androidhive.info/2015/06/android-push-notifications-using-parse-com/
答案 1 :(得分:2)
您可以使用intent额外参数“action”来调用您的意图来处理您想要的任何内容。
原创onPushReceive来源:
protected void onPushReceive(Context context, Intent intent) {
JSONObject pushData = null;
try {
pushData = new JSONObject(intent.getStringExtra("com.parse.Data"));
} catch (JSONException var7) {
Parse.logE("com.parse.ParsePushReceiver", "Unexpected JSONException when receiving push data: ", var7);
}
String action = null;
if(pushData != null) {
action = pushData.optString("action", (String)null);
}
if(action != null) {
Bundle notification = intent.getExtras();
Intent broadcastIntent = new Intent();
broadcastIntent.putExtras(notification);
broadcastIntent.setAction(action);
broadcastIntent.setPackage(context.getPackageName());
context.sendBroadcast(broadcastIntent);
}
Notification notification1 = this.getNotification(context, intent);
if(notification1 != null) {
ParseNotificationManager.getInstance().showNotification(context, notification1);
}
}
如果意图中没有额外的“警告”或“标题”,则不会发出通知。
因此,您根本不需要扩展任何类来进行静默推送更新......