GCM在本地发送推送通知成功,但Android没有显示,但当服务器发送时它能够接收


gcm send push notification locally successful but android no display but when server send it able to receive

我不小心将通知发送给应用程序的所有用户,并且我正在使用本地服务器进行测试。

但我发现我没有收到任何通知。但是当我使用在线服务器时,我能够收到通知。

以前我也在测试其他 android 项目,但只在 1 台带有本地服务器的设备上测试并且成功。所以,我对此感到非常困惑。

对不起,英语不好。希望你们都能理解我的问题。

首先添加以下内容:

compile 'com.google.android.gms:play-services-ads:8.3.0'
compile 'com.google.android.gms:play-services-analytics:8.3.0'
compile 'com.google.android.gms:play-services-base:8.3.0'
compile 'com.google.android.gms:play-services-gcm:8.3.0'
compile 'com.google.android.gms:play-services-plus:8.3.0'

之后获取GCM注册ID。为此,请使用以下代码:

public class StartActivity extends AppCompatActivity implements View.OnClickListener {
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private SharedPreferences sharedpreferences;
private GoogleCloudMessaging gcm;
static String regId;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);
    sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
}
@Override
protected void onResume() {
    super.onResume();
    doGCMRegistration();
}
private void doGCMRegistration() {
    if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(this);
        regId = sharedpreferences.getString("registration_id", null);
        if (regId == null || regId.isEmpty()) {
            getGCMRegisterIdInBackground();
        }
    }
}
private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            finish();
        }
        return false;
    }
    return true;
}
public void getGCMRegisterIdInBackground() {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
                }
                sharedpreferences.edit().putString("registration_id", gcm.register(<Sender ID>)).apply();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }.execute(null, null, null);
}

}

并在下面用于接收消息:

public class NotificationService extends IntentService {
private Handler handler;
private SharedPreferences sharedpreferences;
public static final String NOTIFICATION = "notification";
public static final byte CHAT_NOTIFICATION_ID = 0;
public NotificationService() {
    super("NotificationService");
    setIntentRedelivery(true);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    return START_STICKY;
}
@Override
public void onCreate() {
    super.onCreate();
    handler = new Handler();
    sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
}
@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    String message = extras.getString("message");
    int id = sharedpreferences.getInt(Constants.NOTIFICATION_ID, 0);
    sharedpreferences.edit().putString(NOTIFICATION + id, message).apply();
    sharedpreferences.edit().putInt(Constants.NOTIFICATION_ID, ++id).apply();
    showToast();
    BroadcastReceiver.completeWakefulIntent(intent);
}
public void showToast() {
    handler.post(new Runnable() {
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        public void run() {
            int count = sharedpreferences.getInt(Constants.NOTIFICATION_ID, 0);
            if (count == 0) return;
            ArrayList<String> items = new ArrayList<>();
            for (int i=0; i<count; i++){
                items.add(sharedpreferences.getString(NOTIFICATION + i, ""));
            }
            Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
                    intent, PendingIntent.FLAG_ONE_SHOT);
            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(getApplicationContext())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(getResources().getString(R.string.app_name))
                    .setContentText(sharedpreferences.getString(NOTIFICATION + 0, ""))
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setNumber(count)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);
            Intent resultIntent = new Intent(getApplicationContext(), ChatActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
            stackBuilder.addParentStack(ChatActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            inboxStyle.setBigContentTitle(getResources().getString(R.string.app_name));
            for (String event : items) {
                inboxStyle.addLine(event);
            }
            mBuilder.setStyle(inboxStyle);
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(0, mBuilder.build());
        }
    });
}

}

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

}

向清单添加权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

和回复:

<receiver
        android:name="com.google.android.gms.gcm.GcmReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.example.gcm" />
        </intent-filter>
    </receiver>
    <receiver
        android:name=".GCM.BroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.hmkcode.android.gcm" />
        </intent-filter>
    </receiver>
    <service android:name=".GCM.NotificationService" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="8298000" />