如何在自己的Android应用添加一个推送通知(How to add a push notifica

2019-06-18 06:29发布

我已经开发了一个推送通知的应用程序Android从本教程: 在Android应用程序推送通知 。 当我运行该应用程序会显示注册按钮。 当我点击注册按钮,当注册成功后,通知显示设备上。

我怎样才能将其包含在自己的应用程序? 我的应用程序有一个XML解析示例应用程序。 这里当添加任何新的项目,我希望显示(显示新顺序)在设备上的通知消息。 它会自动产生在这里。

Answer 1:

我张贴的演示应用程序, 谷歌云端通讯 。

请确保您创建API级别相同或比Android OS 2.2与谷歌API较高的演示应用程序

用户必须至少具有一个签署在谷歌帐户才能使用此服务。

首先,你必须添加GCM库 。

比创建类,我命名为GCMIntentService延伸GCMBaseIntentService如下:

package com.example.gcmdemo;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMConstants;

public class GCMIntentService extends GCMBaseIntentService {

     private static final String TAG = "Push Notification Demo GCMIntentService";

    @Override
    protected void onError(Context context, String errorId) {

        if(GCMConstants.ERROR_ACCOUNT_MISSING.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Account Missing");
        } else if(GCMConstants.ERROR_AUTHENTICATION_FAILED.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Authentication Failed");
        } else if(GCMConstants.ERROR_INVALID_PARAMETERS.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Invalid Parameters");
        } else if(GCMConstants.ERROR_INVALID_SENDER.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Invalid Sender");
        } else if(GCMConstants.ERROR_PHONE_REGISTRATION_ERROR.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Phone Registration Error");
        } else if(GCMConstants.ERROR_SERVICE_NOT_AVAILABLE.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Service Not Available");
        } 
    }

    @Override
    protected void onMessage(Context context, Intent intent) {

        // App Server Sends message as key value pairs 
        String value1 = intent.getStringExtra("key1");
        String value2 = intent.getStringExtra("key2");

        Log.v(TAG, "key1: "+value1 );
        Log.v(TAG, "key2: "+value2 );
    }

    @Override
    protected void onRegistered(Context context, String regId) {

        Log.v(TAG, "Successfull Registration : "+regId);
    }

    @Override
    protected void onUnregistered(Context context, String regId) {

        Log.v(TAG, "Successfully Unregistred : "+regId);
    }

    @Override
    protected String[] getSenderIds(Context context) {
        return super.getSenderIds(context);
    }

    @Override
    protected void onDeletedMessages(Context context, int total) {
        super.onDeletedMessages(context, total);
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId) {
        return super.onRecoverableError(context, errorId);
    }
}

下面是你应该在下面的演示活动检查登记:

package com.example.gcmdemo;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

import com.google.android.gcm.GCMRegistrar;

public class MainActivity extends Activity {

    private static final String TAG = "Push Notification Demo Activity";
    private static final String SENDER_ID = "1069713227710";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);
        final String regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) {
          GCMRegistrar.register(this, SENDER_ID);
        } else {
          Log.v(TAG, "Already registered : "+regId);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

最后演示清单:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gcmdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />

    <permission
        android:name="com.example.gcmdemo.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.example.gcmdemo.permission.C2D_MESSAGE" />

    <!-- App receives GCM messages. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <!-- GCM connects to Google Services. -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- GCM requires a Google account. -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <!-- Keeps the processor from sleeping when a message is received. -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="com.google.android.gcm.GCMBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.example.gcmdemo" />
            </intent-filter>
        </receiver>

        <service android:name=".GCMIntentService" />
    </application>

</manifest>

你也将需要为这里指定的第三方服务器端脚本 。



Answer 2:

个人建议你,而不是GCM这里面还有其他命名库解析为PushNotification,它的工作原理同谷歌云消息却是那么那么那么那么多容易然后GCM

你刚才下载PUSH-通知JAR文件和简单的二,三线的代码

学习使用本网站https://parse.com/tutorials/android-push-notifications

即使你没有使用PHP或任何种类的服务器端代码它为您提供便利

看看我将要给你演示

  Parse.initialize(this, "YOUR_APP_ID", "YOUR_CLIENT_KEY");
  PushService.setDefaultPushCallback(this, YourDefaultActivity.class);

从上面的代码是足够用于接收推送通知

如果您要发送通知他们提供了很好的用户界面UI看的画面,他们提供



Answer 3:

发送使用FCM推送通知

谷歌弃用谷歌云端通讯(GCM),并推出了火力地堡是云端通讯(FCM)新的推送通知服务器。 FCM是相同像GCM,FCM还为移动平台跨平台的消息解决方案

火力地堡云消息可以发送三种类型的消息( 消息类型 )

1.Notification留言

2.Data留言

3.message既通知和数据

火力地堡云端通讯整合步骤: -

1.设置新项目或Firbase控制台导入项目( https://firebase.google.com/

2.增加在火力地堡应用APP相同的包名称。

3.Get“谷歌 - services.json”文件,并把该文件到您的项目的应用folder.This文件包含所有的URL和键谷歌服务的,所以不要更改或编辑该文件。

4.增加在项目的新摇篮依赖于火力地堡。

//app/build.gradle
dependencies {
  compile 'com.google.firebase:firebase-messaging:9.6.0'
}

apply plugin: 'com.google.gms.google-services'

5.创建一个包含所有我们整个应用程序的FCM使用常量值的类。

public class Config {
 public static final String TOPIC_GLOBAL = "global";
 // broadcast receiver intent filters
public static final String REGISTRATION_COMPLETE = "registrationComplete";
public static final String PUSH_NOTIFICATION = "pushNotification";

// id to handle the notification in the notification tray
public static final int NOTIFICATION_ID = 100;
public static final int NOTIFICATION_ID_BIG_IMAGE = 101;
public static final String SHARED_PREF = "ah_firebase";
 }

6.创建一个名为类MyFirebaseInstanceIDService.java这将接收到火力注册ID,这将是唯一的每个应用程序。 注册ID被用来发送信息到单个设备中。

    public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        // Saving reg id to shared preferences
        storeRegIdInPref(refreshedToken);

        // sending reg id to your server
        sendRegistrationToServer(refreshedToken);

        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
        registrationComplete.putExtra("token", refreshedToken);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    private void sendRegistrationToServer(final String token) {
        // sending gcm token to server
        Log.e(TAG, "sendRegistrationToServer: " + token);
    }

    private void storeRegIdInPref(String token) {
    SharedPreferences pref =     getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("regId", token);
        editor.commit();
    }
    }

7.Create命名MyFirebaseMessagingService.java多了一个服务类。 这将收到火力消息。

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

    private NotificationUtils notificationUtils;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)
            return;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getNotification().getBody());
        }
    }
 private void handleNotification(String message) {
        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        }else{
            // If the app is in background, firebase itself handles the notification
        }
    }
 /**
     * Showing notification with text only
     */
    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
    }

    /**
     * Showing notification with text and image
     */
    private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
    }
}

8.In在AndroidManifest.xml中添加这两个火力点服务MyFirebaseMessagingService和MyFirebaseInstanceIDService。

 <!-- Firebase Notifications -->
        <service android:name=".service.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <service android:name=".service.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <!-- ./Firebase Notifications -->

现在,只需发送您的第一条消息

注意事项:

*。读了谷歌文档的火力地堡云消息 *

2.如果你想把一个GCM客户端(Android版)火力地堡云消息请按照下列步骤及文件( 迁移一个GCM客户端应用 )

3.Android样品教程和代码( 接收续聘通知 )



文章来源: How to add a push notification in my own android app