Activity小技巧

随时随地退出程序

  新建一个结合类对所有活动进行管理。

 1 public class ActivityCollector{
 2     public static List<Activity> activities = new ArrayList<>();
 3     public static void addActivity(Activity activity){
 4         activities.add(activity);
 5     }
 6     public static void removeActivity(Acitivity activity){
 7         activities.remove(acitivity);
 8     }
 9     public static void finishAll(){
10         for(Activity activity: activities){
11             if(!activity.isFinishing()){
12                 activity.finish();
13             }
14         }
15     }
16 }

 

启动活动技巧

  在SecondActivity中添加一个actionStrat()

1 public class SecondActivity extends BaseActivity{
2     public static void actionStart(Context context,String data1,String data2){
3         Intent intent = new Intent(context,SecondActivity.class);
4         intent.putExtra("param1","data1");
5         intent.putExtra("param2","data2");
6         context.startActivity(intent);
7     }
8 ......
9 }

  启动SecondActivity

public void onClick(View v){
    SecondActivity.actionStart(FirstAcitivity.this,"data1","data2");
}

   杀死整个App

/** 
 * 退出应用程序 
 */  
public void AppExit(Context context) {  
    try {  
        ActivityCollector.finishAll();  
        ActivityManager activityMgr = (ActivityManager) context  
                .getSystemService(Context.ACTIVITY_SERVICE);  
        activityMgr.killBackgroundProcesses(context.getPackageName());  
        System.exit(0);  
    } catch (Exception ignored) {}  
}  

  双击退出程序两个方法:

  1)定义一个变量,来标识是否退出

// 定义一个变量,来标识是否退出
private static boolean isExit = false;
Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        isExit = false;
    }
};

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            exit(this);
        }
        return false;
    }
return super.onKeyDown(keyCode, event);}

  2)保存点击时间:

/保存点击的时间
private long exitTime = 0;
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
                        exit();
                      }
        return false;
    }
        return super.onKeyDown(keyCode, event);
}

 

posted @ 2017-02-09 11:40  yl007  阅读(213)  评论(0编辑  收藏  举报