문제

I want to make an application that could send itself (apk file) by bluetooth. but i have trouble with finding the apk file path. i tried this code:

final PackageManager pm = this.getPackageManager();
    List<PackageInfo> packages =  pm.getInstalledPackages(PackageManager.GET_META_DATA);
    String st = null;
    for (PackageInfo packageInfo : packages) {
        if(packageInfo.packageName.contains("testbutton"))
        st=packageInfo.packageName;
    }

    Intent intent = new Intent();  
    intent.setAction(Intent.ACTION_SEND);  
    intent.setType("image/*");

    String uri = "/data/app/";
    uri+=st;
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(uri)));
    startActivity(intent);

but st returns null value. please help me with this. thanks in advance

도움이 되었습니까?

해결책 2

finally i'd found the right answer that works in this purpose, thanks to @Kanak for her help :)

PackageManager pm = getPackageManager();
    String uri = null;
    for (ApplicationInfo app : pm.getInstalledApplications(0)) {
        if(!((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1))
            if(!((app.flags & ApplicationInfo.FLAG_SYSTEM) == 1)){
                uri=app.sourceDir;
                  if(uri.contains("com.example.test"))
                  break;
            }
    }

    Intent intent = new Intent();  
    intent.setAction(Intent.ACTION_SEND);  
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(uri)));
    startActivity(intent);

다른 팁

There is no need to iteration. Getting the application itself APK file uri is as easy as this:

String appUri = getApplicationInfo().publicSourceDir;

Also note that doc says this about publicSourceDir:

Full path to the publicly available parts of sourceDir, including resources and manifest. This may be different from sourceDir if an application is forward locked.

And also note that to send an APK file, you need to set the type to application/vnd.android.package-archive instead of image/*

So the complete snippet would be:

String appUri = getApplicationInfo().publicSourceDir;
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("application/vnd.android.package-archive");
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(appUri)));
startActivity(Intent.createChooser(sharingIntent, "Share via"));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top