App开发之实时推送组件

分析.png

集成就不说了,看官网就可以了https://docs.jiguang.cn/jpush/client/Android/android_guide/,或者点击下载demo,拷贝mainfest和相关的jni包

PushMessage

public class PushMessage implements Serializable{
    //消息类型,类型为2代表需要登录类型
    public String messageType = null;
    //连接,要打开的url地址
    public String messageUrl = null;
    //详情内容  要在消息推送页面显示的text
    public String messageContent = null;
}

JpushReceiver

public class JpushReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            //不需要跳转的action
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            //需要跳转的action
            //将消息封装成一个度机箱
            PushMessage message = (PushMessage) ResponseEntityToModule
                    .parseJsonToModule(bundle.getString(JPushInterface.EXTRA_EXTRA), PushMessage.class);
            if (Utils.getCurrentTask(context)) {
                Intent pushIntent = new Intent();
                pushIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //传实体对象
                pushIntent.putExtra("pushMessage", message);
                //代表应用已经启动
                if (message != null && message.messageType.equals("2")) {
                    //如果需要登录且当前没有登录
                    pushIntent.setClass(context,LoginActivity.class);
                    pushIntent.putExtra("fromPush",true);
                } else {
                    //用户已经登录或者不需要登录,直接跳转到消息展示页面
                    pushIntent.setClass(context, PushMessgeActivity.class);
                }
                context.startActivity(pushIntent);
            } else {
                //应用未启动
                Intent mainIntent = new Intent(context, HomeActivity.class);
                mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (message != null && message.messageType.equals("2")) {
                    //如果需要登录且当前没有登录
                    Intent loginIntent=new Intent(context,LoginActivity.class);
                    loginIntent.setClass(context,LoginActivity.class);
                    loginIntent.putExtra("fromPush",true);
                    loginIntent.putExtra("pushMessage",message);
                    //首先会进入loginActivity,退出后会进入HomeActivity
                    context.startActivities(new Intent[]{mainIntent,loginIntent});
                }else{
                    Intent pushIntent=new Intent(context,PushMessgeActivity.class);
                    pushIntent.putExtra("pushMessage",message);
                    context.startActivities(new Intent[]{mainIntent,pushIntent});
                }
            }
        }
    }
}

PushMessgeActivity

public class PushMessgeActivity extends BaseActivity {
    /**
     * UI
     */
    private TextView mTypeView;
    private TextView mTypeValueView;
    private TextView mContentView;
    private TextView mContentValueView;
    /**
     * data
     */
    private PushMessage mPushMessage;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jpush_layout);
        initData();
        initView();
    }

    private void initData() {
        Intent intent = getIntent();
        mPushMessage = (PushMessage) intent.getSerializableExtra("pushMessage");

    }

    private void initView() {
        mTypeView = (TextView) findViewById(R.id.message_type_view);
        mTypeValueView = (TextView) findViewById(R.id.message_type_value_view);
        mContentView = (TextView) findViewById(R.id.message_content_view);
        mContentValueView = (TextView) findViewById(R.id.message_content_value_view);

        mTypeValueView.setText(mPushMessage.messageType);
        mContentValueView.setText(mPushMessage.messageContent);
        if (!TextUtils.isEmpty(mPushMessage.messageUrl)) {
            //跳转到web页面
            //gotoWebView();
        }
    }
}

LoginActivity

private void initData() {
        Intent intent = getIntent();
        if (intent.hasExtra("pushMessage")) {
            mPushMessage = (PushMessage) getIntent().getSerializableExtra("pushMessage");
        }
        fromPush = intent.getBooleanExtra("fromPush", false);
    }
 //登录成功后到我们推送的页面
        if (fromPush) {
            Intent intent = new Intent(LoginActivity.this, PushMessgeActivity.class);
            intent.putExtra("pushMessage", mPushMessage);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

        }

Utils判断是否正在运行

