转载请注明出处:http://blog.csdn.net/androidstarjack/article/details/50349999

之前有很多朋友都问过我,在Android系统中怎样才能实现静默安装呢?所谓的静默安装,就是不用弹出系统的安装界面,在不影响用户任何操作的情况下不知不觉地将程序装好。虽说这种方式看上去不打搅用户,但是却存在着一个问题,因为Android系统会在安装界面当中把程序所声明的权限展示给用户看,用户来评估一下这些权限然后决定是否要安装该程序,但如果使用了静默安装的方式,也就没有地方让用户看权限了,相当于用户被动接受了这些权限。在Android官方看来,这显示是一种非常危险的行为,因此静默安装这一行为系统是不会开放给开发者的。

但是总是弹出一个安装对话框确实是一种体验比较差的行为,这一点Google自己也意识到了,因此Android系统对自家的Google Play商店开放了静默安装权限,也就是说所有从Google Play上下载的应用都可以不用弹出安装对话框了。这一点充分说明了拥有权限的重要性,自家的系统想怎么改就怎么改。借鉴Google的做法,很多国内的手机厂商也采用了类似的处理方式,比如说小米手机在小米商店中下载应用也是不需要弹出安装对话框的,因为小米可以在MIUI中对Android系统进行各种定制。因此,如果我们只是做一个普通的应用,其实不太需要考虑静默安装这个功能,因为我们只需要将应用上架到相应的商店当中,就会自动拥有静默安装的功能。

但是如果我们想要做的也是一个类似于商店的平台呢?比如说像360手机助手,它广泛安装于各种各样的手机上,但都是作为一个普通的应用存在的,而没有Google或小米这样的特殊权限,那360手机助手应该怎样做到更好的安装体验呢?为此360手机助手提供了两种方案, 秒装(需ROOT权限)和智能安装,如下图示:

Android静默安装实现方案,仿360手机助手秒装和智能安装功能 ._第1张图片

因此,今天我们就模仿一下360手机助手的实现方式,来给大家提供一套静默安装的解决方案。

一、秒装

所谓的秒装其实就是需要ROOT权限的静默安装,其实静默安装的原理很简单,就是调用Android系统的pm install命令就可以了,但关键的问题就在于,pm命令系统是不授予我们权限调用的,因此只能在拥有ROOT权限的手机上去申请权限才行。

下面我们开始动手,新建一个InstallTest项目,然后创建一个SilentInstall类作为静默安装功能的实现类,代码如下所示:

[java] view plain copy print ?
  1. /**
  2. *静默安装的实现类,调用install()方法执行具体的静默安装逻辑。
  3. *原文地址:http://blog.csdn.net/guolin_blog/article/details/47803149
  4. *@authorguolin
  5. *@since2015/12/7
  6. */
  7. publicclassSilentInstall{
  8. /**
  9. *执行具体的静默安装逻辑,需要手机ROOT。
  10. *@paramapkPath
  11. *要安装的apk文件的路径
  12. *@return安装成功返回true,安装失败返回false。
  13. */
  14. publicbooleaninstall(StringapkPath){
  15. booleanresult=false;
  16. DataOutputStreamdataOutputStream=null;
  17. BufferedReadererrorStream=null;
  18. try{
  19. //申请su权限
  20. Processprocess=Runtime.getRuntime().exec("su");
  21. dataOutputStream=newDataOutputStream(process.getOutputStream());
  22. //执行pminstall命令
  23. Stringcommand="pminstall-r"+apkPath+"\n";
  24. dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
  25. dataOutputStream.flush();
  26. dataOutputStream.writeBytes("exit\n");
  27. dataOutputStream.flush();
  28. process.waitFor();
  29. errorStream=newBufferedReader(newInputStreamReader(process.getErrorStream()));
  30. Stringmsg="";
  31. Stringline;
  32. //读取命令的执行结果
  33. while((line=errorStream.readLine())!=null){
  34. msg+=line;
  35. }
  36. Log.d("TAG","installmsgis"+msg);
  37. //如果执行结果中包含Failure字样就认为是安装失败,否则就认为安装成功
  38. if(!msg.contains("Failure")){
  39. result=true;
  40. }
  41. }catch(Exceptione){
  42. Log.e("TAG",e.getMessage(),e);
  43. }finally{
  44. try{
  45. if(dataOutputStream!=null){
  46. dataOutputStream.close();
  47. }
  48. if(errorStream!=null){
  49. errorStream.close();
  50. }
  51. }catch(IOExceptione){
  52. Log.e("TAG",e.getMessage(),e);
  53. }
  54. }
  55. returnresult;
  56. }
  57. }
