转载请注明出处:
之前有很多朋友都问过我,在Android系统中怎样才能实现静默安装呢?所谓的静默安装,就是不用弹出系统的安装界面,在不影响用户任何操作的情况下不知不觉地将程序装好。虽说这种方式看上去不打搅用户,但是却存在着一个问题,因为Android系统会在安装界面当中把程序所声明的权限展示给用户看,用户来评估一下这些权限然后决定是否要安装该程序,但如果使用了静默安装的方式,也就没有地方让用户看权限了,相当于用户被动接受了这些权限。在Android官方看来,这显示是一种非常危险的行为,因此静默安装这一行为系统是不会开放给开发者的。
但是总是弹出一个安装对话框确实是一种体验比较差的行为,这一点Google自己也意识到了,因此Android系统对自家的Google Play商店开放了静默安装权限,也就是说所有从Google Play上下载的应用都可以不用弹出安装对话框了。这一点充分说明了拥有权限的重要性,自家的系统想怎么改就怎么改。借鉴Google的做法,很多国内的手机厂商也采用了类似的处理方式,比如说小米手机在小米商店中下载应用也是不需要弹出安装对话框的,因为小米可以在MIUI中对Android系统进行各种定制。因此,如果我们只是做一个普通的应用,其实不太需要考虑静默安装这个功能,因为我们只需要将应用上架到相应的商店当中,就会自动拥有静默安装的功能。
但是如果我们想要做的也是一个类似于商店的平台呢?比如说像360手机助手,它广泛安装于各种各样的手机上,但都是作为一个普通的应用存在的,而没有Google或小米这样的特殊权限,那360手机助手应该怎样做到更好的安装体验呢?为此360手机助手提供了两种方案, 秒装(需ROOT权限)和智能安装,如下图示:
因此,今天我们就模仿一下360手机助手的实现方式,来给大家提供一套静默安装的解决方案。
一、秒装
所谓的秒装其实就是需要ROOT权限的静默安装,其实静默安装的原理很简单,就是调用Android系统的pm install命令就可以了,但关键的问题就在于,pm命令系统是不授予我们权限调用的,因此只能在拥有ROOT权限的手机上去申请权限才行。
下面我们开始动手,新建一个InstallTest项目,然后创建一个SilentInstall类作为静默安装功能的实现类,代码如下所示:
1. /**
2. * 静默安装的实现类,调用install()方法执行具体的静默安装逻辑。
3. * 原文地址:
4. * @author guolin
5. * @since 2015/12/7
6. */
7. public class SilentInstall {
8.
9. /**
10. * 执行具体的静默安装逻辑,需要手机ROOT。
11. * @param apkPath
12. * 要安装的apk文件的路径
13. * @return 安装成功返回true,安装失败返回false。
14. */
15. public boolean install(String apkPath) {
16. boolean result = false;
17. null;
18. null;
19. try {
20. // 申请su权限
21. "su");
22. new DataOutputStream(process.getOutputStream());
23. // 执行pm install命令
24. "pm install -r " + apkPath + "\n";
25. "utf-8")));
26. dataOutputStream.flush();
27. "exit\n");
28. dataOutputStream.flush();
29. process.waitFor();
30. new BufferedReader(new InputStreamReader(process.getErrorStream()));
31. "";
32. String line;
33. // 读取命令的执行结果
34. while ((line = errorStream.readLine()) != null) {
35. msg += line;
36. }
37. "TAG", "install msg is " + msg);
38. // 如果执行结果中包含Failure字样就认为是安装失败,否则就认为安装成功
39. if (!msg.contains("Failure")) {
40. true;
41. }
42. catch (Exception e) {
43. "TAG", e.getMessage(), e);
44. finally {
45. try {
46. if (dataOutputStream != null) {
47. dataOutputStream.close();
48. }
49. if (errorStream != null) {
50. errorStream.close();
51. }
52. catch (IOException e) {
53. "TAG", e.getMessage(), e);
54. }
55. }
56. return result;
57. }
58.
59. }
可以看到,SilentInstall类中只有一个install()方法,所有静默安装的逻辑都在这个方法中了,那么我们具体来看一下这个方法。首先在第21行调用了Runtime.getRuntime().exec("su")方法,在这里先申请ROOT权限,不然的话后面的操作都将失败。然后在第24行开始组装静默安装命令,命令的格式就是pm install -r <apk路径>,-r参数表示如果要安装的apk已经存在了就覆盖安装的意思,apk路径是作为方法参数传入的。接下来的几行就是执行上述命令的过程,注意安装这个过程是同步的,因此我们在下面调用了process.waitFor()方法,即安装要多久,我们就要在这里等多久。等待结束之后说明安装过程结束了,接下来我们要去读取安装的结果并进行解析,解析的逻辑也很简单,如果安装结果中包含Failure字样就说明安装失败,反之则说明安装成功。
整个方法还是非常简单易懂的,下面我们就来搭建调用这个方法的环境。修改activity_main.xml中的代码,如下所示:
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:orientation="vertical"
7. android:paddingBottom="@dimen/activity_vertical_margin"
8. android:paddingLeft="@dimen/activity_horizontal_margin"
9. android:paddingRight="@dimen/activity_horizontal_margin"
10. android:paddingTop="@dimen/activity_vertical_margin"
11. tools:context="com.example.installtest.MainActivity">
12.
13. <LinearLayout
14. android:layout_width="match_parent"
15. android:layout_height="wrap_content">
16.
17. <Button
18. android:layout_width="wrap_content"
19. android:layout_height="wrap_content"
20. android:onClick="onChooseApkFile"
21. android:text="选择安装包" />
22.
23. <TextView
24. android:id="@+id/apkPathText"
25. android:layout_width="0dp"
26. android:layout_height="wrap_content"
27. android:layout_weight="1"
28. android:layout_gravity="center_vertical"
29. />
30.
31. </LinearLayout>
32.
33.
34. <View
35. android:layout_width="match_parent"
36. android:layout_height="1dp"
37. android:background="@android:color/darker_gray" />
38.
39. <Button
40. android:layout_width="wrap_content"
41. android:layout_height="wrap_content"
42. android:onClick="onSilentInstall"
43. android:text="秒装" />
44.
45. <View
46. android:layout_width="match_parent"
47. android:layout_height="1dp"
48. android:background="@android:color/darker_gray" />
49.
50. <Button
51. android:layout_width="wrap_content"
52. android:layout_height="wrap_content"
53. android:onClick="onForwardToAccessibility"
54. android:text="开启智能安装服务" />
55.
56. <Button
57. android:layout_width="wrap_content"
58. android:layout_height="wrap_content"
59. android:onClick="onSmartInstall"
60. android:text="智能安装" />
61. </LinearLayout>
这里我们先将程序的主界面确定好,主界面上拥有四个按钮,第一个按钮用于选择apk文件的,第二个按钮用于开始秒装,第三个按钮用于开启智能安装服务,第四个按钮用于开始智能安装,这里我们暂时只能用到前两个按钮。那么调用SilentInstall的install()方法需要传入apk路径,因此我们需要先把文件选择器的功能实现好,新建activity_file_explorer.xml和list_item.xml作为文件选择器的布局文件,代码分别如下所示:
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:orientation="vertical"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent">
6.
7. <ListView
8. android:id="@+id/list_view"
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. />
12.
13. </LinearLayout>
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout
3. xmlns:android="http://schemas.android.com/apk/res/android"
4. android:layout_width="match_parent"
5. android:layout_height="wrap_content"
6. android:padding="4dp"
7. android:orientation="horizontal">
8.
9. <ImageView android:id="@+id/img"
10. android:layout_width="32dp"
11. android:layout_margin="4dp"
12. android:layout_gravity="center_vertical"
13. android:layout_height="32dp"/>
14.
15.
16. <TextView android:id="@+id/name"
17. android:textSize="18sp"
18. android:textStyle="bold"
19. android:layout_width="match_parent"
20. android:gravity="center_vertical"
21. android:layout_height="50dp"/>
22.
23. </LinearLayout>
然后新建FileExplorerActivity作为文件选择器的Activity,代码如下:
1. public class FileExplorerActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
2.
3. ListView listView;
4. SimpleAdapter adapter;
5. String rootPath = Environment.getExternalStorageDirectory().getPath();
6. String currentPath = rootPath;
7. new ArrayList<>();
8.
9. @Override
10. public void onCreate(Bundle savedInstanceState) {
11. super.onCreate(savedInstanceState);
12. setContentView(R.layout.activity_file_explorer);
13. listView = (ListView) findViewById(R.id.list_view);
14. new SimpleAdapter(this, list, R.layout.list_item,
15. new String[]{"name", "img"}, new int[]{R.id.name, R.id.img});
16. listView.setAdapter(adapter);
17. this);
18. refreshListItems(currentPath);
19. }
20.
21. private void refreshListItems(String path) {
22. setTitle(path);
23. new File(path).listFiles();
24. list.clear();
25. if (files != null) {
26. for (File file : files) {
27. new HashMap<>();
28. if (file.isDirectory()) {
29. "img", R.drawable.directory);
30. else {
31. "img", R.drawable.file_doc);
32. }
33. "name", file.getName());
34. "currentPath", file.getPath());
35. list.add(map);
36. }
37. }
38. adapter.notifyDataSetChanged();
39. }
40.
41. @Override
42. public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
43. "currentPath");
44. new File(currentPath);
45. if (file.isDirectory())
46. refreshListItems(currentPath);
47. else {
48. new Intent();
49. "apk_path", file.getPath());
50. setResult(RESULT_OK, intent);
51. finish();
52. }
53.
54. }
55.
56. @Override
57. public void onBackPressed() {
58. if (rootPath.equals(currentPath)) {
59. super.onBackPressed();
60. else {
61. new File(currentPath);
62. currentPath = file.getParentFile().getPath();
63. refreshListItems(currentPath);
64. }
65. }
66. }
这部分代码由于和我们本篇文件的主旨没什么关系,主要是为了方便demo展示的,因此我就不进行讲解了。
接下来修改MainActivity中的代码,如下所示:
1. /**
2. * 仿360手机助手秒装和智能安装功能的主Activity。
3. * 原文地址:
4. * @author guolin
5. * @since 2015/12/7
6. */
7. public class MainActivity extends AppCompatActivity {
8.
9. TextView apkPathText;
10.
11. String apkPath;
12.
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17. apkPathText = (TextView) findViewById(R.id.apkPathText);
18. }
19.
20. @Override
21. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
22. if (requestCode == 0 && resultCode == RESULT_OK) {
23. "apk_path");
24. apkPathText.setText(apkPath);
25. }
26. }
27.
28. public void onChooseApkFile(View view) {
29. new Intent(this, FileExplorerActivity.class);
30. 0);
31. }
32.
33. public void onSilentInstall(View view) {
34. if (!isRoot()) {
35. this, "没有ROOT权限,不能使用秒装", Toast.LENGTH_SHORT).show();
36. return;
37. }
38. if (TextUtils.isEmpty(apkPath)) {
39. this, "请选择安装包!", Toast.LENGTH_SHORT).show();
40. return;
41. }
42. final Button button = (Button) view;
43. "安装中");
44. new Thread(new Runnable() {
45. @Override
46. public void run() {
47. new SilentInstall();
48. final boolean result = installHelper.install(apkPath);
49. new Runnable() {
50. @Override
51. public void run() {
52. if (result) {
53. this, "安装成功!", Toast.LENGTH_SHORT).show();
54. else {
55. this, "安装失败!", Toast.LENGTH_SHORT).show();
56. }
57. "秒装");
58. }
59. });
60.
61. }
62. }).start();
63.
64. }
65.
66. public void onForwardToAccessibility(View view) {
67.
68. }
69.
70. public void onSmartInstall(View view) {
71.
72. }
73.
74. /**
75. * 判断手机是否拥有Root权限。
76. * @return 有root权限返回true,否则返回false。
77. */
78. public boolean isRoot() {
79. boolean bool = false;
80. try {
81. new File("/system/bin/su").exists() || new File("/system/xbin/su").exists();
82. catch (Exception e) {
83. e.printStackTrace();
84. }
85. return bool;
86. }
87.
88. }
可以看到,在MainActivity中,我们对四个按钮点击事件的回调方法都进行了定义,当点击选择安装包按钮时就会调用onChooseApkFile()方法,当点击秒装按钮时就会调用onSilentInstall()方法。在onChooseApkFile()方法方法中,我们通过Intent打开了FileExplorerActivity,然后在onActivityResult()方法当中读取选择的apk文件路径。在onSilentInstall()方法当中,先判断设备是否ROOT,如果没有ROOT就直接return,然后判断安装包是否已选择,如果没有也直接return。接下来我们开启了一个线程来调用SilentInstall.install()方法,因为安装过程会比较耗时,如果不开线程的话主线程就会被卡住,不管安装成功还是失败,最后都会使用Toast来进行提示。
代码就这么多,最后我们来配置一下AndroidManifest.xml文件:
1. <?xml version="1.0" encoding="utf-8"?>
2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="com.example.installtest">
4.
5. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
6.
7. <application
8. android:allowBackup="true"
9. android:icon="@mipmap/ic_launcher"
10. android:label="@string/app_name"
11. android:supportsRtl="true"
12. android:theme="@style/AppTheme">
13. <activity android:name=".MainActivity">
14. <intent-filter>
15. <action android:name="android.intent.action.MAIN" />
16.
17. <category android:name="android.intent.category.LAUNCHER" />
18. </intent-filter>
19. </activity>
20.
21. <activity android:name=".FileExplorerActivity"/>
22. </application>
23.
24. </manifest>
并没有什么特殊的地方,由于选择apk文件需要读取SD卡,因此在AndroidManifest.xml文件中要记得声明读SD卡权限。
另外还有一点需要注意,在Android 6.0系统中,读写SD卡权限被列为了危险权限,因此如果将程序的targetSdkVersion指定成了23则需要做专门的6.0适配,这里简单起见,我把targetSdkVersion指定成了22,因为6.0的适配工作也不在文章的讲解范围之内。
现在运行程序,就可以来试一试秒装功能了,切记手机一定要ROOT,效果如下图所示:
可以看到,这里我们选择的网易新闻安装包已成功安装到手机上了,并且没有弹出系统的安装界面,由此证明秒装功能已经成功实现了。
Android 为TV端助力