我们在使用支付宝的时候会发现,每次我们按下返回键或者home键回到桌面之后,再次打开此app时就会要求我们输入手势,正确输入后会回到我们退出app时的activity,这个效果该如何实现呢。。。
首先我们要为所有需要后台恢复前台启动手势解锁的activity写一个baseActivity,在这个baseActivity中,在说要重写那几个方法之前,先要做的是分析,activity的声明周期。。。当我们单击返回键的时候activity会执行 onpause->onstop->ondestory,重启应用会执行oncreate->onstart->onresume。当我们点击home键的时候会执行onPause->onStop,重启应用会执行onRestart->onstart->onresume,可以明确的是都会执行onstop方法、onstart方法、onPause方法以及onresume方法,这里就挑选onstop方法、onresume方法这两个方法进行重写,onstop方法中要做的事情是判断该app是否还在前台运行,并且用标志位记录已经在后台。在resume方法中判断标志位,如果已经在后台运行则先启动手势activity,否则不做任何操作。
BaseActivity的代码如下:
public class BaseActivity extends FragmentActivity { static boolean isActive = true; @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); if (!isAppOnFreground()) { Log.d("sqq", "back"); isActive = false; } } @Override protected void onResume() { super.onResume(); if (!isActive) { //从后台唤醒 isActive = true; Intent n = new Intent(this, LoginActivity.class); startActivity(n); finish(); } } /** * 是否在后台 * * @return */ public boolean isAppOnFreground() { ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE); String curPackageName = getApplicationContext().getPackageName(); List每次恢复前台需要验证手势的app = am.getRunningAppProcesses(); if (app == null) { return false; } for (ActivityManager.RunningAppProcessInfo a : app) { if (a.processName.equals(curPackageName) && a.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { return true; } } return false; /*ComponentName cn = am.getRunningTasks(1).get(0).topActivity; if(!TextUtils.isEmpty(curPackageName)&&curPackageName.equals(getPackageName())){ return true; } return false;*/ } /** * 检测手机是否屏幕是否关闭 */ private boolean isScreenOFF() { /**false 屏幕为关闭*/ boolean isScreenOff = false; /**true 屏幕关闭*/ PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); isScreenOff = pm.isScreenOn(); return !isScreenOff; } }
LoginActivity的实现如下:
public class LoginActivity extends Activity { private LocusPassWordView lpwv;//手势控件 private TextView tvtitle; private String password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); lpwv = (LocusPassWordView) this.findViewById(R.id.mLocusPassWordView); tvtitle=(TextView)findViewById(R.id.tv_locktitle); tvtitle.setText(R.string.str_lockpatterntitle); lpwv.setOnCompleteListener(new LocusPassWordView.OnCompleteListener() { @Override public void onComplete(String mPassword) { SharedPreferences settings = getSharedPreferences( "USERINFO", Context.MODE_WORLD_READABLE ); password=settings.getString("pattern_password", ""); if(password.equals(mPassword)) { Intent intent = new Intent(LoginActivity.this, SmartDoorMainActivity.class); startActivity(intent); LoginActivity.this.finish(); } else { tvtitle.setText(R.string.str_input_err); lpwv.clearPassword(); } } }); } }注意LoginActivity就是输入手势的页面。