可以看到,SilentInstall类中只有一个install()方法,所有静默安装的逻辑都在这个方法中了,那么我们具体来看一下这个方法。首先在第21行调用了Runtime.getRuntime().exec("su")方法,在这里先申请ROOT权限,不然的话后面的操作都将失败。然后在第24行开始组装静默安装命令,命令的格式就是pm install -r <apk路径>,-r参数表示如果要安装的apk已经存在了就覆盖安装的意思,apk路径是作为方法参数传入的。接下来的几行就是执行上述命令的过程,注意安装这个过程是同步的,因此我们在下面调用了process.waitFor()方法,即安装要多久,我们就要在这里等多久。等待结束之后说明安装过程结束了,接下来我们要去读取安装的结果并进行解析,解析的逻辑也很简单,如果安装结果中包含Failure字样就说明安装失败,反之则说明安装成功。

整个方法还是非常简单易懂的,下面我们就来搭建调用这个方法的环境。修改activity_main.xml中的代码,如下所示:

[html] view plain copy print ?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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. <LinearLayout
  13. android:layout_width="match_parent"
  14. android:layout_height="wrap_content">
  15. <Button
  16. android:layout_width="wrap_content"
  17. android:layout_height="wrap_content"
  18. android:onClick="onChooseApkFile"
  19. android:text="选择安装包"/>
  20. <TextView
  21. android:id="@+id/apkPathText"
  22. android:layout_width="0dp"
  23. android:layout_height="wrap_content"
  24. android:layout_weight="1"
  25. android:layout_gravity="center_vertical"
  26. />
  27. </LinearLayout>
  28. <View
  29. android:layout_width="match_parent"
  30. android:layout_height="1dp"
  31. android:background="@android:color/darker_gray"/>
  32. <Button
  33. android:layout_width="wrap_content"
  34. android:layout_height="wrap_content"
  35. android:onClick="onSilentInstall"
  36. android:text="秒装"/>
  37. <View
  38. android:layout_width="match_parent"
  39. android:layout_height="1dp"
  40. android:background="@android:color/darker_gray"/>
  41. <Button
  42. android:layout_width="wrap_content"
  43. android:layout_height="wrap_content"
  44. android:onClick="onForwardToAccessibility"
  45. android:text="开启智能安装服务"/>
  46. <Button
  47. android:layout_width="wrap_content"
  48. android:layout_height="wrap_content"
  49. android:onClick="onSmartInstall"
  50. android:text="智能安装"/>
  51. </LinearLayout>
这里我们先将程序的主界面确定好,主界面上拥有四个按钮,第一个按钮用于选择apk文件的,第二个按钮用于开始秒装,第三个按钮用于开启智能安装服务,第四个按钮用于开始智能安装,这里我们暂时只能用到前两个按钮。那么调用SilentInstall的install()方法需要传入apk路径,因此我们需要先把文件选择器的功能实现好,新建activity_file_explorer.xml和list_item.xml作为文件选择器的布局文件,代码分别如下所示: [html] view plain copy print ?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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. <ListView
  7. android:id="@+id/list_view"
  8. android:layout_width="match_parent"
  9. android:layout_height="match_parent"
  10. />
  11. </LinearLayout>
[html] view plain copy print ?
  1. <?xmlversion="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. <ImageViewandroid:id="@+id/img"
  9. android:layout_width="32dp"
  10. android:layout_margin="4dp"
  11. android:layout_gravity="center_vertical"
  12. android:layout_height="32dp"/>
  13. <TextViewandroid:id="@+id/name"
  14. android:textSize="18sp"
  15. android:textStyle="bold"
  16. android:layout_width="match_parent"
  17. android:gravity="center_vertical"
  18. android:layout_height="50dp"/>
  19. </LinearLayout>