public class Utils {
    /**
     * 这个是真正的获取指定的包名的应用程序是否在运行(无论前台还是后台)
     */
    public static boolean getCurrentTask(Context context) {
        ActivityManager activityManager = (ActivityManager)
                context.getSystemService(Context.ACTIVITY_SERVICE);
        List appProcessInfos = activityManager.getRunningTasks(Integer.MAX_VALUE);
        for (ActivityManager.RunningTaskInfo process : appProcessInfos) {
            if (process.baseActivity.getPackageName().equals(context.getPackageName())
                    || process.topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }
}

ResponseEntityToModule对象封装类

public class ResponseEntityToModule {
    public static Object parseJsonToModule(String jsonContent, Class clazz) {
        Object moduleObj = null;
        try {
            JSONObject jsonObj = new JSONObject(jsonContent);
            moduleObj = parseJsonObjectToModule(jsonObj, clazz);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return moduleObj;
    }

    public static Object parseJsonObjectToModule(JSONObject jsonObj, Class clazz) {
        Object moduleObj = null;
        try {
            moduleObj = (Object) clazz.newInstance();
            setFieldValue(moduleObj, jsonObj, clazz);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return moduleObj;
    }


    private static void setFieldValue(Object moduleObj, JSONObject jsonObj, Class clazz)
            throws IllegalArgumentException, IllegalAccessException, JSONException, InstantiationException {
        if (clazz.getSuperclass() != null) {
            setFieldValue(moduleObj, jsonObj, clazz.getSuperclass());
        }
        Field[] fields = clazz.getDeclaredFields();
        Class cls;
        String name;
        for (Field f : fields) {
            f.setAccessible(true);
            cls = f.getType();
            name = f.getName();
            if (!jsonObj.has(name) || jsonObj.isNull(name)) {
                continue;
            }
            if (cls.isPrimitive() || isWrappedPrimitive(cls))
            {
                setPrimitiveFieldValue(f, moduleObj, jsonObj.get(name));
            } else {
                if (cls.isAssignableFrom(String.class)) {
                    f.set(moduleObj, String.valueOf(jsonObj.get(name)));
                } else if (cls.isAssignableFrom(ArrayList.class)) {
                    parseJsonArrayToList(f, name, moduleObj, jsonObj);
                } else {
                    Object obj = parseJsonObjectToModule(jsonObj.getJSONObject(name), cls.newInstance().getClass());
                    f.set(moduleObj, obj);
                }
            }
        }
    }

    private static ArrayList parseJsonArrayToList(Field field, String fieldName, Object moduleObj,
                                                          JSONObject jsonObj) throws JSONException, IllegalArgumentException, IllegalAccessException {
        ArrayList objList = new ArrayList();
        Type fc = field.getGenericType();
        if (fc instanceof ParameterizedType)
        {
            ParameterizedType pt = (ParameterizedType) fc;
            if (pt.getActualTypeArguments()[0] instanceof Class)
            {
                Class clss = (Class) pt.getActualTypeArguments()[0];

                if (jsonObj.get(fieldName) instanceof JSONArray) {
                    JSONArray array = jsonObj.getJSONArray(fieldName);
                    for (int i = 0; i < array.length(); i++) {
                        if (array.get(i) instanceof JSONObject) {
                            objList.add(parseJsonObjectToModule(array.getJSONObject(i), clss));
                        } else {
                            if (clss.isAssignableFrom(array.get(i).getClass())) {
                                objList.add(array.get(i));
                            }
                        }
                    }
                }
                field.set(moduleObj, objList);
            }
        }
        return objList;
    }

    private static void setPrimitiveFieldValue(Field field, Object moduleObj, Object jsonObj)
            throws IllegalArgumentException, IllegalAccessException {
        if (field.getType().isAssignableFrom(jsonObj.getClass())) {
            field.set(moduleObj, jsonObj);
        } else {
            field.set(moduleObj, makeTypeSafeValue(field.getType(), jsonObj.toString()));

        }
    }

    private static final Object makeTypeSafeValue(Class type, String value) throws NumberFormatException,
            IllegalArgumentException {
        if (int.class == type || Integer.class == type) {
            return Integer.parseInt(value);
        } else if (long.class == type || Long.class == type) {
            return Long.parseLong(value);
        } else if (short.class == type || Short.class == type) {
            return Short.parseShort(value);
        } else if (char.class == type || Character.class == type) {
            return value.charAt(0);
        } else if (byte.class == type || Byte.class == type) {
            return Byte.valueOf(value);
        } else if (float.class == type || Float.class == type) {
            return Float.parseFloat(value);
        } else if (double.class == type || Double.class == type) {
            return Double.parseDouble(value);
        } else if (boolean.class == type || Boolean.class == type) {
            return Boolean.valueOf(value);
        } else {
            return value;
        }
    }

    private static boolean isWrappedPrimitive(Class type) {
        if (type.getName().equals(Boolean.class.getName()) || type.getName().equals(Byte.class.getName())
                || type.getName().equals(Character.class.getName()) || type.getName().equals(Short.class.getName())
                || type.getName().equals(Integer.class.getName()) || type.getName().equals(Long.class.getName())
                || type.getName().equals(Float.class.getName()) || type.getName().equals(Double.class.getName())) {
            return true;
        }
        return false;
    }
}

 

                            
                        
                    
                    
                    

你可能感兴趣的:(App开发之实时推送组件)