繁体   English   中英

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

[英]Install apk in android device from java code

我正在尝试使用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模块

您的帮助之手将受到赞赏;

您可以使用以下方式从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();
                    }

不要忘记运行时权限

这个简单的示例适用于API28。它打开一个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>

主要活动


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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM