Android P实现静默安装的方法示例(官方Demo)

Android9.0无法通过以下两种方式实现静默安装:

1.runtime执行shell cmd
2.PackageInstall 反射机制

但是Google已经给我们推荐了相关的APIDemos,所以建议大家多看看源码~

在frameworks/base/core/java/android/content/pm/PackageInstaller.java有段关于该类的介绍:

  1. The ApiDemos project contains examples of using this API:
  2. <code>ApiDemos/src/com/example/android/apis/content/InstallApk*.java</code>.
/**
 * Offers the ability to install, upgrade, and remove applications on the
 * device. This includes support for apps packaged either as a single
 * "monolithic" APK, or apps packaged as multiple "split" APKs.
 * <p>
 * An app is delivered for installation through a
 * {@link PackageInstaller.Session}, which any app can create. Once the session
 * is created, the installer can stream one or more APKs into place until it
 * decides to either commit or destroy the session. Committing may require user
 * intervention to complete the installation.
 * <p>
 * Sessions can install brand new apps, upgrade existing apps, or add new splits
 * into an existing app.
 * <p>
 * Apps packaged as multiple split APKs always consist of a single "base" APK
 * (with a {@code null} split name) and zero or more "split" APKs (with unique
 * split names). Any subset of these APKs can be installed together, as long as
 * the following constraints are met:
 * <ul>
 * <li>All APKs must have the exact same package name, version code, and signing
 * certificates.
 * <li>All APKs must have unique split names.
 * <li>All installations must contain a single base APK.
 * </ul>
 * <p>
 * ###########此处告诉开发者如何调用API安装apk##############
 * The ApiDemos project contains examples of using this API:
 * <code>ApiDemos/src/com/example/android/apis/content/InstallApk*.java</code>.
 */
public class PackageInstaller

翻阅源码,InstallApk*.java相关的一共两个demo
InstallApkSessionApi.java //静默安装
InstallApk.java //普通安装,调用系统install intent进行安装

下面是InstallApkSessionApi.java的具体demo

package com.example.android.apis.content;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageInstaller;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Demonstration of package installation and uninstallation using the package installer Session
 * API.
 *
 * @see InstallApk for a demo of the original (non-Session) API.
 */
public class InstallApkSessionApi extends Activity {
  private static final String PACKAGE_INSTALLED_ACTION =
      "com.example.android.apis.content.SESSION_API_PACKAGE_INSTALLED";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.install_apk_session_api);

    // Watch for button clicks.
    Button button = (Button) findViewById(R.id.install);
    button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        PackageInstaller.Session session = null;
        try {
          PackageInstaller packageInstaller = getPackageManager().getPackageInstaller();
          PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
              PackageInstaller.SessionParams.MODE_FULL_INSTALL);
          int sessionId = packageInstaller.createSession(params);
          session = packageInstaller.openSession(sessionId);

          addApkToInstallSession("HelloActivity.apk", session);

          // Create an install status receiver.
          Context context = InstallApkSessionApi.this;
          Intent intent = new Intent(context, InstallApkSessionApi.class);
          intent.setAction(PACKAGE_INSTALLED_ACTION);

          //此处也可以使用getBoradcast或者getService回调通知
          PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
          IntentSender statusReceiver = pendingIntent.getIntentSender();

          // Commit the session (this will start the installation workflow).
          session.commit(statusReceiver);
        } catch (IOException e) {
          throw new RuntimeException("Couldn't install package", e);
        } catch (RuntimeException e) {
          if (session != null) {
            session.abandon();
          }
          throw e;
        }
      }
    });
  }

  private void addApkToInstallSession(String assetName, PackageInstaller.Session session)
      throws IOException {
    // It's recommended to pass the file size to openWrite(). Otherwise installation may fail
    // if the disk is almost full.
    try (OutputStream packageInSession = session.openWrite("package", 0, -1);
       InputStream is = getAssets().open(assetName)) {
      byte[] buffer = new byte[16384];
      int n;
      while ((n = is.read(buffer)) >= 0) {
        packageInSession.write(buffer, 0, n);
      }
    }
  }

  // Note: this Activity must run in singleTop launchMode for it to be able to receive the intent
  // in onNewIntent().
  @Override
  protected void onNewIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    if (PACKAGE_INSTALLED_ACTION.equals(intent.getAction())) {
      int status = extras.getInt(PackageInstaller.EXTRA_STATUS);
      String message = extras.getString(PackageInstaller.EXTRA_STATUS_MESSAGE);

      switch (status) {
        case PackageInstaller.STATUS_PENDING_USER_ACTION:
          // This test app isn't privileged, so the user has to confirm the install.
          Intent confirmIntent = (Intent) extras.get(Intent.EXTRA_INTENT);
          startActivity(confirmIntent);
          break;

        case PackageInstaller.STATUS_SUCCESS:
          Toast.makeText(this, "Install succeeded!", Toast.LENGTH_SHORT).show();
          break;

        case PackageInstaller.STATUS_FAILURE:
        case PackageInstaller.STATUS_FAILURE_ABORTED:
        case PackageInstaller.STATUS_FAILURE_BLOCKED:
        case PackageInstaller.STATUS_FAILURE_CONFLICT:
        case PackageInstaller.STATUS_FAILURE_INCOMPATIBLE:
        case PackageInstaller.STATUS_FAILURE_INVALID:
        case PackageInstaller.STATUS_FAILURE_STORAGE:
          Toast.makeText(this, "Install failed! " + status + ", " + message,
              Toast.LENGTH_SHORT).show();
          break;
        default:
          Toast.makeText(this, "Unrecognized status received from installer: " + status,
              Toast.LENGTH_SHORT).show();
      }
    }
  }
}

