您的位置:首页 > 移动开发 > Android开发

android 在锁频界面直接打开自己的应用

2016-04-05 14:04 417 查看
用到WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED,使在锁屏界面就能打开自己的应用,在onCreat中添加:

Window win = getWindow();
           WindowManager.LayoutParams params =win.getAttributes();
           params.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                  | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                  | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                  | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
          win.setAttributes(params);

 

在用的过程中,一切都很顺利,不过在一个singletask模式的Activity出现了问题.当跳转到singletask模式的Activity时,会先闪烁显示锁屏界面,然后跳转到该界面,这是什么原因?

 

分析原因:

Singletask的Activity会启动一个新的任务栈,而原先的任务栈就会退出,而新启动的任务栈上只有一个设置为singletask的Activity,这个时候,该activity还没有显示出来,就会先显示锁屏界面了.

问题解决:

如果要解决此问题,而且还要保证该activity只有一个实例,那么要怎么做?

查看Activity有4种启动模式:standard、singletask、singletop、singleinstance

其中singletop模式为:如果当前任务栈顶为该activity,则启用当前的任务栈顶的实例,执行onNewIntent()方法,如果没有就重新实例化一个。

了解到intent中有一个这样的flag:Intent.FLAG_ACTIVITY_CLEAR_TOP,介绍文档是这样说的:

If set, and the activity beinglaunched is already running in the current task, then instead of launching anew instance of that activity, all of the other activities on top of it will beclosed and this Intent will be delivered to the (now on top) old activity
as anew Intent.

For example, consider a taskconsisting of the activities: A, B, C, D. If D calls startActivity() with anIntent that resolves to the component of activity B, then C and D will befinished and B receive the given Intent, resulting in the stack now being: A,B.

大概的意思就是:在启动对应activity的时候清除当前任务栈顶的实例,如果任务栈中有此类型的实例,结束此实例,并且重新实例化一个。

 结合singletop模式和Intent.FLAG_ACTIVITY_CLEAR_TOP,在启动Activity的intent中添加flag:Intent.FLAG_ACTIVITY_CLEAR_TOP,也就相当于实现了singletask的模式,替换使用此模式,解决该问题

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息