然后新建FileExplorerActivity作为文件选择器的Activity,代码如下: [java] view plain copy print ?
  1. publicclassFileExplorerActivityextendsAppCompatActivityimplementsAdapterView.OnItemClickListener{
  2. ListViewlistView;
  3. SimpleAdapteradapter;
  4. StringrootPath=Environment.getExternalStorageDirectory().getPath();
  5. StringcurrentPath=rootPath;
  6. List<Map<String,Object>>list=newArrayList<>();
  7. @Override
  8. publicvoidonCreate(BundlesavedInstanceState){
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.activity_file_explorer);
  11. listView=(ListView)findViewById(R.id.list_view);
  12. adapter=newSimpleAdapter(this,list,R.layout.list_item,
  13. newString[]{"name","img"},newint[]{R.id.name,R.id.img});
  14. listView.setAdapter(adapter);
  15. listView.setOnItemClickListener(this);
  16. refreshListItems(currentPath);
  17. }
  18. privatevoidrefreshListItems(Stringpath){
  19. setTitle(path);
  20. File[]files=newFile(path).listFiles();
  21. list.clear();
  22. if(files!=null){
  23. for(Filefile:files){
  24. Map<String,Object>map=newHashMap<>();
  25. if(file.isDirectory()){
  26. map.put("img",R.drawable.directory);
  27. }else{
  28. map.put("img",R.drawable.file_doc);
  29. }
  30. map.put("name",file.getName());
  31. map.put("currentPath",file.getPath());
  32. list.add(map);
  33. }
  34. }
  35. adapter.notifyDataSetChanged();
  36. }
  37. @Override
  38. publicvoidonItemClick(AdapterView<?>parent,Viewv,intposition,longid){
  39. currentPath=(String)list.get(position).get("currentPath");
  40. Filefile=newFile(currentPath);
  41. if(file.isDirectory())
  42. refreshListItems(currentPath);
  43. else{
  44. Intentintent=newIntent();
  45. intent.putExtra("apk_path",file.getPath());
  46. setResult(RESULT_OK,intent);
  47. finish();
  48. }
  49. }
  50. @Override
  51. publicvoidonBackPressed(){
  52. if(rootPath.equals(currentPath)){
  53. super.onBackPressed();
  54. }else{
  55. Filefile=newFile(currentPath);
  56. currentPath=file.getParentFile().getPath();
  57. refreshListItems(currentPath);
  58. }
  59. }
  60. }
这部分代码由于和我们本篇文件的主旨没什么关系,主要是为了方便demo展示的,因此我就不进行讲解了。

接下来修改MainActivity中的代码,如下所示:

[java] view plain copy print ?
  1. /**
    * 仿360手机助手秒装和智能安装功能的主Activity。
    * 原文地址:http://blog.csdn.net/androidstarjack/article/details/50349999
    * @author androidstarjack
    * @since 2015/12/7
    */
  2. publicclassMainActivityextendsAppCompatActivity{
  3. TextViewapkPathText;
  4. StringapkPath;
  5. @Override
  6. protectedvoidonCreate(BundlesavedInstanceState){
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.activity_main);
  9. apkPathText=(TextView)findViewById(R.id.apkPathText);
  10. }
  11. @Override
  12. protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
  13. if(requestCode==0&&resultCode==RESULT_OK){
  14. apkPath=data.getStringExtra("apk_path");
  15. apkPathText.setText(apkPath);
  16. }
  17. }
  18. publicvoidonChooseApkFile(Viewview){
  19. Intentintent=newIntent(this,FileExplorerActivity.class);
  20. startActivityForResult(intent,0);
  21. }
  22. publicvoidonSilentInstall(Viewview){
  23. if(!isRoot()){
  24. Toast.makeText(this,"没有ROOT权限,不能使用秒装",Toast.LENGTH_SHORT).show();
  25. return;
  26. }
  27. if(TextUtils.isEmpty(apkPath)){
  28. Toast.makeText(this,"请选择安装包!",Toast.LENGTH_SHORT).show();
  29. return;
  30. }
  31. finalButtonbutton=(Button)view;
  32. button.setText("安装中");
  33. newThread(newRunnable(){
  34. @Override
  35. publicvoidrun(){
  36. SilentInstallinstallHelper=newSilentInstall();
  37. finalbooleanresult=installHelper.install(apkPath);
  38. runOnUiThread(newRunnable(){
  39. @Override
  40. publicvoidrun(){
  41. if(result){
  42. Toast.makeText(MainActivity.this,"安装成功!",Toast.LENGTH_SHORT).show();
  43. }else{
  44. Toast.makeText(MainActivity.this,"安装失败!",Toast.LENGTH_SHORT).show();
  45. }
  46. button.setText("秒装");
  47. }
  48. });
  49. }
  50. }).start();
  51. }
  52. publicvoidonForwardToAccessibility(Viewview){
  53. }
  54. publicvoidonSmartInstall(Viewview){
  55. }
  56. /**
  57. *判断手机是否拥有Root权限。
  58. *@return有root权限返回true,否则返回false。
  59. */
  60. publicbooleanisRoot(){
  61. booleanbool=false;
  62. try{
  63. bool=newFile("/system/bin/su").exists()||newFile("/system/xbin/su").exists();
  64. }catch(Exceptione){
  65. e.printStackTrace();
  66. }
  67. returnbool;
  68. }
  69. }
