美文网首页
Android-->安装程序(APK)后并启动程序(APP

Android-->安装程序(APK)后并启动程序(APP

作者: angcyo | 来源:发表于2017-04-27 08:38 被阅读109次

    应用场景
    一般现在的APP,都自带自动更新功能,但是如果不处理的,安装APK完成后,默认是不会启动的;
    这个时候,就有必要查看此文了;

    开始本文:
    原理:就是通过,安装程序之前,启动一个定时任务,任务发送一个广播,广播收到之后,启动程序.

    附上代码:
    1:安装APK的代码(需要root权限)

        public static String install(String str) {
            String[] args = { "/system/bin/pm", "install", "-r", str };
            String result = "";
            ProcessBuilder processBuilder = new ProcessBuilder(args);
            Process process = null;
            InputStream errIs = null;
            InputStream inIs = null;
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int read = -1;
                process = processBuilder.start();
                errIs = process.getErrorStream();
                while ((read = errIs.read()) != -1) { // 获取错误信息
                    baos.write(read);
                }
    
                baos.write('\n');
                inIs = process.getInputStream();
                while ((read = inIs.read()) != -1) { // 获取输出信息
                    baos.write(read);
                }
    
                byte[] data = baos.toByteArray(); //
                result = new String(data);
                return result; // 返回值
            } catch (Exception e) {
                return "";
            } finally {
                try {
                    if (errIs != null) {
                        errIs.close();
                    }
                    if (inIs != null) {
                        inIs.close();
                    }
                } catch (Exception e) {
                }
            }
        }
    

    2:按钮事件代码

        public void install(View view) {
            String sdPath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath();
    
            //主要就是通过,安装程序之前,启动一个定时任务,任务发送一个广播,广播收到之后,启动程序
            Intent ite = new Intent(this, StartReceiver.class);
            ite.setAction("install_and_start");
            PendingIntent SENDER = PendingIntent.getBroadcast(this, 0, ite,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            AlarmManager ALARM = (AlarmManager) getSystemService(ALARM_SERVICE);
            ALARM.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000,
                    SENDER);
    
            install(sdPath + "/InstallAndStartDemo.apk");
            finish();
    
        }
    

    3:启动程序的广播

    public class StartReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase("install_and_start")) {
                Intent intent2 = new Intent(context, MainActivity.class);
                intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//注意,不能少
                context.startActivity(intent2);
            }
        }
    
    }
    

    4:清单文件(Manifest.xml)

            <receiver android:name="com.example.installandstartdemo.StartReceiver">
                <intent-filter >
                    <action android:name="install_and_start"/>
                </intent-filter>
            </receiver>
    

    安装APK的2种方式:

    /**
    * 使用root方式,静态安装apk
    */
    private boolean installUseRoot(String filePath) {
      if (TextUtils.isEmpty(filePath))
          throw new IllegalArgumentException("Please check apk file path!");
      boolean result = false;
      Process process = null;
      OutputStream outputStream = null;
      BufferedReader errorStream = null;
      try {
          process = Runtime.getRuntime().exec("su");
          outputStream = process.getOutputStream();
    
          String command = "pm install -r " + filePath + "\n";
          outputStream.write(command.getBytes());
          outputStream.flush();
          outputStream.write("exit\n".getBytes());
          outputStream.flush();
          process.waitFor();
          errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
          StringBuilder msg = new StringBuilder();
          String line;
          while ((line = errorStream.readLine()) != null) {
              msg.append(line);
          }
          Log.d(TAG, "install msg is " + msg);
          if (!msg.toString().contains("Failure")) {
              result = true;
          }
      } catch (Exception e) {
          Log.e(TAG, e.getMessage(), e);
      } finally {
          try {
              if (outputStream != null) {
                  outputStream.close();
              }
              if (errorStream != null) {
                  errorStream.close();
              }
          } catch (IOException e) {
              outputStream = null;
              errorStream = null;
              process.destroy();
          }
      }
      return result;
    }
    
    /**
    * 正常方式安装APK
    */
    private void installUseAS(String filePath) {
      Uri uri = Uri.fromFile(new File(filePath));
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.setDataAndType(uri, "application/vnd.android.package-archive");
      mContext.startActivity(intent);
    }
    

    源代码下载:http://download.csdn.net/detail/angcyo/8772963


    至此: 文章就结束了,如有疑问: QQ群:274306954 欢迎您的加入.

    相关文章

      网友评论

          本文标题:Android-->安装程序(APK)后并启动程序(APP

          本文链接:https://www.haomeiwen.com/subject/imkgzttx.html