Android实现点击通知栏后,先启动应用再打开目标Activity

情况简述

  1. app正在运行
  2. app已退出

方案和思路

  1. SplashActivity 用于显示app大图,同时进行用户登录等操作,服务器返回数据后跳转到MainActivity。

  2. MainActivity app的主Activity。

  3. DetailActivity MainActivity中点击Button进入的Activity,用于显示某件商品详情。

  4. 点击通知栏通知,假如app正在运行,则直接跳转到DetailActivity显示具体内容,在DetailActivity中按Back键返回MainActivity

  5. 点击通知栏通知,假如app已经退出,先从SplashActivity进入,显示app启动界面,初始化操作完成后进入MainActivity再跳转到DetailActivity显示具体内容,在DetailActivity中按Back键返回MainActivity。

代码实现

  1. PushService,在新进程中启动的Service,负责监听服务器,收到服务器的信息后将消息广播出去,在本demo中,为了简化,只是简单的广播一个消息
  2. ShowNotificationReceiver,在新进程中注册的BroadcastReceiver,收到PushService发的消息后,会在通知栏弹出通知
  3. NotificationReceiver, 在新进程中注册的BroadcastReceiver,用来设置点击通知栏通知的动作,打开app中的某个Activity
  4. SplashActivity, app启动页面,先是启动图片,3s后进入MainActivity
  5. MainActivity,app的主Activity
  6. DetailActivity,app中显示详情的Activity

PushService.java


PushService的工作很简单,启动后发一个广播在通知栏显示通知,然后常驻在后台

public class PushService extends Service{
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
 
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("PushService", "PushService onCreate");
        //用AlarmManager定时发送广播
        AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
 
        Intent intent = new Intent(this, ShowNotificationReceiver.class);
 
        PendingIntent pendingIntent =
                PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
 
        am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.currentThreadTimeMillis(), pendingIntent);
 
    }
 }

ShowNotificationReceiver.java

这个广播类用来在通知栏弹出通知

public class ShowNotificationReceiver extends BroadcastReceiver{
    private static final String TAG = "RepeatReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "ShowNotificationReceiver onReceive");
        //设置点击通知栏的动作为启动另外一个广播
        Intent broadcastIntent = new Intent(context, NotificationReceiver.class);
        PendingIntent pendingIntent = PendingIntent.
                getBroadcast(context, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
 
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setContentTitle("这就是通知的头")
                .setTicker("这是通知的ticker")
                .setContentIntent(pendingIntent)
                .setSmallIcon(android.R.drawable.ic_lock_idle_charging);
 
        Log.i("repeat", "showNotification");
        NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(2, builder.build());
    }
}

NotificationReceiver.java

点击通知栏后,会发送一个广播,NotificationReceiver收到该广播后,就会判断,app进程是否仍然存活,根据app进程的不同状态,定义不同的app启动方式

public class NotificationReceiver extends BroadcastReceiver{
 
    @Override
    public void onReceive(Context context, Intent intent) {
        int isAppRuning = isAppAlive(context, "com.rangeidc.android.alarm");
        if (isAppRuning != 0) {
            Log.i("NotificationReceiver", "the app process is alive");
            int noType = pushNotifyBean.getNoType();
            Bundle bundle = new Bundle();
            if (noType == 1) {
                long day = pushNotifyBean.getDay();
                int reportType = pushNotifyBean.getReportType();
                String building = pushNotifyBean.getBuilding();
                Intent intent = new Intent(context, DailyShowActivity.class);
                bundle.putLong("time", day);
                bundle.putInt("type", reportType);
                bundle.putString("address", building);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent, bundle);
            } else if (noType == 0) {
                String evtLogId = pushNotifyBean.getEvtLogId();
                Intent intent = new Intent(context, NewIncidentDetailsActivity.class);
                bundle.putString("evtLogId", evtLogId);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent, bundle);
            }
            return;
        }
        // 如果app进程已经被杀死,先重新启动app,将DetailActivity的启动参数传入Intent中,参数经过
        // SplashActivity传入MainActivity,此时app的初始化已经完成,在MainActivity中就可以根据传入
        // 参数跳转到DetailActivity中去了
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage("com.rangeidc.android.alarm");
        // 设置flag
        launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        Bundle bundle = new Bundle();
        // 传递的数据
        bundle.putSerializable("pushNotifyDate", pushNotifyBean);
        // 设置跳转标志符
        launchIntent.putExtra(Constants.PREF_EXTRA, bundle);
        context.startActivity(launchIntent, bundle);
  }
 /**
     * 返回app运行状态
     *
     * @param context     一个context
     * @param packageName 要判断应用的包名
     * @return int 1:前台 2:后台 0:不存在
     */
    public static int isAppAlive(Context context, String packageName) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List listInfos = activityManager
                .getRunningTasks(20);
        // 判断程序是否在栈顶
        if (listInfos.get(0).topActivity.getPackageName().equals(packageName)) {
            return 1;
        } else {
            // 判断程序是否在栈里
            for (ActivityManager.RunningTaskInfo info : listInfos) {
                if (info.topActivity.getPackageName().equals(packageName)) {
                    return 2;
                }
            }
            return 0;// 栈里找不到,返回3
        }
    }
}

SplashActivity.java

SplashActivity.java先是app启动的图片,3s后进入MainActivity, 如果启动SplashActivity的Intent中带有参数,就将参数取出,放入启动MainActivity的Intent中

public class SplashActivity extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        //隐藏ActionBar
        getSupportActionBar().hide();
        //使用handler倒数3秒后进入MainActivity
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                //如果启动app的Intent中带有额外的参数,表明app是从点击通知栏的动作中启动的
                //将参数取出,传递到MainActivity中
                if(getIntent().getBundleExtra(Constants.PREF_EXTRA) != null){
                    intent.putExtra(Constants.PREF_EXTRA,
                            getIntent().getBundleExtra(Constants.PREF_EXTRA));
                }
                startActivity(intent);
                finish();
            }
        }, 3000);
    }
}

MainActivity.java

MainActivity中,如果有参数传入,就在初始化结束后,根据参数启动DetailActivity,如果没有参数传入,就此结束自己的任务

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Bundle extras = getIntent().getBundleExtra(Constants.PREF_EXTRA);
        // 点击通知栏传过来的启动页-->mainActivity-->指定跳转页
        if (extras != null) {
            PushNotifyBean pushNotifyBean = (PushNotifyBean) extras.getSerializable("pushNotifyDate");
            int noType = pushNotifyBean.getNoType();
            Log.i("Notification:点击通知栏进入主页", pushNotifyBean.toString() + noType);
            if (noType == 1) {
                long day = pushNotifyBean.getDay();
                int reportType = pushNotifyBean.getReportType();
                String building = pushNotifyBean.getBuilding();
                Intent intent = new Intent(mContext, DailyShowActivity.class);
                intent.putExtra("time", day);
                intent.putExtra("type", reportType);
                intent.putExtra("address", building);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            } else if (noType == 0) {
                String evtLogId = pushNotifyBean.getEvtLogId();
                Intent intent = new Intent(mContext, NewIncidentDetailsActivity.class);
                intent.putExtra("evtLogId", evtLogId);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
    }
}

DetailActivity.java

比较简单,显示传入的参数即可:-D

public class DetailActivity extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        
        Bundle bundle = getIntent().getExtras();
        String address = bundle.getString("address");
        Int type = bundle.getInt("type");
        long time = bundle.getLong("time");
 
        ...
    }
}

你可能感兴趣的:(Android实现点击通知栏后,先启动应用再打开目标Activity)