信鸽推送踩过的坑,特别是6.0以后

现在的android app中都存在推送这个功能,市面上的第三方也比较多,想个推,信鸽,JPush等,今天主要讲一下,我们公司用的信鸽推送。
1,将信鸽SDK目录下的libs目录下的文件考到工程的libs目录下,也就是导入包,一定要添加依赖
	// 信鸽的包
compile files('libs/Xg_sdk_v2.46_20160602_1638.jar')
compile files('libs/wup-1.0.0.E-SNAPSHOT.jar')
compile files('libs/jg_filter_sdk_1.1.jar')

2,按照提示在 Maindest 中配置
    
<receiver
    android:name="com.tencent.android.tpush.XGPushReceiver"
    android:process=":xg_service_v2">
    <intent-filter android:priority="0x7fffffff">
        
        <action android:name="com.tencent.android.tpush.action.SDK" />
        <action android:name="com.tencent.android.tpush.action.INTERNAL_PUSH_MESSAGE" />
        
        <action android:name="android.intent.action.USER_PRESENT" />
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        
        <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
    intent-filter>
receiver>
<activity
    android:name="com.tencent.android.tpush.XGPushActivity"
    android:exported="false">
    <intent-filter>
        
        <action android:name="android.intent.action" />
    intent-filter>
activity>
<service
    android:name="com.tencent.android.tpush.service.XGPushService"
    android:exported="true"
    android:persistent="true"
    android:process=":xg_service_v2" />
<service
    android:name="com.tencent.android.tpush.rpc.XGRemoteService"
    android:exported="true">
    <intent-filter>
        <action android:name="${applicationId}.PUSH_ACTION" />
    intent-filter>
service>
<meta-data
    android:name="XG_V2_ACCESS_ID"
    android:value="2100248887" />
<meta-data
    android:name="XG_V2_ACCESS_KEY"
    android:value="AT32A916BJLD" />
3,申请所需要的权限
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BATTERY_STATS" />

4,这时要特别注意
buildToolsVersion "24.0.2"
defaultConfig {
    minSdkVersion 17
    targetSdkVersion 22
}
    你的targetSdkVersion得版本最高不得超过22,要不6.0以上的一些手机不能收到消息(小米)

5,这时你就可以在你的代码中实现你的逻辑

// 注册推送reciver一定先执行
rigisterPush();
       // 注册推送服务
    rigisterPushService();
 * 注册云推送接收方法
 */
private void rigisterPush() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(SysConfig.PUSH_MESSAGE_ACTION);
    registerReceiver(testReceiveData, filter);
}
     * 注册推送
     */
    private void rigisterPushService() {
        XGPushConfig.enableDebug(this, false);
        // 如果需要知道注册是否成功,请使用registerPush(getApplicationContext(),
        // XGIOperateCallback)带callback版本
        // 如果需要绑定账号,请使用registerPush(getApplicationContext(),account)版本
        // 具体可参考详细的开发指南
        // 传递的参数为ApplicationContext
//        Context context = MainActivity.this;
        XGPushManager.registerPush(getApplicationContext(), xgiOperateCallback);
        if (yunPushRstTimer != null) {
            yunPushRstTimer.cancel();
        }
        yunPushRstTimer = new YunPushRstTimer(10000, 10000);
        yunPushRstTimer.start();
        // 在XGPushManager.registerPush(context)或其它版本的注册接口之后调用以下代码
        // 使用ApplicationContext
        Intent service = new Intent(this, XGPushService.class);
        startService(service);
    }
    XGIOperateCallback xgiOperateCallback = new XGIOperateCallback() {
        @Override
        public void onSuccess(Object o, int i) {//成功时
            registerYunPushSuccess = true;
            // 关闭 timer
            //Log.e("tokenid","----------:" +o);
            if (yunPushRstTimer != null) {
                yunPushRstTimer.cancel();
            }
            myApplication.setToken((String) o);
           
            if (((MyApplication) getApplication()).getUserInfoBean().getUserInfo() != null) {
                // 请求服务器提交token,只有注册成功才能收到消息
                settoken((String) o);
            }
        }
        @Override
        public void onFail(Object o, int i, String s) {
        }
    };
 * 推送注册计时器不成功的时候再次去注册
 */
class YunPushRstTimer extends MyCountDownTimer {
    public YunPushRstTimer(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }
    @Override
    public void onFinish() {// 计时完毕
        // 如果成功的话 就什么都不坐 否则重新注册
        if (!registerYunPushSuccess) {
            rigisterPushService();
            Log.e("main", "重新注册中");
        }
    }
    @Override
    public void onTick(long millisUntilFinished) {// 计时过程
    }
}

最后一步自己写一个Receiver 继承 XGPushBaseReceiver 来做一些推送过来时的操作

