【问题标题】:How to open browser and youtube app with the title as URL in android with intent create chooser如何使用意图创建选择器在android中打开标题为URL的浏览器和youtube应用程序
【发布时间】:2019-03-23 09:16:10
【问题描述】:

我正在制作一个 android 音乐播放器应用程序,我想在其中添加搜索功能,这就是为什么我需要像这样实现:

我想搜索歌曲名称并为 youtube 和所有已安装的浏览器创建带有歌曲标题而不是 url 的选择器

我想我无法描述我的问题,所以请看下面的内容可能会帮助你理解:-

Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("https://stackoverflow.com/"));
//here i want to set like that intent.setData("my song title")
            startActivity(Intent.createChooser(intent,"search")); 

但如果我这样做,它会告诉我 - 没有应用程序可以执行此操作

所以我不知道如何将标题作为 url 放在意图中

请记住该用户也可以在 youtube 上搜索此内容

【问题讨论】:

    标签: android android-intent audio-player android-music-player


    【解决方案1】:

    您可以使用查询开始两个单独的搜索,如下所示:

    Youtube 搜索

    Intent intent = new Intent(Intent.ACTION_SEARCH);
    intent.setPackage("com.google.android.youtube");
    intent.putExtra(SearchManager.QUERY, "Sunday Bloody Sunday");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    

    浏览器搜索

    Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
    intent.putExtra(SearchManager.QUERY, "Sunday Bloody Sunday");
    startActivity(intent);
    

    请注意,如果这首歌是众所周知的,浏览器搜索的第一个结果将是 Youtube 视频。

    编辑

    这里是自动为 Youtube 和浏览器创建搜索查询:

    private void startSearchIntent(String query) {
        List<Intent> browserIntents = new ArrayList<>();
        // Find browser intents
        List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(new Intent(Intent.ACTION_WEB_SEARCH), 0);
    
        // Create a search intent for each browser that was found
        for (ResolveInfo info : resInfo) {
            Intent browserIntent = new Intent(Intent.ACTION_WEB_SEARCH);
            browserIntent.putExtra(SearchManager.QUERY, query);
            browserIntent.setPackage(info.activityInfo.packageName.toLowerCase());
            browserIntents.add(browserIntent);
        }
    
        // Create Youtube Intent
        Intent youtubeIntent = new Intent(Intent.ACTION_SEARCH);
        youtubeIntent.setPackage("com.google.android.youtube");
        youtubeIntent.putExtra(SearchManager.QUERY, query);
        youtubeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    
        Intent chooserIntent = Intent.createChooser(youtubeIntent, query);
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, browserIntents.toArray(new Parcelable[]{}));
        startActivity(chooserIntent);
    
    }
    

    然后你只需要调用方法:

    startSearchIntent("Sunday Bloody Sunday");
    

    希望对你有帮助。

    【讨论】:

    • 是的,哥们,它帮了我很多,但不满足我的问题,请看上面的图片,它显示了多种不同类型的搜索应用程序
    • 查看我编辑的答案,我添加了您要查找的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    • 2016-03-04
    相关资源
    最近更新 更多