我正在做一个应用程序,需要我向用户发送推送通知。
我正在使用this example。首先,我在点击通知栏上的通知时没有打开所需的活动但是现在已经解决了。我在应用程序处于活动状态或后台时收到通知。
然而,我的一部手机(Nexus 4有Android Kitkat 4.4)出现意外行为:当应用程序处于前台并显示消息时,它会通过广播显示通知,但是当点击通知时无法启动需要启动的活动在通知栏上。有时它不会像我的其他手机一样收到通知。
package com.androidhive.pushnotifications;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gcm.GCMBaseIntentService;
import static com.androidhive.pushnotifications.CommonUtilities.SENDER_ID;
import static com.androidhive.pushnotifications.CommonUtilities.displayMessage;
import android.database.sqlite.SQLiteDatabase;
public class GCMIntentService extends GCMBaseIntentService {
private static SQLiteDatabase sampleDB;
private static final String SAMPLE_DB_NAME = "pushData.db";
private static final String SAMPLE_TABLE_NAME = "pushtabledata";
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(SENDER_ID);
}
/**
* Method called on device registered
**/
@Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, "Your device registred with GCM");
Log.d("NAME", MainActivity.name);
ServerUtilities.register(context, MainActivity.name, MainActivity.email, registrationId);
}
/**
* Method called on device un registred
* */
@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
ServerUtilities.unregister(context, registrationId);
}
/**
* Method called on Receiving a new message
* */
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("price");
Log.d("GCMIntentService", "here");
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on receiving a deleted message
* */
@Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on Error
* */
@Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
/*NotificationManager mNotificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent inty = new Intent(context, MainActivity.class);
inty.putExtra("message", message);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
inty, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setContentText(message);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(0, mBuilder.build());*/
// Log.d("in GCM Intent", message);
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification();
StringBuffer sb = new StringBuffer();
if(message != null){
Log.d("in GCM Intent", "not null");
if(message.contains("@@@@@@@@@@@@"))
{
Log.d("in GCM Intent", "got @");
String []parts = message.split("@@@@@@@@@@@@");
Log.d("After : separate", parts[0] + "" + parts[1]);
sb.append(parts[0]);
sampleDB= context.openOrCreateDatabase(SAMPLE_DB_NAME, SQLiteDatabase.OPEN_READWRITE, null);
ContentValues values = new ContentValues();
values.put("title", parts[0]);
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
values.put("time", date);
values.put("message", parts[1]);
try{
sampleDB.beginTransaction();
sampleDB.insert(SAMPLE_TABLE_NAME, null, values);
sampleDB.setTransactionSuccessful();
}
catch(Exception e)
{
Log.d("Exception",e.toString());
}
finally{
sampleDB.endTransaction();
}
sampleDB.close();
}
else
{
sb.append(message);
}
}
else
{
sb.append("No data");
}
String title = context.getString(R.string.app_name);
notification.when = when;
notification.icon = icon;
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.putExtra("message", message);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, title, sb.toString(), intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
我尝试了谷歌关于这个问题并发现了一些像下面这样的数据,但它没有任何意义。
编辑: - 我按要求粘贴了GCMIntentService的代码。
答案 0 :(得分:7)
此问题以Android Kitkat 4.4和Lollipop而闻名。 请添加:
android:exported="true"
在android清单里面的活动标签,应该在点击状态栏的通知后打开。
此外,Google Play服务已更新,因此请将Google Play服务库导入您的项目,而不是导入gcm.jar。
答案 1 :(得分:3)
我遇到了同样的问题。尝试使用
PendingIntent.getActivity(context, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);`
而不是
PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);