可以看到,在MainActivity中,我们对四个按钮点击事件的回调方法都进行了定义,当点击选择安装包按钮时就会调用onChooseApkFile()方法,当点击秒装按钮时就会调用onSilentInstall()方法。在onChooseApkFile()方法方法中,我们通过Intent打开了FileExplorerActivity,然后在onActivityResult()方法当中读取选择的apk文件路径。在onSilentInstall()方法当中,先判断设备是否ROOT,如果没有ROOT就直接return,然后判断安装包是否已选择,如果没有也直接return。接下来我们开启了一个线程来调用SilentInstall.install()方法,因为安装过程会比较耗时,如果不开线程的话主线程就会被卡住,不管安装成功还是失败,最后都会使用Toast来进行提示。

代码就这么多,最后我们来配置一下AndroidManifest.xml文件:

[html] view plain copy print ?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.example.installtest">
  4. <uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"/>
  5. <application
  6. android:allowBackup="true"
  7. android:icon="@mipmap/ic_launcher"
  8. android:label="@string/app_name"
  9. android:supportsRtl="true"
  10. android:theme="@style/AppTheme">
  11. <activityandroid:name=".MainActivity">
  12. <intent-filter>
  13. <actionandroid:name="android.intent.action.MAIN"/>
  14. <categoryandroid:name="android.intent.category.LAUNCHER"/>
  15. </intent-filter>
  16. </activity>
  17. <activityandroid:name=".FileExplorerActivity"/>
  18. </application>
  19. </manifest>
并没有什么特殊的地方,由于选择apk文件需要读取SD卡,因此在AndroidManifest.xml文件中要记得声明读SD卡权限。

另外还有一点需要注意,在Android 6.0系统中,读写SD卡权限被列为了危险权限,因此如果将程序的targetSdkVersion指定成了23则需要做专门的6.0适配,这里简单起见,我把targetSdkVersion指定成了22,因为6.0的适配工作也不在文章的讲解范围之内。

现在运行程序,就可以来试一试秒装功能了,切记手机一定要ROOT,效果如下图所示:

Android静默安装实现方案,仿360手机助手秒装和智能安装功能 ._第2张图片

可以看到,这里我们选择的网易新闻安装包已成功安装到手机上了,并且没有弹出系统的安装界面,由此证明秒装功能已经成功实现了。

二、智能安装

那么对于ROOT过的手机,秒装功能确实可以避免弹出系统安装界面,在不影响用户操作的情况下实现静默安装,但是对于绝大部分没有ROOT的手机,这个功能是不可用的。那么我们应该怎么办呢?为此360手机助手提供了一种折中方案,就是借助Android提供的无障碍服务来实现智能安装。所谓的智能安装其实并不是真正意义上的静默安装,因为它还是要弹出系统安装界面的,只不过可以在安装界面当中释放用户的操作,由智能安装功能来模拟用户点击,安装完成之后自动关闭界面。这个功能是需要用户手动开启的,并且只支持Android 4.1之后的手机,如下图所示:

Android静默安装实现方案,仿360手机助手秒装和智能安装功能 ._第3张图片

好的,那么接下来我们就模仿一下360手机助手,来实现类似的智能安装功能。

智能安装功能的实现原理要借助Android提供的无障碍服务,关于无障碍服务的详细讲解可参考官方文档:http://developer.android.com/guide/topics/ui/accessibility/services.html。

首先在res/xml目录下新建一个accessibility_service_config.xml文件,代码如下所示:

[html] view plain copy print ?
  1. <accessibility-servicexmlns:android="http://schemas.android.com/apk/res/android"
  2. android:packageNames="com.android.packageinstaller"
  3. android:description="@string/accessibility_service_description"
  4. android:accessibilityEventTypes="typeAllMask"
  5. android:accessibilityFlags="flagDefault"
  6. android:accessibilityFeedbackType="feedbackGeneric"
  7. android:canRetrieveWindowContent="true"
  8. />
