Empuje avanzado de Baidu imprescindible para Android

Escribir al frente

Hoy les enviaré un artículo sobre el empuje de Baidu. Las aplicaciones que se utilizan comúnmente en nuestros teléfonos móviles mostrarán mensajes push de vez en cuando en nuestra barra de mensajes. Las aplicaciones más utilizadas son QQ message push, WeChat message push, Alipay transfer message push, etc. En el futuro, usarás push para proyectos grandes y pequeños. Hoy resumí un artículo sobre el uso de Baidu Cloud para hacer mensajes push. Lo usarás a menudo en proyectos futuros. ¡Aprende cuando tengas tiempo!

Empuje avanzado de Baidu imprescindible para Android

Implementar notificaciones push de aplicaciones con Baidu Cloud

Paso 1: primero registre una cuenta en Baidu Cloud ( http://push.baidu.com/ )

Paso 2: después de registrar una cuenta, cree una aplicación

Empuje avanzado de Baidu imprescindible para Android
Paso 3: haga clic para crear una nueva aplicación.

Empuje avanzado de Baidu imprescindible para Android


Paso 4: Complete el nombre de la aplicación.

Empuje avanzado de Baidu imprescindible para Android

Paso 5: Haga clic para crear la aplicación y configurar la aplicación.

Empuje avanzado de Baidu imprescindible para Android

Paso 6: Seleccione la terminal (aquí elegimos Android) y complete el nombre del paquete del proyecto.

Empuje avanzado de Baidu imprescindible para Android

Paso 7: Recuerde usarlo en el proyecto API KEY.

Empuje avanzado de Baidu imprescindible para Android

Paso 8: Descargue Baidu Push SDK (sitio web oficial) y agréguelo al proyecto. (Respuesta de cuenta pública: se puede obtener el SDK de Baidu)

Empuje avanzado de Baidu imprescindible para Android

Paso 9: Comience a crear un nuevo proyecto de Android como BaiDu_Push_Demo.

Paso 10: agregue dependencias en build.gradle.


1//加载jar包
2compile files('src/main/JniLibs/pushservice-6.1.1.21.jar')

Paso 11: Cree una nueva clase PushServiceReceiver.java (las clases tienen que ver con las devoluciones de llamada push de Baidu)


  1package com.example.boybaby.baidu_pust_demo;
  2/**
  3 * Created by apple on 2018/4/25.
  4 */
  5import android.content.Context;
  6import android.text.TextUtils;
  7import android.util.Log;
  8import android.widget.Toast;
  9import org.json.JSONException;
 10import org.json.JSONObject;
 11import java.util.List;
 12/*
 13 * Push消息处理receiver。请编写您需要的回调函数, 一般来说: onBind是必须的,用来处理startWork返回值;
 14 *onMessage用来接收透传消息; onSetTags、onDelTags、onListTags是tag相关操作的回调;
 15 *onNotificationClicked在通知被点击时回调; onUnbind是stopWork接口的返回值回调
 16 * 返回值中的errorCode,解释如下:
 17 *0 - Success
 18 *10001 - Network Problem
 19 *10101  Integrate Check Error
 20 *30600 - Internal Server Error
 21 *30601 - Method Not Allowed
 22 *30602 - Request Params Not Valid
 23 *30603 - Authentication Failed
 24 *30604 - Quota Use Up Payment Required
 25 *30605 -Data Required Not Found
 26 *30606 - Request Time Expires Timeout
 27 *30607 - Channel Token Timeout
 28 *30608 - Bind Relation Not Found
 29 *30609 - Bind Number Too Many
 30 * 当您遇到以上返回错误时,如果解释不了您的问题,请用同一请求的返回值requestId和errorCode联系我们追查问题。
 31 *
 32 */
 33public class PushMessageReceiver extends com.baidu.android.pushservice.PushMessageReceiver {
 34    /**
 35     * TAG to Log
 36     */
 37    public static final String TAG = PushMessageReceiver.class
 38            .getSimpleName();
 39    /**
 40     * 调用PushManager.startWork后,sdk将对push
 41     * server发起绑定请求,这个过程是异步的。绑定请求的结果通过onBind返回。 如果您需要用单播推送,需要把这里获取的channel
 42     * id和user id上传到应用server中,再调用server接口用channel id和user id给单个手机或者用户推送。
 43     *
 44     * @param context   BroadcastReceiver的执行Context
 45     * @param errorCode 绑定接口返回值,0 - 成功
 46     * @param appid     应用id。errorCode非0时为null
 47     * @param userId    应用user id。errorCode非0时为null
 48     * @param channelId 应用channel id。errorCode非0时为null
 49     * @param requestId 向服务端发起的请求id。在追查问题时有用;
 50     * @return none
 51     */
 52    @Override
 53    public void onBind(Context context, int errorCode, String appid,
 54                       String userId, String channelId, String requestId) {
 55        String responseString = "onBind errorCode=" + errorCode + " appid="
 56                + appid + " userId=" + userId + " channelId=" + channelId
 57                + " requestId=" + requestId;
 58        Log.d(TAG, responseString);
 59        if (errorCode == 0) {
 60            // 绑定成功
 61            Log.d(TAG, "绑定成功");
 62        }
 63    }
 64    /**
 65     * 接收透传消息的函数。
 66     *
 67     * @param context             上下文
 68     * @param message             推送的消息
 69     * @param customContentString 自定义内容,为空或者json字符串
 70     */
 71    @Override
 72    public void onMessage(Context context, String message,
 73                          String customContentString) {
 74        String messageString = "透传消息 onMessage=\"" + message
 75                + "\" customContentString=" + customContentString;
 76        Log.d(TAG, messageString);
 77        // 自定义内容获取方式,mykey和myvalue对应透传消息推送时自定义内容中设置的键和值
 78        if (!TextUtils.isEmpty(customContentString)) {
 79            JSONObject customJson = null;
 80            try {
 81                customJson = new JSONObject(customContentString);
 82                String myvalue = null;
 83                if (!customJson.isNull("mykey")) {
 84                    myvalue = customJson.getString("mykey");
 85                }
 86            } catch (JSONException e) {
 87                // TODO Auto-generated catch block
 88                e.printStackTrace();
 89            }
 90        }
 91    }
 92    /**
 93     * 接收通知到达的函数。
 94     *
 95     * @param context             上下文
 96     * @param title               推送的通知的标题
 97     * @param description         推送的通知的描述
 98     * @param customContentString 自定义内容,为空或者json字符串
 99     */
100    @Override
101    public void onNotificationArrived(Context context, String title,
102                                      String description, String customContentString) {
103        String notifyString = "通知到达 onNotificationArrived  title=\"" + title
104                + "\" description=\"" + description + "\" customContent="
105                + customContentString;
106        Log.d(TAG, notifyString);
107        //Toast.makeText(context,description,Toast.LENGTH_LONG).show();
108        //Intent intent=new Intent(context,Main2Activity.class);
109        //context.startActivity(intent);
110        // 自定义内容获取方式,mykey和myvalue对应通知推送时自定义内容中设置的键和值
111        if (!TextUtils.isEmpty(customContentString)) {
112            JSONObject customJson = null;
113            try {
114                customJson = new JSONObject(customContentString);
115                String myvalue = null;
116                if (!customJson.isNull("mykey")) {
117                    myvalue = customJson.getString("mykey");
118                }
119            } catch (JSONException e) {
120                // TODO Auto-generated catch block
121                e.printStackTrace();
122            }
123        }
124        // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
125        // 你可以參考 onNotificationClicked中的提示从自定义内容获取具体值
126    }
127    /**
128     * 接收通知点击的函数。
129     *
130     * @param context             上下文
131     * @param title               推送的通知的标题
132     * @param description         推送的通知的描述
133     * @param customContentString 自定义内容,为空或者json字符串
134     */
135    @Override
136    public void onNotificationClicked(Context context, String title,
137                                      String description, String customContentString) {
138        String notifyString = "通知点击 onNotificationClicked title=\"" + title + "\" description=\""
139                + description + "\" customContent=" + customContentString;
140        Log.d(TAG, notifyString);
141        Toast.makeText(context,description,Toast.LENGTH_LONG).show();
142        // 自定义内容获取方式,mykey和myvalue对应通知推送时自定义内容中设置的键和值
143        if (!TextUtils.isEmpty(customContentString)) {
144            JSONObject customJson = null;
145            try {
146                customJson = new JSONObject(customContentString);
147                String myvalue = null;
148                if (!customJson.isNull("mykey")) {
149                    myvalue = customJson.getString("mykey");
150                }
151            } catch (JSONException e) {
152                // TODO Auto-generated catch block
153                e.printStackTrace();
154            }
155        }
156    }
157    /**
158     * setTags() 的回调函数。
159     *
160     * @param context   上下文
161     * @param errorCode 错误码。0表示某些tag已经设置成功;非0表示所有tag的设置均失败。
162     * @param failTags  设置失败的tag
163     * @param requestId 分配给对云推送的请求的id
164     */
165    @Override
166    public void onSetTags(Context context, int errorCode,
167                          List<String> sucessTags, List<String> failTags, String requestId) {
168        String responseString = "onSetTags errorCode=" + errorCode
169                + " sucessTags=" + sucessTags + " failTags=" + failTags
170                + " requestId=" + requestId;
171        Log.d(TAG, responseString);
172    }
173    /**
174     * delTags() 的回调函数。
175     *
176     * @param context   上下文
177     * @param errorCode 错误码。0表示某些tag已经删除成功;非0表示所有tag均删除失败。
178     * @param failTags  删除失败的tag
179     * @param requestId 分配给对云推送的请求的id
180     */
181    @Override
182    public void onDelTags(Context context, int errorCode,
183                          List<String> sucessTags, List<String> failTags, String requestId) {
184        String responseString = "onDelTags errorCode=" + errorCode
185                + " sucessTags=" + sucessTags + " failTags=" + failTags
186                + " requestId=" + requestId;
187        Log.d(TAG, responseString);
188    }
189    /**
190     * listTags() 的回调函数。
191     *
192     * @param context   上下文
193     * @param errorCode 错误码。0表示列举tag成功;非0表示失败。
194     * @param tags      当前应用设置的所有tag。
195     * @param requestId 分配给对云推送的请求的id
196     */
197    @Override
198    public void onListTags(Context context, int errorCode, List<String> tags,
199                           String requestId) {
200        String responseString = "onListTags errorCode=" + errorCode + " tags="
201                + tags;
202        Log.d(TAG, responseString);
203    }
204    /**
205     * PushManager.stopWork() 的回调函数。
206     *
207     * @param context   上下文
208     * @param errorCode 错误码。0表示从云推送解绑定成功;非0表示失败。
209     * @param requestId 分配给对云推送的请求的id
210     */
211    @Override
212    public void onUnbind(Context context, int errorCode, String requestId) {
213        String responseString = "onUnbind errorCode=" + errorCode
214                + " requestId = " + requestId;
215        Log.d(TAG, responseString);
216        if (errorCode == 0) {
217            // 解绑定成功
218            Log.d(TAG, "解绑成功");
219        }
220    }
221}

Paso 12: Configure los permisos y los servicios relacionados en AndroidManifest.xml.


  1<?xml version="1.0" encoding="utf-8"?>
  2<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3    package="包名">
  4    <!-- Push service 运行需要的权限 -->
  5    <uses-permission android:name="android.permission.INTERNET" />
  6    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
  7    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  8    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
  9    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
 10    <uses-permission android:name="android.permission.VIBRATE" />
 11    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 12    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
 13    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 14    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
 15    <!-- 富媒体需要声明的权限 -->
 16    <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER" />
 17    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
 18    <uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
 19    <!-- 适配Android N系统必需的ContentProvider写权限声明,写权限包含应用包名 -->
 20    <uses-permission android:name="baidu.push.permission.WRITE_PUSHINFOPROVIDER.包名" />
 21    <permission
 22        android:name="baidu.push.permission.WRITE_PUSHINFOPROVIDER.包名"
 23        android:protectionLevel="signature">
 24    </permission>
 25    <!-- 权限结束 -->
 26    <application
 27        android:allowBackup="true"
 28        android:icon="@mipmap/ic_launcher"
 29        android:label="@string/app_name"
 30        android:roundIcon="@mipmap/ic_launcher_round"
 31        android:supportsRtl="true"
 32        android:theme="@style/AppTheme">
 33        <activity android:name=".MainActivity">
 34            <intent-filter>
 35                <action android:name="android.intent.action.MAIN" />
 36                <category android:name="android.intent.category.LAUNCHER" />
 37            </intent-filter>
 38        </activity>
 39        <!-- push service start -->
 40        <!-- 用于接收系统消息以保证PushService正常运行 -->
 41        <receiver
 42            android:name="com.baidu.android.pushservice.PushServiceReceiver"
 43            android:process=":bdservice_v1">
 44            <intent-filter>
 45                <action android:name="android.intent.action.BOOT_COMPLETED" />
 46                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
 47                <action android:name="com.baidu.android.pushservice.action.notification.SHOW" />
 48                <action android:name="com.baidu.android.pushservice.action.media.CLICK" />
 49                <!-- 以下四项为可选的action声明,可大大提高service存活率和消息到达速度 -->
 50                <action android:name="android.intent.action.MEDIA_MOUNTED" />
 51                <action android:name="android.intent.action.USER_PRESENT" />
 52                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
 53                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
 54            </intent-filter>
 55        </receiver>
 56        <!-- Push服务接收客户端发送的各种请求 -->
 57        <receiver
 58            android:name="com.baidu.android.pushservice.RegistrationReceiver"
 59            android:process=":bdservice_v1">
 60            <intent-filter>
 61                <action android:name="com.baidu.android.pushservice.action.METHOD" />
 62                <action android:name="com.baidu.android.pushservice.action.BIND_SYNC" />
 63            </intent-filter>
 64            <intent-filter>
 65                <action android:name="android.intent.action.PACKAGE_REMOVED" />
 66                <data android:scheme="package" />
 67            </intent-filter>
 68        </receiver>
 69        <service
 70            android:name="com.baidu.android.pushservice.PushService"
 71            android:exported="true"
 72            android:process=":bdservice_v1">
 73            <intent-filter>
 74                <action android:name="com.baidu.android.pushservice.action.PUSH_SERVICE" />
 75            </intent-filter>
 76        </service>
 77        <!-- 4.4版本新增的CommandService声明,提升小米和魅族手机上的实际推送到达率 -->
 78        <service
 79            android:name="com.baidu.android.pushservice.CommandService"
 80            android:exported="true" />
 81        <!-- 适配Android N系统必需的ContentProvider声明,写权限包含应用包名 -->
 82        <provider
 83            android:name="com.baidu.android.pushservice.PushInfoProvider"
 84            android:authorities="com.example.boybaby.baidu_pust_demo.bdpush"
 85            android:exported="true"
 86            android:protectionLevel="signature"
 87            android:writePermission="baidu.push.permission.WRITE_PUSHINFOPROVIDER.包名.PushMessageReceiver" />
 88        <!-- push应用定义消息receiver声明 -->
 89        <receiver android:name="com.example.boybaby.baidu_pust_demo.PushMessageReceiver">
 90            <intent-filter>
 91                <!-- 接收push消息 -->
 92                <action android:name="com.baidu.android.pushservice.action.MESSAGE" />
 93                <!-- 接收bind、setTags等method的返回结果 -->
 94                <action android:name="com.baidu.android.pushservice.action.RECEIVE" />
 95                <!-- 接收通知点击事件,和通知自定义内容 -->
 96                <action android:name="com.baidu.android.pushservice.action.notification.CLICK" />
 97            </intent-filter>
 98        </receiver>
 99        <!-- push结束 -->
100    </application>
101</manifest>

Nota: El nombre del paquete debe reemplazarse con el nombre del paquete en su proyecto; de lo contrario, no se recibirá el mensaje push

Paso 13: Registre Baidu Push API KEY en MainAcitivity.


 1package com.example.boybaby.baidu_pust_demo;
 2import android.os.Bundle;
 3import android.support.v7.app.AppCompatActivity;
 4import com.baidu.android.pushservice.PushConstants;
 5import com.baidu.android.pushservice.PushManager;
 6public class MainActivity extends AppCompatActivity {
 7    @Override
 8    protected void onCreate(Bundle savedInstanceState) {
 9        super.onCreate(savedInstanceState);
10        setContentView(R.layout.activity_main);
11        //注册,第三个参数是要修改的API KEY的字符串
12        PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,"Cy1dU6vskzHqPmEmNu2aCZsR");
13    }
14}

Paso 14: crea una notificación y envíala.

Empuje avanzado de Baidu imprescindible para Android

Paso 15: Envíe correctamente.

Empuje avanzado de Baidu imprescindible para Android

Recibir notificación en el móvil:

Empuje avanzado de Baidu imprescindible para Android

Supongo que te gusta

Origin blog.51cto.com/15064450/2602802
Recomendado
Clasificación