Android极光推送

本周是要做一个计步器一样的APP
但是原型图还没出来
就自己做了一个极光推送的项目,中间有好多bug,还有真机不显示问题。
下面贴代码

1.先进入极光推送的官方,申请一个账号,申请好账号:
点击进入服务中心

点击开发者平台

我使用的是旧版的
在这里插入图片描述
然后我们开始创建应用

在这里插入图片描述这里定义自己的应用名称和图标

下面我们创建好了自己的应用开始配置

在这里插入图片描述
然后我们点击完成推送设置

在这里插入图片描述
包名写你自己的包名 然后点击下载Demo

下载好这里我们极光配置的也差不多了
然后引进我们的项目中:

在这里插入图片描述
引入后配置一下然后将他的Manifest的东西配置进你的Manifest 注意可以去极光指南配置
剩下的我们就可以写程序了:
先看我的布局

在这里插入图片描述
布局没什么可看的因为推送主要是内部程序
先看MainActivity

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JPushInterface.init(getApplicationContext());
}
}

然后需要初始化一下MyAppaction

public class MyAppaction extends Application {

private static Context sContext;
@Override
public void onCreate() {
    super.onCreate();
    sContext = getApplicationContext();
    //TODO: 设置开启日志,发布时请关闭日志
    JPushInterface.setDebugMode(true);
    //初始化极光推送
    JPushInterface.init(this);
}
public static Context getsContext(){
    return sContext;
}

}

MyJPushMessageReceiver和PushService可以从我们引进来的项目中复制进我们的项目害怕有些新萌不懂我贴一下代码
PushService的代码

public class PushService extends JCommonService {

}

MyJPushMessageReceiver的代码

public class MyJPushMessageReceiver extends JPushMessageReceiver {

private static final String TAG = "MyJPushMessageReceiver";

/**
 * tag增删查改的操作会在此方法中回调结果
 */
@Override
public void onTagOperatorResult(Context context, JPushMessage jPushMessage) {
    super.onTagOperatorResult(context, jPushMessage);
    //下面2个回调类似
    Log.e(TAG, "onTagOperatorResult查询得到的别名:" + jPushMessage.getAlias());
    Log.e(TAG, "onTagOperatorResult查询得到的标签:" + jPushMessage.getTags());
    Log.e(TAG, "onTagOperatorResult错误码0为成功:" + jPushMessage.getErrorCode());
    Log.e(TAG, "onTagOperatorResult传入的标示:" + jPushMessage.getSequence());
}

/**
 * 查询某个tag与当前用户的绑定状态的操作会在此方法中回调结果
 */
@Override
public void onCheckTagOperatorResult(Context context, JPushMessage jPushMessage) {
    super.onCheckTagOperatorResult(context, jPushMessage);
    Log.e(TAG, "onCheckTagOperatorResult错误码0为成功: " + jPushMessage.getErrorCode());
}

/**
 * alias相关的操作会在此方法中回调结果
 */
@Override
public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
    super.onAliasOperatorResult(context, jPushMessage);
    Log.e(TAG, "onAliasOperatorResult错误码0为成功: " + jPushMessage.getErrorCode());
}

}

最后看一下推送的主要文件把
public class MyReceiver extends BroadcastReceiver {
private static final String TAG = “JIGUANG-Example”;
private static final String ACTION = “android.intent.action.BOOT_COMPLETED”;

@Override
public void onReceive(Context context, Intent intent) {
    try {
        Bundle bundle = intent.getExtras();
        Logger.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Logger.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Logger.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            //processCustomMessage(context, bundle);

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Logger.d(TAG, "[MyReceiver] 用户点击打开了通知");

            //打开自定义的Activity
            Intent i = new Intent(context, MainActivity.class);
            i.putExtras(bundle);
            //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(i);

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Logger.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的Activity, 打开一个网页等..

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Logger.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            Logger.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    } catch (Exception e) {
    }

    try {
        Bundle bundle = intent.getExtras();
        Log.e(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
        Intent pushintent = new Intent(context, PushService.class);//启动极光推送的服务
        context.startService(pushintent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Log.e(TAG, "8.0处理了");
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);//定义通知id
            String channelId = context.getPackageName();//通知渠道id
            String channelName = "消息通知";//"PUSH_NOTIFY_NAME";//通知渠道名
            int importance = NotificationManager.IMPORTANCE_HIGH;//通知级别
            NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);//
            channel.enableLights(true);//设置闪光灯
            channel.setLightColor(Color.RED);
            channel.enableVibration(true);//设置通知出现震动
            channel.setShowBadge(true);
            channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            notificationManager.createNotificationChannel(channel);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            Intent notificationIntent = new Intent(context, MainActivity.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            String message = bundle.getString(JPushInterface.EXTRA_ALERT);
            String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
            String s = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Intent intent0 = new Intent(context, MainActivity.class);
            PendingIntent pi = PendingIntent.getActivity(context, 0, intent0, PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentTitle(title)//设置通知栏标题
                    .setContentText(message)
                    .setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间
                    //.setSmallIcon(R.mipmap.new_app_icon)//设置通知小ICON
                    .setChannelId(channelId)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setContentIntent(pi);
            Notification notification = builder.build();
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            if (notificationManager != null) {
                notificationManager.notify(notificationId, notification);
            }
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            //跳转
            //打开自定义的Activity
            Intent i = new Intent(context, MainActivity.class);
            i.putExtras(bundle);
            //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(i);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(TAG, "极光推送出错:" + e.getMessage());
    }

}

// 打印所有的 intent extra 数据
private static String printBundle(Bundle bundle) {
    StringBuilder sb = new StringBuilder();
    for (String key : bundle.keySet()) {
        if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
            sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
        } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
            sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
        } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
            if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                Logger.i(TAG, "This message has no Extra data");
                continue;
            }

            try {
                JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                Iterator<String> it = json.keys();

                while (it.hasNext()) {
                    String myKey = it.next();
                    sb.append("\nkey:" + key + ", value: [" +
                            myKey + " - " + json.optString(myKey) + "]");
                }
            } catch (JSONException e) {
                Logger.e(TAG, "Get message extra JSON error!");
            }

        } else {
            sb.append("\nkey:" + key + ", value:" + bundle.get(key));
        }
    }
    return sb.toString();
}
}

这里我们运行一下手机

在这里插入图片描述
然后我们去极光推送中点击推送——发送通知

在这里插入图片描述
然后立即发送
这个时候我们的手机 上会出现
在这里插入图片描述

真机打包APK的时候记得把日志关闭

还有一个缺点就是真机后台清理后推送就不推送了
这个问题可能是因为手机不兼容 我还没找到办法。
切记一定要把 AndroidManifest配置好否则会出现问题的https://docs.jiguang.cn/jpush/client/Android/android_guide/这是配置Manifest

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值