public class MessageReceiver extends XGPushBaseReceiver {

    // private Intent intent = new Intent("com.qq.xgdemo.activity.UPDATE_LISTVIEW");

    public static final String LogTag = "TPushReceiver";


    private void show(Context context, String text) {

//    Toast.makeText(context, text, Toast.LENGTH_SHORT).show();

    }


    // 通知展示

    @Override

    public void onNotifactionShowedResult(Context context,

                                          XGPushShowedResult notifiShowedRlt) {

//    if (context == null || notifiShowedRlt == null) {

//       return;

//    }

//    XGNotification notific = new XGNotification();

//    notific.setMsg_id(notifiShowedRlt.getMsgId());

//    notific.setTitle(notifiShowedRlt.getTitle());

//    notific.setContent(notifiShowedRlt.getContent());

//    // notificationActionType==1为Activity,2为url,3为intent

//    notific.setNotificationActionType(notifiShowedRlt

//          .getNotificationActionType());

//    // Activity,url,intent都可以通过getActivity()获得

//    notific.setActivity(notifiShowedRlt.getActivity());

//    notific.setUpdate_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

//          .format(Calendar.getInstance().getTime()));

//    NotificationService.getInstance(context).save(notific);

//    context.sendBroadcast(intent);

//    show(context, "您有1条新消息, " + "通知被展示 , " + notifiShowedRlt.toString());

//    showNotification(context, notifiShowedRlt.getTitle(), notifiShowedRlt.getContent());

    }


    @Override

    public void onUnregisterResult(Context context, int errorCode) {

        if (context == null) {

            return;

        }

        String text = "";

        if (errorCode == XGPushBaseReceiver.SUCCESS) {

            text = "反注册成功";

        } else {

            text = "反注册失败" + errorCode;

        }

        Log.d(LogTag, text);

        show(context, text);


    }


    @Override

    public void onSetTagResult(Context context, int errorCode, String tagName) {

        if (context == null) {

            return;

        }

        String text = "";

        if (errorCode == XGPushBaseReceiver.SUCCESS) {

            text = "\"" + tagName + "\"设置成功";

        } else {

            text = "\"" + tagName + "\"设置失败,错误码:" + errorCode;

        }

        Log.d(LogTag, text);

        show(context, text);


    }


    @Override

    public void onDeleteTagResult(Context context, int errorCode, String tagName) {

        if (context == null) {

            return;

        }

        String text = "";

        if (errorCode == XGPushBaseReceiver.SUCCESS) {

            text = "\"" + tagName + "\"删除成功";

        } else {

            text = "\"" + tagName + "\"删除失败,错误码:" + errorCode;

        }

        Log.d(LogTag, text);

        show(context, text);


    }


    // 通知点击回调 actionType=1为该消息被清除,actionType=0为该消息被点击

    @Override

    public void onNotifactionClickedResult(Context context,

                                           XGPushClickedResult message) {

        if (context == null || message == null) {

            return;

        }

        String text = "";

        if (message.getActionType() == XGPushClickedResult.NOTIFACTION_CLICKED_TYPE) {

            // 通知在通知栏被点击啦。。。。。

            // APP自己处理点击的相关动作

            // 这个动作可以在activity的onResume也能监听,请看第3点相关内容

            text = "通知被打开 :" + message;

        } else if (message.getActionType() == XGPushClickedResult.NOTIFACTION_DELETED_TYPE) {

            // 通知被清除啦。。。。

            // APP自己处理通知被清除后的相关动作

            text = "通知被清除 :" + message;

        }

//    Toast.makeText(context, "广播接收到通知被点击:" + message.toString(),

//          Toast.LENGTH_SHORT).show();

        // 获取自定义key-value

        String customContent = message.getCustomContent();

        if (customContent != null && customContent.length() != 0) {

            try {

                JSONObject obj = new JSONObject(customContent);

                // key1为前台配置的key

                if (!obj.isNull("key")) {

                    String value = obj.getString("key");

                    Log.d(LogTag, "get custom value:" + value);

                }

                // ...

            } catch (JSONException e) {

                e.printStackTrace();

            }

        }

        // APP自主处理的过程。。。

        Log.d(LogTag, text);

        show(context, text);

    }


    @Override

    public void onRegisterResult(Context context, int errorCode,

                                 XGPushRegisterResult message) {

        if (context == null || message == null) {

            return;

        }

        String text = "";

        if (errorCode == XGPushBaseReceiver.SUCCESS) {

            text = message + "注册成功";

            // 在这里拿token

            String token = message.getToken();

            // TOTO 把消息传给mainActivity

            Intent intent2 = new Intent();

            intent2.setAction(SysConfig.PUSH_MESSAGE_ACTION);

            intent2.putExtra("data", token); //这个data为你要传的数据

            intent2.putExtra("type", "1"); //这个data为你要传的数据

            context.sendBroadcast(intent2);

        } else {

            text = message + "注册失败,错误码:" + errorCode;

        }

        Log.d(LogTag, text);

        show(context, text);

    }


