搞了好多天的android apk自动更新,终于有点结果了。现说下怎么获取activity栈里的activty信息
//get some activity information from stack
ActivityManager manager = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(5);
if (runningTaskInfos != null) {
if(runningTaskInfos.get(0)!=null){
ComponentName cn = runningTaskInfos.get(0).baseActivity;
if(cn!=null){
Log.d(TAG, "pkg:" + cn.getPackageName());
Log.d(TAG, "cls:" + cn.getClassName());
}
Log.d(TAG, "running activity number is "+runningTaskInfos.get(0).numActivities);
}
}
需要添加权限
<uses-permission android:name="android.permission.GET_TASKS"/>
如果自动更新自己的app, install之后会发现栈底元素是
PackageName com.android.packageinstaller
ClassName com.android.packageinstaller.InstallAppProgress
如果在launch activity 的oncreate里面有如下代码
if (!isTaskRoot()) {
final Intent intent = getIntent();
final String intentAction = intent.getAction();
if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) &&
intentAction != null && intentAction.equals(Intent.ACTION_MAIN)) {
Log.d(TAG,"Main Activity is not the root. Finishing Main Activity instead of launching.");
finish();
}
}
那么在install新app之后是进到finish()的判断条件的, 这样导致app重装后不能重启。需要进一步添加判断。
附上app自动更新的实现:
//存储到外部download文件夹
String downloadedFilepath=new StringBuffer().append(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)).toString();
//启动install
String apkPath=downloadedFilepath+apkName;
Uri data = Uri.parse("file://"+apkPath);
intent.setDataAndType(data, "application/vnd.android.package-archive");
startActivity(intent);
//为了使package installer上面有"打开"按钮,需要先把所有acitivty清掉
//此处代码省略,大致是使用在 application里面创建的HashMap<String, Activity> map集合,然后获取每个activity,调用finish()方法。
需要用到的权限:
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />