Android推送 - Activity跳转控制处理

来源:互联网 发布:淘宝卖家发物流怎么办 编辑:程序博客网 时间:2024/06/07 09:18

功能需求:


// ============= 功能需求 =================// 1.当App在前台可见时,点击通知栏推送消息时,直接跳转到对应的页面(TipsActivity)// 2.当App在后台不可见时(未关闭),点击通知栏推送消息时,直接跳转到对应的页面(TipsActivity)// 3.当App关闭时,点击通知栏推送消息时,先显示欢迎页面,然后直接跳转到对应的页面(TipsActivity)(返回时回到首页,而非关闭App)// ==================// 按照该解决方法,搬运到自己项目中,就可以解决该问题// 如同微信,后台关闭了,则先显示欢迎页面,然后显示消息,返回则回到首页,未关闭则不打开欢迎页面

实现思路:


// ============= 处理的思路 =================// 首先创建BaseActivity类,是让全部Activity都继承该类,然后在onStart里面处理是否推送// 接着创建 PushHanderActivity类,中转处理推送消息,点击通知消息时都跳转到该类,该类通过Acitivyt Task处理App在前后台情况控制// ==// 1.当App关闭时,则会自动先打开WelComeActivity,然后触发onStart方法,因为欢迎页面还不需要进行跳转// 所以在PushHanderActivity 的isHandler方法过滤了需要不处理的类,然后在MainActivity的onStart里面触发推送消息,然后才跳转到TipsActivity// 2.当App在前台可见、后台不可见(未关闭)时,因为设置了addCategory,则不会再从WelComeActivity启动,而是直接触发onStart方法,就会进行判断是否跳转到TipsActivity// ==// 也预留了不同类型跳转到不同的页面,便于后台控制  PushHanderActivity - checkPush - switch(pushMsgVo.pmType)// --- 可能贴代码,比较难理解,最下面有代码链接// 处理判断的代码 onStart - PushHanderActivity.checkPush(claName, this);

实现代码:


package com.push.pro.activitys;import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle;import android.view.View;import android.widget.Button;import com.push.pro.BaseActivity;import com.push.pro.R;import com.push.pro.push.PushMsgVo;import com.push.pro.push.PushReceiver;import org.json.JSONObject;import java.util.Random;/** * 首页Activity */public class MainActivity extends BaseActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        // --        ((Button) this.findViewById(R.id.am_btn)).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Random random = new Random();                // --                PushMsgVo pushMsgVo = new PushMsgVo();                pushMsgVo.pmType = 2;                pushMsgVo.pmMsg = "推送消息 - " + System.currentTimeMillis() + " - " + random.nextInt(50);                pushMsgVo.pmTitle = "推送标题 - " + System.currentTimeMillis() + " - " + random.nextInt(50);                // ==                JSONObject jsonObj = new JSONObject();                try{                    jsonObj.put("type", pushMsgVo.pmType);                    jsonObj.put("msg", pushMsgVo.pmMsg);                    jsonObj.put("title", pushMsgVo.pmTitle);                } catch (Exception e){                }                // 发送广播                Intent intent = new Intent(mContext, PushReceiver.class);                Bundle bundle = new Bundle();                bundle.putString("pushMsg", jsonObj.toString());                intent.putExtras(bundle);                sendBroadcast(intent);            }        });        // ======= 注册广播 ========        // 注册监听广播        IntentFilter filter = new IntentFilter();        filter.addAction("com.push.pro.push.PushReceiver");        mContext.registerReceiver(new PushReceiver(), filter);    }}

-