    // 消息透传

    @Override

    public void onTextMessage(Context context, XGPushTextMessage message) {

        String text = "收到消息:" + message.toString();

//    String notifyContent = "";

        // 获取自定义key-value

        String customContent = message.getCustomContent();

        if (customContent != null && customContent.length() != 0) {

            try {

                JSONObject obj = new JSONObject(customContent);

                // key1为前台配置的key

                if (!obj.isNull("notifyContent")) {

//             notifyContent = obj.getString("notifyContent");

                }


                // ...

            } catch (JSONException e) {

                e.printStackTrace();

            }

        }

        // APP自主处理消息的过程...

        Log.d(LogTag, text);

        show(context, text);


        // 把消息传给mainActivity

//    if (!isRunningForeground(context)) { //在后台运行时提示消息

        // 显示notification

        showNotification(context, message.getTitle(), message.getContent());

//    }


//    getTopActivityName(context);


        Intent intent2 = new Intent();

        intent2.setAction(SysConfig.PUSH_MESSAGE_ACTION);

        intent2.putExtra("data", customContent); //这个data为你要传的数据

        intent2.putExtra("type", "2"); //这个data为你要传的数据

        context.sendBroadcast(intent2);


    }


    public boolean isRunningForeground(Context context) {

        String packageName = getPackageName(context);

        String topActivityClassName = getTopActivityName(context);

        System.out.println("packageName=" + packageName + ",topActivityClassName=" + topActivityClassName);

        if (packageName != null && topActivityClassName != null && topActivityClassName.startsWith(packageName)) {

            System.out.println("---> isRunningForeGround");

            return true;

        } else {

            System.out.println("---> isRunningBackGround");

            return false;

        }


    }


    public String getTopActivityName(Context context) {

        String topActivityClassName = null;

        ActivityManager activityManager =

                (ActivityManager) (context.getSystemService(Context.ACTIVITY_SERVICE));

        List runningTaskInfos = activityManager.getRunningTasks(1);

        if (runningTaskInfos != null) {

            ComponentName f = runningTaskInfos.get(0).topActivity;

            topActivityClassName = f.getClassName();

        }

        return topActivityClassName;

    }


    public String getPackageName(Context context) {

        String packageName = context.getPackageName();

        return packageName;

    }


    int notifyID = 50000;


    /**

     * 显示通知

     */

    public void showNotification(Context context, String title, String content) {

        Notification mNotification;

//        Notification.Builder builder;

//        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        mNotification = new Notification(R.mipmap.ic_logo,content, System.currentTimeMillis());

        mNotification.flags = Notification.FLAG_AUTO_CANCEL;

//        // 将使用默认的声音来提醒用户

        mNotification.defaults = Notification.DEFAULT_SOUND;

//        Intent mIntent = new Intent(context, MainActivity.class);

//        // 这里需要设置Intent.FLAG_ACTIVITY_NEW_TASK属性

//        mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

//        PendingIntent mContentIntent = PendingIntent.getActivity(

//                context, 0, mIntent, 0);

//        // 这里必需要用setLatestEventInfo(上下文,标题,内容,PendingIntent)不然会报错.

        mNotification.setLatestEventInfo(context, title, content,

                mContentIntent);

//        builder = new Notification.Builder(context)

//                .setAutoCancel(true)

//                .setContentTitle(title)

//                .setContentText(content)

//                .setContentIntent(mContentIntent)

//                .setSmallIcon(R.mipmap.ic_logo)

//                .setWhen(System.currentTimeMillis())

//                .setDefaults(Notification.DEFAULT_SOUND)

//        ;

//        notifyID = notifyID + 1;

//        // 这里发送通知(消息ID,通知对象)

//        mNotificationManager.notify((int) System.currentTimeMillis(), builder.getNotification());


        //设置想要展示的数据内容

        Intent intent = new Intent(context, MainActivity.class);

        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pIntent = PendingIntent.getActivity(context,

                (int) SystemClock.uptimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);

        //----------------------------------------------------------------------------------------------

        int smallIcon = R.drawable.ic_logo;

        //int smallIcon = R.mipmap.logo;

        //--------------------------------------------------------------------------------------------------

        String ticker = "您有一条新通知";

        //实例化工具类,并且调用接口

        NotifyUtil notify = new NotifyUtil(context, 1);

        notify.notify_normal_singline(pIntent, smallIcon, ticker, title, content, true, true, false);

        // 清除消息

//        notify.clear();

    }

}

这样就ok了

你可能感兴趣的:(推送功能)