从Java代码在Android设备中安装APK

时间:2019-01-05 07:24:36

标签: java android

我正在尝试使用Java创建一个简单的应用程序,以便在通过USB连接的Android设备上安装APK。手动使用ABD或从Android Studio安装都可以正常工作,但是我想在应用程序中提供一个简单的单击按钮安装选项,我尝试了以下代码,但不幸的是,它无法正常工作

    abdsourcesync = apkpath;
    progress.setString("sync in progress");
    System.out.println("Starting Sync via adb with command " + "adb"
            + " install -r " + apkpath);

    Process process = Runtime.getRuntime().exec(
            "adb" + " install -r " + apkpath);
    InputStreamReader reader = new InputStreamReader(
            process.getInputStream());
    Scanner scanner = new Scanner(reader);
    scanner.close();
    int exitCode = process.waitFor();
    System.out.println("Process returned: " + exitCode);

我在这里搜索过,但是我只发现从Android应用程序或android studio而不是核心Java安装APK。或Java Web模块

非常感谢您的帮助;

2 个答案:

答案 0 :(得分:2)

不要忘记运行时权限

这个简单的示例适用于API 28。 它会打开一个apk文件,可从“下载文件夹”中安装

为简单起见: 将要安装的应用程序的apk文件下载到手机的“下载”文件夹中。 (有很多说明可以通过编程方式进行,也可以手动进行)

要做

  • 创建新项目
  • 向MainActivity添加按钮
  • 在res文件夹中创建xml文件夹,并在其中创建file_paths.xml文件
  • 使用下面的代码
  • 享受=)

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.teko.testcleanopenfile">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
    </application>
</manifest>

MainActivity


public class MainActivity extends AppCompatActivity {

    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // textView and button
        textView = findViewById(R.id.textView);textView.setText("Hello updatable World\n");
        (findViewById(R.id.button)).setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View view) {RunAPK(getBaseContext());}
        });
    }

    private void RunAPK(Context context){
        requestPermissionsToRead();
    }

    private void requestPermissionsToRead() {
        // ASK RUNTIME PERMISSIONS
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{READ_EXTERNAL_STORAGE},111);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length > 0) {
            if (requestCode == 111 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                textView.append("Permission granted write\n");

                // Create Uri
                File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                File file1 = new File (downloads + "//app-debug.apk");//downloads.listFiles()[0];
                Uri contentUri1 = getUriForFile(this, BuildConfig.APPLICATION_ID, file1);

                // Intent to open apk
                Intent intent = new Intent(Intent.ACTION_VIEW, contentUri1);
                intent.setDataAndType(contentUri1, "application/vnd.android.package-archive");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivity(intent);
            }
        }
    }
}

file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="download" path="."/>
</paths>

答案 1 :(得分:0)

您可以通过以下方式从Java代码安装应用程序。

File outputFile = null;
                    try {

                        outputFile = new File(<APK Path>);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            Uri apkUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", outputFile);
                            Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                            intent.setData(apkUri);
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            mContext.startActivity(intent);
                        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N){
                            Uri apkUri = Uri.fromFile(outputFile);
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(intent);
                        }else {
                            Toast.makeText(mContext, "File not found.", Toast.LENGTH_LONG).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }