【发布时间】:2018-03-12 16:28:38
【问题描述】:
我想在 cordova 应用程序中将我自己的 apk 文件分享给其他人。我试过很多插件,但所有插件都只是分享应用名称和一些描述而已。
https://www.npmjs.com/package/cordova-plugin-share https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin
所以我决定创建自己的插件,并且我有 java 的搜索共享 apk 代码,我得到了以下代码,当我从 MainActivity.java 调用该函数时它工作正常/p>
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();
}
}
但我想从 cordova 扩展 java 文件调用该函数(shareApplication())。
public class AppVersion extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
if (action.equals("shareApk")) {
MainActivity cc=new MainActivity();
cc.shareApplication();
MyClass myClass = new MyClass(c);
}
return false;
} catch (NameNotFoundException e) {
callbackContext.success("N/A");
return true;
}
}
【问题讨论】:
标签: android cordova apk phonegap