Search code examples
androidandroid-intentbittorrent

Android: torrent intent


I have a couple of apps installed to download torrents (Ttorrent, UTorrent etc..) but when I run this code in my app

    Intent i = new Intent(Intent.ACTION_VIEW);
    i.addCategory(Intent.CATEGORY_DEFAULT);
    i.setType("application/x-bittorrent");
    i.setData(Uri.parse(movie.getTorrentUrl()));
    startActivity(Intent.createChooser(i, "view"));

I get "no apps can perform this action" dialog.


Solution

  • I solved getting an intent for every app that can handle my action, and then I perform some filters based on intent package name (in my case I check if the package contains "torrent" word). Here the code:

      public Intent generateTorrentIntent(Context context, String action, Intent intent) {
        final PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        if (resolveInfo.size() > 0) {
            List<Intent> targetedShareIntents = new ArrayList<Intent>();
            for (ResolveInfo r : resolveInfo) {
                Intent progIntent = (Intent)intent.clone();
                String packageName = r.activityInfo.packageName;
    
                progIntent.setPackage(packageName);
                if (r.activityInfo.packageName.contains("torrent"))
                    targetedShareIntents.add(progIntent);
    
            }
            if (targetedShareIntents.size() > 0) {
                Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0),
                        "Select app to share");
    
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
                        targetedShareIntents.toArray(new Parcelable[] {}));
    
                return chooserIntent;
            }
        }
        return null;
    }