另外,权限要求:

需要系统签名
permission

<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

到此这篇关于Android P实现静默安装的方法示例(官方Demo)的文章就介绍到这了,更多相关Android P 静默安装 内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • android实现静默安装与卸载的方法

    本文实例讲述了android实现静默安装与卸载的方法.分享给大家供大家参考.具体如下: 方法1:[使用调用接口方法,由于安装卸载应用程序的部分API是隐藏的,所以必须下载Android系统源码,在源码下开发并编译之后使用MM命令编译生成APK文件] import java.io.File; import android.app.Activity; import android.os.Bundle; import android.content.Intent; import android.con

  • Android9.0 静默安装源码的实现

    网上基本都停在8.0就没人开始分析Android9.0如何静默apk的代码,这是我自己之前研究9.0的framework整理出来的,真实源码整理 import android.content.BroadcastReceiver; import android.content.Context; import android.content.IIntentReceiver; import android.content.IIntentSender; import android.content.In

  • Android程序静默安装安装后重新启动APP的方法

     一:需求简介 之前boss提出一个需求,运行在广告机上的app,需要完成自动升级的功能,广告机是非触摸屏的,不能通过手动点击,所以app必须做到自动下载,自动安装升级,并且安装完成后,app还要继续运行,最好不借助其它app来实现以上功能.  二:实现思路 实现这个功能第一个想到的方法就是静默安装,由于广告机已经root,静默安装比较顺利,安装app的主要代码如下: /* @pararm apkPath 等待安装的app全路径,如:/sdcard/app/app.apk **/ private

  • Android无需root实现apk的静默安装

    Android的静默安装似乎是一个很有趣很诱人的东西,但是,用普通做法,如果手机没有root权限的话,似乎很难实现静默安装,因为Android并不提供显示的Intent调用,一般是通过以下方式安装apk: Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); startAct

  • Android 静默安装和智能安装的实现方法

    1 简介 最近研究了Android的静默安装和智能安装,于是写博客记录一下.静默安装就是无声无息的在后台安装apk,没有任何界面提示.智能安装就是有安装界面,但全部是自动的,不需要用户去点击. 首先强调两点:静默安装必须要root权限 智能安装必须要用户手动开启无障碍服务 2 原理 静默安装.卸载的原理就是利用pm install命令来安装apk,pm uninstall 来卸载apk. 智能安装是利用android系统提供的无障碍服务AccessibilityService,来模拟用户点击,从

  • Android实现静默安装实例代码

    静默安装主要分为以下几种方式: 一.在ROOT过的机器上,在App中使用pm install指令安装APK: // 申请su权限 Process process = Runtime.getRuntime().exec("su"); dataOutputStream = new DataOutputStream(process.getOutputStream()); // 执行pm install命令 String command = "pm install -r "

  • Android 静默安装和卸载的方法

    本文介绍了Android 静默安装和卸载的方法,分享给大家,具体如下: 一. 条件 系统签名 需要放到 /system/app里作为系统app 二. 适用环境 机顶盒开发,系统开发,车机开发,智能设备开发. 三. 步骤 1. 在 AndroidManifest.xml 中 1.1. 在清单文件 AndroidManifest.xml 添加 android.uid.system 声明为系统应用. 1.2. 权限 <uses-permission android:name="android.p

  • Android 静默安装实现方法

    Android静默安装的方法,静默安装就是绕过安装程序时的提示窗口,直接在后台安装. 注意:静默安装的前提是设备有ROOT权限. 代码如下: /** * 静默安装 * @param file * @return */ public boolean slientInstall(File file) { boolean result = false; Process process = null; OutputStream out = null; try { process = Runtime.ge

  • Android静默安装实现方案 仿360手机助手秒装和智能安装功能

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

  • Android实现静默安装的两种方法

    前言 一般情况下,Android系统安装apk会出现一个安装界面,用户可以点击确定或者取消来进行apk的安装. 但在实际的项目需求中,有一种需求,就是希望apk在后台安装(不出现安装界面的提示),这种安装方式称为静默安装.下面这篇文章就给大家介绍了两种方法来实现,下面来一起看看吧. 1.root权限静默安装实现 实现实际使用的是su pm install -r filePath命令. 核心代码如下: protected static void excuteSuCMD() { Process pr

随机推荐