在NavigationDrawer上通过共享选项共享Apk

时间:2017-06-14 01:44:38

标签: android android-fragments android-intent apk

我正在尝试通过导航抽屉中的共享选项分享我的应用apk。此代码适用于文本,但如何为Apk执行此操作?

mutableString

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码分享您的APK,

public static void shareAPK(Activity activity) {
    if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        try {
            // First we should copy apk file from source dir to ur external dir
            ApplicationInfo app = activity.getPackageManager().getApplicationInfo(activity.getPackageName(), 0);

            File apkFile = new File(app.sourceDir);
            File backupFile = new File(Environment.getExternalStorageDirectory(), "[ANY NAME FOR APK].apk");

            copy(apkFile, backupFile);

            Intent shareIntent = getShareIntent(backupFile);
            activity.startActivity(Intent.createChooser(shareIntent, "Send [AppName] application APK using"));
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public static Intent getShareIntent(File file) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
    intent.setType("application/vnd.android.package-archive");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    return intent;
}


public static void copy(File src, File dst) throws IOException {
    FileInputStream inStream = new FileInputStream(src);
    FileOutputStream outStream = new FileOutputStream(dst);
    FileChannel inChannel = inStream.getChannel();
    FileChannel outChannel = outStream.getChannel();
    inChannel.transferTo(0, inChannel.size(), outChannel);
    inStream.close();
    outStream.close();
}
相关问题