End

Activity 基础 管理器 生命周期

本文地址


目录

Activity 基础 管理器 生命周期

应用进入前后台判断

getApplication().registerActivityLifecycleCallbacks(new SampleActivityLifecycleCallbacks() {
    private int mFinalCount;

    @Override
    public void onActivityStarted(Activity activity) {
        super.onActivityStarted(activity);
        mFinalCount++;
        if (mFinalCount == 1){
            //如果mFinalCount ==1,说明是从后台到前台
        }
    }

    @Override
    public void onActivityStopped(Activity activity) {
        super.onActivityStopped(activity);
        mFinalCount--;
        if (mFinalCount == 0){
            //如果mFinalCount ==0,说明是前台到后台
        }
    }
}

获取自己App中的所有Activity

try {
    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES);
    for (ActivityInfo activity : packageInfo.activities) {
        Log.i("bqt", activity.name); //com.bqt.test.MainActivity
    }
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

获取栈顶和栈底的Activity

ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> list = manager.getRunningTasks(Integer.MAX_VALUE);
for (ActivityManager.RunningTaskInfo info : list) {
    Log.i("bqt", info.topActivity.getClassName() + "---" + info.baseActivity.getClassName());
}

Activity管理器

ActivityStackManager

定义一个集合(Stack)保存所有还未销毁的 Activity

public class ActivityStackManager {
    private Stack<ActivityInfo> activityStack;
    
    private static ActivityStackManager instance = new ActivityStackManager();
    
    private ActivityStackManager() {//构造方法私有
    }
    
    public static ActivityStackManager getInstance() {
        return instance;
    }
    
    //入栈
    public void push(Activity activity) {
        if (activityStack == null) activityStack = new Stack<>();
        
        for (int i = 0; i < activityStack.size(); i++) {
            if (activity == activityStack.get(i).activity) return;
        }
        activityStack.add(ActivityInfo.newBuilder()
                .activity(activity)
                .startTime(System.currentTimeMillis())
                .build());
    }
    
    //出栈
    public void pop(Activity activity) {
        if (activityStack != null && activityStack.size() > 0 && activity != null) {
            activity.finish();
            activityStack.remove(new ActivityInfo(activity));
        }
    }
    
    //第一种方式
    public ActivityInfo getActivityInfo(Activity activity) {
        ActivityInfo activityInfo = null;
        if (activityStack != null && activityStack.size() > 0) {
            for (ActivityInfo info : activityStack) {
                if (info.activity == activity) {
                    activityInfo = info;
                    break;
                }
            }
        }
        return activityInfo;
    }
    
    //第二种方式,不建议采用这种方式,因为在使用中发现可能会报数组越界异常
    //原因可能是当我通过search查找到之后和通过get获取之前这段时间,某个Activity被移除掉了,所以导致数组大小改变,取值时就可能越界了
    public ActivityInfo getActivityInfo2(Activity activity) {
        ActivityInfo activityInfo = null;
        if (activityStack != null && activityStack.size() > 0) {
            int index = activityStack.search(new ActivityInfo(activity));
            if (index >= 0) {
                activityInfo = activityStack.get(index);
            }
        }
        return activityInfo;
    }
    
    public long getStartTime(Activity activity) {
        ActivityInfo activityInfo = getActivityInfo(activity);
        return activityInfo != null ? activityInfo.startTime : 0;
    }
}

registerActivityLifecycleCallbacks

注册 Activity 生命周期回调

registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
   @Override
   public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
      ActivityStackManager.getInstance().push(activity);
   }
   
   @Override
   public void onActivityDestroyed(Activity activity) {
      long time = ActivityStackManager.getInstance().getStartTime(activity);
      String date = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss SSS", Locale.getDefault()).format(new Date(time));
      Log.i("bqt", "【" + activity.getClass().getSimpleName() + "启动时间】" + date);
      ActivityStackManager.getInstance().pop(activity);//必须放在获取消息后面,否则一经清空了就获取不到了
   }
   
   @Override
   public void onActivityStarted(Activity activity) {
   }
   
   @Override
   public void onActivityResumed(Activity activity) {
       Log.i("bqt", "当前Activity" + "(" + activity.getClass().getSimpleName()+".java" + ":" +30 + ")");
   }
   
   @Override
   public void onActivityPaused(Activity activity) {
   }
   
   @Override
   public void onActivityStopped(Activity activity) {
   }
   
   @Override
   public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
   }
});

ActivityInfo

保存与Activity相关的一些信息

//用于保存Activity示例以及与Activity相关的一些信息,比如Activity启动时间等
public class ActivityInfo {
    public Activity activity;
    public long startTime;
    
    public ActivityInfo(Activity activity) {
        this.activity = activity;
    }
    
    @Override
    public boolean equals(Object obj) {//必须重写equals方法
        return obj instanceof ActivityInfo && ((ActivityInfo) obj).activity.equals(activity);
    }
    
    //省略Builder代码
}

一个通用的AppManager

/**
 * activity堆栈式管理
 */
public class AppManager {
    private static Stack<Activity> activityStack;
    private static AppManager instance;
    
    private AppManager() {
    }