package com.push.pro.activitys;import android.content.Intent;import android.os.Bundle;import android.widget.TextView;import com.push.pro.BaseActivity;import com.push.pro.R;import com.push.pro.push.PushMsgVo;public class TipsActivity extends BaseActivity {    /** 显示推送内容 */    private TextView am_tips_tv;    // === 其他对象 ===    public static final String PUSH_MSG_VO = "pushMsgVo";    /** 消息内容实体类 */    private PushMsgVo pushMsgVo;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_tips);        // --        am_tips_tv = (TextView) this.findViewById(R.id.am_tips_tv);        // 获取推送消息        Intent intent = getIntent();        if (intent != null && intent.hasExtra(PUSH_MSG_VO)){            try{                pushMsgVo = (PushMsgVo) intent.getSerializableExtra(PUSH_MSG_VO);            } catch (Exception e){                e.printStackTrace();            }        }        // --        if (pushMsgVo != null){            // 拼接消息内容            StringBuilder sBuilder = new StringBuilder();            sBuilder.append("\r\npmType: " + pushMsgVo.pmType);            sBuilder.append("\r\npmMsg: " + pushMsgVo.pmMsg);            sBuilder.append("\r\npmTitle: " + pushMsgVo.pmTitle);            // 显示消息内容            am_tips_tv.setText(sBuilder.toString());        }    }}

-

package com.push.pro.push;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import com.push.pro.R;public class PushReceiver extends BroadcastReceiver {    /** 日志Tag */    private final String TAG = "PushReceiver";    @Override    public void onReceive(Context mContext, Intent intent) {        // ==== 初始化通知管理类  ====        if(mNotificationManager == null){            mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);        }        // ========================        Bundle bundle = intent.getExtras();        if (bundle != null){            if (bundle.containsKey("pushMsg")){                // 获取推送消息                String pushMsg = bundle.getString("pushMsg");                // 显示通知                displayNotification(mContext, pushMsg);            }        }    }    /** 通知栏管理类 */    private static NotificationManager mNotificationManager = null;    /**     * 显示通知     * @param mContext 上下文     * @param pushMsg 推送的消息     */    public void displayNotification(Context mContext, String pushMsg) {        if(TextUtils.isEmpty(pushMsg)){            return;        }        // 解析数据        PushMsgVo pushMsgVo = PushMsgVo.analyPushMsgVoJson(pushMsg);        // 通知标题        String title = pushMsgVo.pmTitle;        // 通知内容        String content = pushMsgVo.pmMsg;        // 防止消息都为null        if(title == null || content == null){            return;        }        // ----        // 设置通知栏id        int notifyId = (int) System.currentTimeMillis();        // ======== 跳转到推送中转Activity ========        Intent intent = new Intent(mContext, PushHanderActivity.class);        intent.putExtra(PushHanderActivity.PUSH_MSG, pushMsg); // 设置推送消息        PendingIntent pIntent = PendingIntent.getActivity(mContext, notifyId, intent, PendingIntent.FLAG_UPDATE_CURRENT);//      // -- 初始化通知信息实体类 --//      Notification notification = new Notification();//      // 设置图标//      notification.icon = R.drawable.ic_launcher;//      // 设置标题//      notification.tickerText = title;//      // 设置时间//      notification.when = System.currentTimeMillis();//      // 设置消息提醒,震动 | 声音//      notification.defaults = Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND;//      /* 点击了此通知则取消该通知栏 *///      notification.flags |= Notification.FLAG_AUTO_CANCEL;//      /* 用上面的属性初始化 Nofification *///      notification.setLatestEventInfo(mContext, title, content, pIntent);//      /* 显示通知栏 *///      mNotificationManager.notify(notifyId, notification);        // ===        // 新建Notification.Builder对象        Notification.Builder builder = new Notification.Builder(mContext);        builder.setContentTitle(title); // 设置标题        builder.setContentText(content); // 设置内容        builder.setSmallIcon(R.mipmap.ic_launcher); // 设置图标        builder.setContentIntent(pIntent); // 执行intent        // 将builder对象转换为普通的notification        Notification notification = builder.getNotification();        // 设置图标        notification.icon = R.mipmap.ic_launcher;        // 设置标题        notification.tickerText = title;        // 设置时间        notification.when = System.currentTimeMillis();        // 设置消息提醒,震动 | 声音        notification.defaults = Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND;        /* 点击了此通知则取消该通知栏 */        notification.flags |= Notification.FLAG_AUTO_CANCEL;        /* 显示通知栏 */        mNotificationManager.notify(notifyId,notification);    }}

-

package com.push.pro.push;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import com.push.pro.activitys.TipsActivity;import com.push.pro.activitys.WelComeActivity;import com.push.pro.utils.SharePreferencesUtils;/** * 推送消息处理Activity - 不需要继承BaseActivity */public class PushHanderActivity extends Activity {    /** 推送消息Key */    public static final String PUSH_MSG = "pushMsg";    /** 判断是否点击了推送通知栏消息 */    public static final String IS_CLICK_PUSH_MSG = "isClickPushMsg";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // 进行处理点击通知栏推送消息        handlerPushOp(getIntent());    }    @Override    protected void onNewIntent(Intent intent) {        super.onNewIntent(intent);        // 进行处理点击通知栏推送消息        handlerPushOp(intent);    }    // =====================================================    /**     * 处理推送操作     * @param intent 获取传递的数据     */    private void handlerPushOp(Intent intent) {        // 推送数据        String pushData = null;        // 判读是否存在数据        if(intent != null && intent.hasExtra(PushHanderActivity.PUSH_MSG)){            try {                // 获取推送数据                pushData = intent.getStringExtra(PushHanderActivity.PUSH_MSG);            } catch (Exception e) {                e.printStackTrace();            }        }        // 判断是否存在推送数据        if(TextUtils.isEmpty(pushData)){            // 关闭当前页面            finish();            return;        }        // 保存状态 - 是否存在推送消息        SharePreferencesUtils.setBoolean(PushHanderActivity.this, PushHanderActivity.IS_CLICK_PUSH_MSG, true);        // 保存数据        SharePreferencesUtils.setString(PushHanderActivity.this, PushHanderActivity.PUSH_MSG, pushData);        // 关闭当前页面        finish();        // =================  进行跳转  =================        Intent pIntent = new Intent(Intent.ACTION_MAIN);        pIntent.addCategory(Intent.CATEGORY_LAUNCHER);        pIntent.setComponent(new ComponentName(PushHanderActivity.this.getPackageName(), WelComeActivity.class.getCanonicalName()));        pIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);        startActivity(pIntent);        // ============================================    }    /**     * 是否进行处理(判断类,防止都进行触发判断)     * @param claName 类名     */    private static boolean isHandler(String claName){        // 防止为null        if (TextUtils.isEmpty(claName)){            return false;        }        // ---        if(claName.equals(WelComeActivity.class.getSimpleName())){            return false; // 属于欢迎页面则不进行处理        } else if (claName.equals("GuideActivity")){            return false; // 属于引导页面则不进行处理        }        // 默认进行处理        return true;    }    /**     * 检查推送操作     * @param mContext 上下文     */    public static void checkPush(Context mContext){        if (mContext != null){            try {                // 判断是否点击推送消息 - 必须点击了才进行处理                if(SharePreferencesUtils.getBoolean(mContext, PushHanderActivity.IS_CLICK_PUSH_MSG, false)){                    // 清空状态                    SharePreferencesUtils.setBoolean(mContext, PushHanderActivity.IS_CLICK_PUSH_MSG, false);                    // 获取数据                    String msgData = SharePreferencesUtils.getString(mContext, PushHanderActivity.PUSH_MSG, null);                    // 如果为null,则重置                    if(TextUtils.isEmpty(msgData)){                        return;                    }                    // 清空数据                    SharePreferencesUtils.setString(mContext, PushHanderActivity.PUSH_MSG, null);                    // ====================== JSON解析数据处理需要操作的页面  ======================                    // 解析数据                    PushMsgVo pushMsgVo = PushMsgVo.analyPushMsgVoJson(msgData);                    // 判断类型,如果属于订阅消息(他人)                    switch(pushMsgVo.pmType){                        case 1:                            // mContext.startActivity(new Intent(mContext, Class.class));                            break;                        case 2:                            // 跳转页面 - 提示页面                            Intent intent = new Intent(mContext, TipsActivity.class);                            intent.putExtra(TipsActivity.PUSH_MSG_VO, pushMsgVo);                            mContext.startActivity(intent);                            break;                    }                }            } catch (Exception e) {                e.printStackTrace();            }        }    }    /**     * 检查推送     * @param claName 类名     * @param mContext 上下文     */    public static void checkPush(String claName, Context mContext){        if (isHandler(claName)){ // 进行过滤类,判断是否进行处理            checkPush(mContext);        }    }}

-

package com.push.pro.push;import org.json.JSONObject;import java.io.Serializable;/** * 推送消息实体类 */public class PushMsgVo implements Serializable{    /** 类型*/    public int pmType;    /** 消息 */    public String pmMsg;    /** 标题 */    public String pmTitle;    // =========================    /**     * 解析推送消息信息     * @param json     * @return     */    public static PushMsgVo analyPushMsgVoJson(String json){        try {            // 生成JSON对象            JSONObject jsonObj = new JSONObject(json);            // 初始化信息实体类            PushMsgVo pushMsgVo = new PushMsgVo();            /** 类型 */            pushMsgVo.pmType = jsonObj.getInt("type");            /** 消息 */            pushMsgVo.pmMsg = jsonObj.getString("msg");            /** 标题息 */            pushMsgVo.pmTitle = jsonObj.getString("title");            return pushMsgVo;        } catch (Exception e) {        }        return null;    }}

-

package com.push.pro;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.util.Log;import com.push.pro.push.PushHanderActivity;/** Activity 基类 */public class BaseActivity extends Activity {    /** 日志Tag */    private String TAG = "BaseActivity";    /** 上下文 */    protected Context mContext = null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        try {            // TAG = this.getClass().getName();            TAG = this.getClass().getSimpleName();        } catch (Exception e) {        }        mContext = this;        // 打印日志        printLog("onCreate");    }    @Override    protected void onStart() {        super.onStart();        printLog("onStart");    }    @Override    protected void onRestart() {        super.onRestart();        printLog("onRestart");    }    @Override    protected void onResume() {        super.onResume();        printLog("onResume");        // 获取类名        String claName = this.getClass().getSimpleName();        // 检查推送        PushHanderActivity.checkPush(claName, this);    }    @Override    protected void onPause() {        super.onPause();        printLog("onPause");    }    @Override    protected void onStop() {        super.onStop();        printLog("onStop");    }    @Override    protected void onDestroy() {        super.onDestroy();        printLog("onDestroy");    }    // =========================  其他自定义方法  =========================    /**     * 统一打印日志     * @param message 打印内容     */    private final void printLog(String message) {        Log.d(TAG, TAG + " -> " + message);    }}

代码下载


Android推送Activity跳转控制处理

0 0
原创粉丝点击