2017-06-14 85 views
0

我試圖通過導航抽屜中的共享選項分享我的應用程序apk。這段代碼適用於文本,但是如何爲Apk做到這一點?通過導航抽屜上的共享選項共享應用程序

else if(id==share){ 
Intent sharingIntent = new Intent("android.intent.action.send"); 
sharingIntent.setType("text/plain"); 
sharingIntent.putExtra("android.intent.extr.TEXT", "Theshared text"); 
startActivity(Intent.createChooser(sharingIntent, "Share Using")); 
} 
+0

你要共享的APK本身還是你想分享Play商店中的網址是什麼? –

+0

APK本身@ArunShankar –

+0

嘗試先搜索你的問題,人們已經懷疑你現在擁有了。 [請參閱您的解決方案](https://stackoverflow.com/a/37986490/6047274) –

回答

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(); 
}