其中,packageNames指定我们要监听哪个应用程序下的窗口活动,这里写com.android.packageinstaller表示监听Android系统的安装界面。description指定在无障碍服务当中显示给用户看的说明信息,上图中360手机助手的一大段内容就是在这里指定的。accessibilityEventTypes指定我们在监听窗口中可以模拟哪些事件,这里写typeAllMask表示所有的事件都能模拟。accessibilityFlags可以指定无障碍服务的一些附加参数,这里我们传默认值flagDefault就行。accessibilityFeedbackType指定无障碍服务的反馈方式,实际上无障碍服务这个功能是Android提供给一些残疾人士使用的,比如说盲人不方便使用手机,就可以借助无障碍服务配合语音反馈来操作手机,而我们其实是不需要反馈的,因此随便传一个值就可以,这里传入feedbackGeneric。最后canRetrieveWindowContent指定是否允许我们的程序读取窗口中的节点和内容,必须写true。

记得在string.xml文件中写一下description中指定的内容,如下所示:

[html] view plain copy print ?
  1. <resources>
  2. <stringname="app_name">InstallTest</string>
  3. <stringname="accessibility_service_description">智能安装服务,无需用户的任何操作就可以自动安装程序。</string>
  4. </resources>
接下来修改AndroidManifest.xml文件,在里面配置无障碍服务: [html] view plain copy print ?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.example.installtest">
  4. <uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"/>
  5. <application
  6. android:allowBackup="true"
  7. android:icon="@mipmap/ic_launcher"
  8. android:label="@string/app_name"
  9. android:supportsRtl="true"
  10. android:theme="@style/AppTheme">
  11. ......
  12. <service
  13. android:name=".MyAccessibilityService"
  14. android:label="我的智能安装"
  15. android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
  16. <intent-filter>
  17. <actionandroid:name="android.accessibilityservice.AccessibilityService"/>
  18. </intent-filter>
  19. <meta-data
  20. android:name="android.accessibilityservice"
  21. android:resource="@xml/accessibility_service_config"/>
  22. </service>
  23. </application>
  24. </manifest>
这部分配置的内容多数是固定的,必须要声明一个android.permission.BIND_ACCESSIBILITY_SERVICE的权限,且必须要有一个值为android.accessibilityservice.AccessibilityService的action,然后我们通过<meta-data>将刚才创建的配置文件指定进去。

接下来就是要去实现智能安装功能的具体逻辑了,创建一个MyAccessibilityService类并继承自AccessibilityService,代码如下所示:

[java] view plain copy print ?
  1. /**
  2. *智能安装功能的实现类。
  3. *原文地址:http://blog.csdn.net/androidstarjack/article/details/50349999
  4. *@author androidstarjack
  5. *@since2015/12/7
  6. */
  7. publicclassMyAccessibilityServiceextendsAccessibilityService{
  8. Map<Integer,Boolean>handledMap=newHashMap<>();
  9. publicMyAccessibilityService(){
  10. }
  11. @Override
  12. publicvoidonAccessibilityEvent(AccessibilityEventevent){
  13. AccessibilityNodeInfonodeInfo=event.getSource();
  14. if(nodeInfo!=null){
  15. inteventType=event.getEventType();
  16. if(eventType==AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED||
  17. eventType==AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED){
  18. if(handledMap.get(event.getWindowId())==null){
  19. booleanhandled=iterateNodesAndHandle(nodeInfo);
  20. if(handled){
  21. handledMap.put(event.getWindowId(),true);
  22. }
  23. }
  24. }
  25. }
  26. }
  27. privatebooleaniterateNodesAndHandle(AccessibilityNodeInfonodeInfo){
  28. if(nodeInfo!=null){
  29. intchildCount=nodeInfo.getChildCount();
  30. if("android.widget.Button".equals(nodeInfo.getClassName())){
  31. StringnodeContent=nodeInfo.getText().toString();
  32. Log.d("TAG","contentis"+nodeContent);
  33. if("安装".equals(nodeContent)
  34. ||"完成".equals(nodeContent)
  35. ||"确定".equals(nodeContent)){
  36. nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
  37. returntrue;
  38. }
  39. }elseif("android.widget.ScrollView".equals(nodeInfo.getClassName())){
  40. nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
  41. }
  42. for(inti=0;i<childCount;i++){
  43. AccessibilityNodeInfochildNodeInfo=nodeInfo.getChild(i);
  44. if(iterateNodesAndHandle(childNodeInfo)){
  45. returntrue;
  46. }
  47. }
  48. }
  49. returnfalse;
  50. }
  51. @Override
  52. publicvoidonInterrupt(){
  53. }
  54. }
