2016-09-14 55 views
0

我嘗試使用此代碼,以我的應用程序的apk文件發送到另一設備:我如何共享apk文件在我的應用程序(發送應用程序本身)

public static void sendAppItself(Activity paramActivity) throws IOException { 
    PackageManager pm = paramActivity.getPackageManager(); 
    ApplicationInfo appInfo; 
    try { 
     appInfo = pm.getApplicationInfo(paramActivity.getPackageName(), 
       PackageManager.GET_META_DATA); 
     Intent sendBt = new Intent(Intent.ACTION_SEND); 
     sendBt.setType("*/*"); 
     sendBt.putExtra(Intent.EXTRA_STREAM, 
       Uri.parse("file://" + appInfo.publicSourceDir)); 

     paramActivity.startActivity(Intent.createChooser(sendBt, 
       "Share it using")); 
    } catch (PackageManager.NameNotFoundException e1) { 
     e1.printStackTrace(); 
    } 
} 

此代碼的工作非常好。

但apk文件共享與此代碼名稱爲base.apk

如何改變呢?

+0

這隻適用於有根設備。爲什麼不告訴? – greenapps

+0

該評論不正確。在Marshmellow與GMail應用程序我得到了「權限被拒絕的附件」。名字是base.apk。但在Android 4.2.2設備上,它是 -1.apk,可以通過電子郵件應用發送。 – greenapps

+0

這不僅適用於根植設備!所有設備都支持它。 – miladsolgi

回答

5

將文件從源目錄複製到新目錄。 在複製和共享複製文件時重命名文件。 共享完成後刪除臨時文件。

private void shareApplication() { 
    ApplicationInfo app = getApplicationContext().getApplicationInfo(); 
    String filePath = app.sourceDir; 

    Intent intent = new Intent(Intent.ACTION_SEND); 

    // MIME of .apk is "application/vnd.android.package-archive". 
    // but Bluetooth does not accept this. Let's use "*/*" instead. 
    intent.setType("*/*"); 

    // Append file and send Intent 
    File originalApk = new File(filePath); 

    try { 
     //Make new directory in new location 
     File tempFile = new File(getExternalCacheDir() + "/ExtractedApk"); 
     //If directory doesn't exists create new 
     if (!tempFile.isDirectory()) 
      if (!tempFile.mkdirs()) 
       return; 
     //Get application's name and convert to lowercase 
     tempFile = new File(tempFile.getPath() + "/" + getString(app.labelRes).replace(" ","").toLowerCase() + ".apk"); 
     //If file doesn't exists create new 
     if (!tempFile.exists()) { 
      if (!tempFile.createNewFile()) { 
       return; 
      } 
     } 
     //Copy file to new location 
     InputStream in = new FileInputStream(originalApk); 
     OutputStream out = new FileOutputStream(tempFile); 

     byte[] buf = new byte[1024]; 
     int len; 
     while ((len = in.read(buf)) > 0) { 
      out.write(buf, 0, len); 
     } 
     in.close(); 
     out.close(); 
     System.out.println("File copied."); 
     //Open share dialog 
     intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile)); 
     startActivity(Intent.createChooser(intent, "Share app via")); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

謝謝。非常好 – HPbyP

1

這隻發生,因爲它是由base.apk名稱保存。 要根據您的需要分享它,您必須將該文件複製到另一個目錄路徑並在那裏重命名。然後使用新文件分享。

數據文件夾中的此文件路徑[file:///data/app/com.yourapppackagename/base.apk]僅具有讀取權限,因此您無法在此處重命名.apk文件。

+0

如何以編程方式將此文件複製到其他目錄路徑? – miladsolgi

相關問題