    public static AppManager getAppManager() {
        if (instance == null) {
            instance = new AppManager();
        }
        return instance;
    }
    
    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<>();
        }
        activityStack.add(activity);
    }
    
    /**
     * 获取当前Activity(堆栈中最后一个压入的)
     */
    public Activity currentActivity() {
        return activityStack.lastElement();
    }
    
    /**
     * 结束当前Activity(堆栈中最后一个压入的)
     */
    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }
    
    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null && !activity.isFinishing()) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }
    
    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
                break;
            }
        }
    }
    
    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                finishActivity(activityStack.get(i));
                break;
            }
        }
        activityStack.clear();
    }
    
    /**
     * 获取指定的Activity
     */
    public static Activity getActivity(Class<?> cls) {
        if (activityStack != null)
            for (Activity activity : activityStack) {
                if (activity.getClass().equals(cls)) {
                    return activity;
                }
            }
        return null;
    }
    
    public static Stack<Activity> getActivitys() {
        return activityStack;
    }
    
    /**
     * 退出应用程序
     */
    public void AppExit(Context context) {
        try {
            finishAllActivity();
            android.os.Process.killProcess(android.os.Process.myPid());// 杀死该应用进程
            System.exit(0);
        } catch (Exception ignored) {
        }
    }
    
    /**
     * 返回当前Activity栈中Activity的数量
     */
    public int getActivityCount() {
        int count = activityStack.size();
        return count;
    }
    
    /**
     * 堆栈中移除Activity
     */
    public void removeActivity(Activity activity) {
        if (activityStack == null) {
            return;
        } else if (activityStack.contains(activity)) {
            activityStack.remove(activity);
        }
        if (activity != null && !activity.isFinishing()) {
            activity.finish();
            activity = null;
        }
    }
}

零碎知识点

启动Activit

public static void launche(Context ctx) {
   Intent intent = new Intent(ctx, TestActivity.class);
   intent.putExtra("", "");
   ctx.startActivity(intent);
}

启动并返回数据

public static void launche(Activity ctx, int requestCode) {
   Intent intent = new Intent(ctx,TestActivity.class);
   intent.putExtra("", "");
   ctx.startActivityForResult(intent, requestCode);
}
@Override
public void finish() {
   Intent intent = new Intent();
   intent.putExtra("", "");
   setResult(RESULT_OK, intent);
   super.finish();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if (resultCode == RESULT_OK && requestCode == 123 && data != null) {
      aaa = data.getParcelableArrayListExtra("aaa");
   }
}

启动其他应用的Activity

Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, "com.bqt.test.MainActivity"));//需要提供包名和Activity完整类名
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//intent.setAction("android.intent.action.MAIN");
context.startActivity(intent);

同时启动多个Activity

Intent second = new Intent(this,SecondActivity.class); //先启动SecondActivity
Intent third = new Intent(this,ThirdActivity.class); //再启动ThirdActivity
startActivities(new Intent[]{second,third}); 

等价于

startActivity(new Intent(this, SecondActivity.class)); //先启动SecondActivity
startActivity(new Intent(this, ThirdActivity.class)); //再启动ThirdActivity

我们先启动的是SecondActivity,然后启动ThirdActivity
但是实际上用户只看到启动了ThirdActivity,ThirdActivity返回时用户会看的SecondActivity

重新启动一个Activity

第一种方式,调用 recreate() 方法,会自动走一遍Activity的生命周期
第二种方式,先调用 Activity 的 finish() 方法,再启动【startActivity(activity.getIntent())】

按返回键让Frag回退到上一个网页

Activity

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
   if (keyCode == KeyEvent.KEYCODE_BACK && fragment != null) {
      return fragment.goBack() || super.onKeyDown(keyCode, event);
   }
   return super.onKeyDown(keyCode, event);
}

Fragment

private String preUrl;//防止网页挂掉时一直返回不了的问题
public boolean goBack() {
   if (mWebView.canGoBack() && !mWebView.getUrl().equals(preUrl)) {//防止网页挂掉时一直返回不了的问题
      preUrl = mWebView.getUrl();
      mWebView.goBack();
      return true;
   }
   return false;
}

再按一次返回键退出

private long currentBackPressedTime = 0;
/**
 * 退出间隔
 */
public static final int BACK_PRESSED_INTERVAL = 2000;

@Override
public void onBackPressed() {
   if (System.currentTimeMillis() - currentBackPressedTime > BACK_PRESSED_INTERVAL) {
      currentBackPressedTime = System.currentTimeMillis();
      Toast.makeText(this, "再按一次返回键退出", Toast.LENGTH_SHORT).show();
   } else {
      finish();
   }
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
   if (keyCode == KeyEvent.KEYCODE_BACK) { //onKeyDown的优先级比onBackPressed高
      onBackPressed();
      return true;//消耗掉此事件
   } else {
      return super.onKeyDown(keyCode, event);
   }
}

防止短时间内按钮被快速点击

方式一,放在BaseActivity中统一处理:

private long lastClickTime;

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        if (isFastDoubleClick()) {
            return true;//消耗掉 ACTION_DOWN 事件
        }
    }
    return super.dispatchTouchEvent(ev);
}

public boolean isFastDoubleClick() {
    long timeD = System.currentTimeMillis() - lastClickTime;
    lastClickTime = System.currentTimeMillis();
    return timeD <= 500;
}

方式二,工具类判断:

public class FastClickUtils {
    private static final int MIN_DELAY_TIME = 1000;  // 两次点击间隔不能少于1000ms
    private static long lastClickTime;
    
    public static boolean isFastClick() {
        return isFastClick(MIN_DELAY_TIME);
    }
    
    public static boolean isFastClick(long delayTime) {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if (currentClickTime - lastClickTime >= delayTime) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }
}

ListActivity模板代码

public class MainActivity extends ListActivity {
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] array = {"",
            "",
            "",
            "",};
        setListAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, array));
        
        array[0] = getListView().getParent().getClass().getName(); //FrameLayout,所以不要在Parent中addView
        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.drawable.icon);
        getListView().addFooterView(imageView);
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        switch (position) {
            case 0:
                
                break;
            case 1:
                
                break;
            case 2:
                
                break;
        }
    }
}

2018-5-30

posted @ 2018-05-30 18:33  白乾涛  阅读(898)  评论(0编辑  收藏  举报