代码并不复杂,我们来解析一下。每当窗口有活动时,就会有消息回调到onAccessibilityEvent()方法中,因此所有的逻辑都是从这里开始的。首先我们可以通过传入的AccessibilityEvent参数来获取当前事件的类型,事件的种类非常多,但是我们只需要监听TYPE_WINDOW_CONTENT_CHANGED和TYPE_WINDOW_STATE_CHANGED这两种事件就可以了,因为在整个安装过程中,这两个事件必定有一个会被触发。当然也有两个同时都被触发的可能,那么为了防止二次处理的情况,这里我们使用了一个Map来过滤掉重复事件。

接下来就是调用iterateNodesAndHandle()方法来去解析当前界面的节点了,这里我们通过递归的方式将安装界面中所有的子节点全部进行遍历,当发现按钮节点的时候就进行判断,按钮上的文字是不是“安装”、“完成”、“确定”这几种类型,如果是的话就模拟一下点击事件,这样也就相当于帮用户自动操作了这些按钮。另外从Android 4.4系统开始,用户需要将应用申请的所有权限看完才可以点击安装,因此如果我们在节点中发现了ScrollView,那就模拟一下滑动事件,将界面滑动到最底部,这样安装按钮就可以点击了。

最后,回到MainActivity中,来增加对智能安装功能的调用,如下所示:

[java] view plain copy print ?
  1. /**
  2. *仿360手机助手秒装和智能安装功能的主Activity。
  3. *原文地址:http://blog.csdn.net/androidstarjack/article/details/50349999
  4. *@author Androidstarajack
  5. *@since2015/12/7
  6. */
  7. publicclassMainActivityextendsAppCompatActivity{
  8. ......
  9. publicvoidonForwardToAccessibility(Viewview){
  10. Intentintent=newIntent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
  11. startActivity(intent);
  12. }
  13. publicvoidonSmartInstall(Viewview){
  14. if(TextUtils.isEmpty(apkPath)){
  15. Toast.makeText(this,"请选择安装包!",Toast.LENGTH_SHORT).show();
  16. return;
  17. }
  18. Uriuri=Uri.fromFile(newFile(apkPath));
  19. IntentlocalIntent=newIntent(Intent.ACTION_VIEW);
  20. localIntent.setDataAndType(uri,"application/vnd.android.package-archive");
  21. startActivity(localIntent);
  22. }
  23. }
当点击了开启智能安装服务按钮时,我们通过Intent跳转到系统的无障碍服务界面,在这里启动智能安装服务。当点击了智能安装按钮时,我们通过Intent跳转到系统的安装界面,之后所有的安装操作都会自动完成了。

现在可以重新运行一下程序,效果如下图所示:


可以看到,当打开网易新闻的安装界面之后,我们不需要进行任何的手动操作,界面的滑动、安装按钮、完成按钮的点击都是自动完成的,最终会自动回到手机原来的界面状态,这就是仿照360手机助手实现的智能安装功能。

好的,本篇文章的所有内容就到这里了,虽说不能说完全实现静默安装,但是我们已经在权限允许的范围内尽可能地去完成了,并且360手机助手也只能实现到这一步而已,那些被产品经理逼着去实现静默安装的程序员们也有理由交差了吧?

http://download.csdn.net/detail/androidstarjack/9399585





更多相关文章

  1. 亚马逊应用商店 – Android 手机的新选择
  2. android 获得root权限解密
  3. android 修改ramdisk.img和init.rc && android启动后设置/data权
  4. Android安全模型之Android安全机制(应用权限)
  5. Android将手机相册图片展示到GridView中
  6. 45套精美的 ( Android, iPhone, iPad ) 手机界面设计素材和线框

随机推荐

  1. Android Push Notificatioin Service(And
  2. Android基础UI篇------六种基本布局
  3. android动态的加载so库文件
  4. Android的selector 背景选择器
  5. Android线程学习总结
  6. Android SDK更新后Eclipse无法正常工作问
  7. Android第十九课 attempt to write a rea
  8. android的消息处理机制(图+源码分析)——Lo
  9. Android Studio 3.6 特征大揭秘
  10. android 面试题二