【问题标题】:receiving android push notification接收安卓推送通知
【发布时间】:2015-10-05 01:51:07
【问题描述】:

我有我设备的注册 ID,当我尝试从我的服务器向我的应用发送推送通知时,我收到了成功消息:

{"multicast_id":SOME_ID,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:SOME_ID"}]}

但我的应用没有显示任何通知或警报。我在网络上尝试了超过 6 种不同的指南,但仍然找不到从我的应用接收此通知的方法。

即使用户没有打开应用程序,如何接收此通知并将其作为推送通知显示在我的应用程序中?

public class GcmIntentService extends IntentService {
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    public GcmIntentService() {
        super("GcmIntentService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0);
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle("New Message!");
        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }
}

广播接收器

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

【问题讨论】:

  • 可能推送正在发送到您的应用程序,但您没有正确处理它。如果您不共享您的某些应用程序代码,我无法推断出其他任何内容。您的清单中是否添加了适当的权限?
  • 请发布您用于 IntentService 的代码
  • 是的,关于权限我确定,但我不知道如何处理我发送的通知。尝试使用我在网上找到的所有内容,但没有任何效果。
  • @AndroidEnthusiast 我发布了它,但我的主要活动中没有任何相关内容
  • 请同时添加广播接收器的代码

标签: android google-cloud-messaging


【解决方案1】:
public class MyGcmListenerService extends GcmListenerService {

private static final String TAG = "MyGcmListenerService";

@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");

    // showing an alert activity if there is an active activity 

    Intent pushReceivedIntent = new Intent("Push");
    pushReceivedIntent.putExtras(data);

    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    ComponentName componentInfo = taskInfo.get(0).topActivity;
    if(componentInfo.getPackageName().equalsIgnoreCase(Constants.APP_PACKAGE)){
        getApplicationContext().sendBroadcast(pushReceivedIntent);
    }
    else{
        // showNotification(data);
    }
}

还有……

private void showNotification(Bundle data) {
    String message = data.getString("message");

    Intent intent = new Intent(this, HomeActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

这是我使用的 Intent 服务,

public class RegistrationIntentService extends IntentService {

private static final String TAG = "RegIntentService";
private static final String gcm_defaultSenderId = "1234556";

public RegistrationIntentService() {
    super(TAG);
}

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    try {
        // [START register_for_gcm]
        // Initially this call goes out to the network to retrieve the token, subsequent calls
        // are local.
        // [START get_token]
        InstanceID instanceID = InstanceID.getInstance(this);
        String token = instanceID.getToken(gcm_defaultSenderId,
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        // [END get_token]


        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(token);

        sharedPreferences.edit().putBoolean("SENT_TOKEN_TO_SERVER", true).apply();
        // [END register_for_gcm]
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        // If an exception happens while fetching the new token or updating our registration data
        // on a third-party server, this ensures that we'll attempt the update at a later time.
        sharedPreferences.edit().putBoolean("SENT_TOKEN_TO_SERVER", false).apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new Intent("REGISTRATION_COMPLETE");
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}

private void sendRegistrationToServer(String token) {
    Log.d("token ", token);
    //TODO: Send This to server
}

}

现在,在你的活动 onResume 方法中,你需要添加接收者。

 protected void onResume() {
    super.onResume();

    // receiver to get the Notification ALert
    IntentFilter filter = new IntentFilter();
    filter.addAction("PUSH");

    mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Intent intent1 = new Intent(this, SomeActivity.class);
            intent1.putExtras(intent.getExtras());
            startActivity(intent1);
        }
    };
    registerReceiver(mReceiver, filter);

    // Push Notification receiver
    LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
            new IntentFilter("REGISTRATION_COMPLETE"));
}

另外,还要检查设备令牌。

【讨论】:

  • Constants.ACTION_PUSH 这是什么?我对这个常量类有一个错误,我没有。
  • @user4177344:对不起,我的错。这是一个用于识别意图的常量。已编辑我的答案。感谢您指出。
  • 很好,但我在用它做什么?只是将此代码添加为新的 java 类或什么?如何实现它以向我显示我从我的 php 代码发送的推送?我仍然没有收到任何通知
  • 你是否正确地遵循了这个? developers.google.com/cloud-messaging/android/start。对我来说很好。如果你愿意,我可以分享我的完整实现。
猜你喜欢
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多