用于 Twitter 应用程序的 Android Intent

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2077008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:25:43  来源:igfitidea点击:

Android Intent for Twitter application

androidtwitterandroid-intent

提问by wouter88

Is it possible to show a list of applications (with intent.createChooser) that only show me my twitter apps on my phone (so htc peep (htc hero) or twitdroid). I have tried it with intent.settype("application/twitter")but it doesnt find any apps for twitter and only shows my mail apps.

是否可以显示intent.createChooser仅在我的手机上显示我的 twitter 应用程序的应用程序列表(带有)(因此 htc peep(htc hero)或 twitdroid)。我已经尝试过,intent.settype("application/twitter")但它没有找到任何适用于 twitter 的应用程序,并且只显示我的邮件应用程序。

Thank you,

谢谢,

Wouter

沃特

采纳答案by CommonsWare

It is entirely possible your users will only ever, now and forever, only want to post to Twitter.

完全有可能您的用户永远、现在和永远只想在 Twitter 上发帖。

I would think that it is more likely that your users want to send information to people, and Twitter is one possibility. But, they might also want to send a text message, or an email, etc.

我认为您的用户更有可能想要向人们发送信息,而 Twitter 是一种可能性。但是,他们可能还想发送短信或电子邮件等。

In that case, use ACTION_SEND, as described here. Twidroid, notably, supports ACTION_SEND, so it will appear in the list of available delivery mechanisms.

在这种情况下,使用ACTION_SEND,描述在这里。值得注意的是,Twidroid 支持ACTION_SEND,因此它将出现在可用交付机制列表中。

回答by Jonik

I'm posting this because I haven't seen a solution yet that does exactly what I want.

我发布这个是因为我还没有看到一个完全符合我想要的解决方案。

This primarily launches the official Twitter app, or if that is not installed, either brings up a "Complete action using..." dialog (like this) or directly launches a web browser.

这主要启动官方 Twitter 应用程序,或者如果未安装,则显示“使用...完成操作”对话框(如下所示)或直接启动网络浏览器。

For list of different parameters in the twitter.com URL, see the Tweet Button docs. Remember to URL encodethe parameter values. (This code is specifically for tweeting a URL; if you don't want that, just leave out the urlparam.)

有关 twitter.com URL 中不同参数的列表,请参阅推文按钮文档。请记住参数值进行URL 编码。(此代码专门用于发布 URL;如果您不想要那样,请省略url参数。)

// Create intent using ACTION_VIEW and a normal Twitter url:
String tweetUrl = String.format("https://twitter.com/intent/tweet?text=%s&url=%s",
        urlEncode("Tweet text"), 
        urlEncode("https://www.google.fi/"));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(tweetUrl));

// Narrow down to official Twitter app, if available:
List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
    if (info.activityInfo.packageName.toLowerCase().startsWith("com.twitter")) {
        intent.setPackage(info.activityInfo.packageName);
    }
}

startActivity(intent);

(URL encoding is cleaner if you have a little utility like this somewhere, e.g. "StringUtils".)

(如果您在某处有类似这样的小工具,例如“StringUtils”,则 URL 编码会更清晰。)

public static String urlEncode(String s) {
    try {
        return URLEncoder.encode(s, "UTF-8");
    }
    catch (UnsupportedEncodingException e) {
        Log.wtf(TAG, "UTF-8 should always be supported", e);
        throw new RuntimeException("URLEncoder.encode() failed for " + s);
    }
}

For example, on my Nexus 7 device, this directlyopens the official Twitter app:

例如,在我的 Nexus 7 设备上,这会直接打开官方 Twitter 应用程序

enter image description here

在此处输入图片说明

If official Twitter app is notinstalled and user either selects Chrome or it opens automatically (as the only app which can handle the intent):

如果官方 Twitter 应用程序安装且用户选择 Chrome 或自动打开(作为唯一可以处理意图的应用程序):

enter image description here

在此处输入图片说明

回答by Derzu

The solutions posted before, allow you to post directly on your first twitter app. To show a list of twitters app (if there are more then one), you can custom your Intent.createChooser to show only the Itents you want.

之前发布的解决方案允许您直接在您的第一个 Twitter 应用程序上发布。要显示 twitters 应用程序列表(如果有多个),您可以自定义您的 Intent.createChooser 以仅显示您想要的 Itents。

The trick is add EXTRA_INITIAL_INTENTS to the default list, generated from the createChoose, and remove the others Intents from the list.

诀窍是将 EXTRA_INITIAL_INTENTS 添加到从 createChoose 生成的默认列表中,并从列表中删除其他 Intent。

Look at this sample where I create a chooser that shows only my e-mails apps. In my case appears three mails: Gmail, YahooMail and the default Mail.

看看这个示例,我在其中创建了一个仅显示我的电子邮件应用程序的选择器。就我而言,出现了三封邮件:Gmail、YahooMail 和默认邮件。

private void share(String nameApp, String imagePath) {
    List<Intent> targetedShareIntents = new ArrayList<Intent>();
    Intent share = new Intent(android.content.Intent.ACTION_SEND);
    share.setType("image/jpeg");
    List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);
    if (!resInfo.isEmpty()){
        for (ResolveInfo info : resInfo) {
            Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
            targetedShare.setType("image/jpeg"); // put here your mime type

            if (info.activityInfo.packageName.toLowerCase().contains(nameApp) || 
                    info.activityInfo.name.toLowerCase().contains(nameApp)) {
                targetedShare.putExtra(Intent.EXTRA_TEXT,     "My body of post/email");
                targetedShare.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(imagePath)) );
                targetedShare.setPackage(info.activityInfo.packageName);
                targetedShareIntents.add(targetedShare);
            }
        }

        Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Select app to share");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
        startActivity(chooserIntent);
    }
}

You can run like that: share("twi", "/sdcard/dcim/Camera/photo.jpg");

你可以这样运行: share("twi", "/sdcard/dcim/Camera/photo.jpg");

This was based on post: Custom filtering of intent chooser based on installed Android package name

这是基于帖子:基于已安装的 Android 包名称的意图选择器的自定义过滤

回答by Alexander Rautenberg

This question is a bit older, but since I have just come across a similar problem, it may also still be of interest to others. First, as mentioned by Peter, create your intent:

这个问题有点老了,但由于我刚刚遇到了类似的问题,因此其他人可能仍然感兴趣。首先,正如彼得所提到的,创建你的意图:

Intent tweetIntent = new Intent(Intent.ACTION_SEND);
tweetIntent.putExtra(Intent.EXTRA_TEXT, "Test; please ignore");
tweetIntent.setType("application/twitter");

"application/twitter" is in fact a known content type, see here. Now, when you try to start an activity with this intent, it will show all sorts of apps that are not really Twitter clients, but want a piece of the action. As already mentioned in a couple of the "why do you even want to do that?" sort of answers, some users may find that useful. On the other hand, if I have a button in my app that says "Tweet this!", the user would very much expect this to bring up a Twitter client.

“application/twitter”实际上是一种已知的内容类型,请参见此处。现在,当您尝试以此意图启动 Activity 时,它会显示各种并非真正的 Twitter 客户端但想要参与其中的应用程序。正如在“你为什么要那样做?”中已经提到的那样。排序的答案,一些用户可能会觉得有用。另一方面,如果我的应用程序中有一个按钮,上面写着“Tweet this!”,用户会非常希望这会调出一个 Twitter 客户端。

Which means that instead of just launching an activity, we need to filter out the ones that are appropriate:

这意味着我们需要过滤掉合适的活动,而不是仅仅启动一个活动:

PackageManager pm = getPackageManager();
List<ResolveInfo> lract 
= pm.queryIntentActivities(tweetIntent,
    PackageManager.MATCH_DEFAULT_ONLY);

boolean resolved = false;

for(ResolveInfo ri: lract)
{
    if(ri.activityInfo.name.endsWith(".SendTweet"))
    {
        tweetIntent.setClassName(ri.activityInfo.packageName,
                        ri.activityInfo.name);
        resolved = true;
        break;
    }
}

You would need to experiment a bit with the different providers, but if the name ends in ".SendTweet" you are pretty safe (this is the activity name in Twidroyd). You can also check your debugger for package names you want to use and adjust the string comparison accordingly (i.e. Twidroyd uses "com.twidroid.*").

您需要对不同的提供者进行一些试验,但如果名称以“.SendTweet”结尾,您就很安全(这是 Twidroyd 中的活动名称)。您还可以检查调试器中要使用的包名称并相应地调整字符串比较(即 Twidroyd 使用“com.twidroid.*”)。

In this simple example we just pick the first matching activity that we find. This brings up the Twitter client directly, without the user having to make any choices. If there are no proper Twitter clients, we revert to the standard activity chooser:

在这个简单的例子中,我们只选择我们找到的第一个匹配活动。这会直接打开 Twitter 客户端,用户无需做出任何选择。如果没有合适的 Twitter 客户端,我们将恢复到标准活动选择器:

startActivity(resolved ? tweetIntent :
    Intent.createChooser(tweetIntent, "Choose one"));

You could expand the code and take into account the case that there is more than one Twitter client, when you may want to create your own chooser dialog from all the activity names you find.

您可以扩展代码并考虑到存在多个 Twitter 客户端的情况,当您可能希望根据您找到的所有活动名称创建自己的选择器对话框时。

回答by MSpeed

These answers are all overly complex.

这些答案都过于复杂。

If you just do a normal url Intent that does to Twitter.com, you'll get this screen:

如果你只是对 Twitter.com 执行一个普通的 url Intent,你会看到这个屏幕:

enter image description here

在此处输入图片说明

which gives you the option of going to the website if you have no Twitter apps installed.

如果您没有安装 Twitter 应用程序,您可以选择访问该网站。

String url = "https://twitter.com/intent/tweet?source=webclient&text=TWEET+THIS!";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

回答by rds

Either

任何一个

  • You start an activity with an Intent with action Intent.ACTION_SENDand the text/plainMIME type. You'll have all applications that support sending text. That should be any twitter client, as well as Gmail, dropbox, etc.
  • Or, you try to look up for the specific actionof every client you are aware of, like "com.twitter.android.PostActivity" for the official client. That will point to this client, and that is unlikely to be a complete list.
  • Or, you start with the second point, and fall back on the first...
  • 你开始一个带有动作的意图Intent.ACTION_SENDtext/plainMIME 类型的活动。您将拥有所有支持发送文本的应用程序。那应该是任何 Twitter 客户端,以及 Gmail、Dropbox 等。
  • 或者,您尝试查找您知道的每个客户端的特定操作,例如官方客户端的“com.twitter.android.PostActivity”。这将指向这个客户,这不太可能是一个完整的列表。
  • 或者,你从第二点开始,然后回到第一点......

回答by Mirko N.

Nope. The intent type is something like image/pngor application/pdf, i.e. a file type, and with createChooser you're basically asking which apps can open this file type.

不。Intent 类型类似于image/pngor application/pdf,即一种文件类型,使用 createChooser 您基本上是在询问哪些应用程序可以打开这种文件类型。

Now, there's no such thing as an application/twitterfile that can be opened, so that won't work. I'm not aware of any other way you can achieve what you want either.

现在,没有application/twitter可以打开的文件之类的东西,所以这是行不通的。我不知道您还有其他任何方式可以实现您想要的目标。

回答by Peter

From http://twidroid.com/plugins/

来自http://twidroid.com/plugins/

Twidroid's ACTION_SEND intent

Twidroid 的 ACTION_SEND 意图

Intent sendIntent = new Intent(Intent.ACTION_SEND); 
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is a sample message via Public Intent"); 
sendIntent.setType("application/twitter");   
startActivity(Intent.createChooser(sendIntent, null)); 

回答by echappy

I used "billynomates" answer and was able to use hashtags by using the "URLEncoder.encode(, "UTF-8")" function. The hash tags showed up just fine.

我使用了“billynomates”答案,并且能够通过使用“URLEncoder.encode(,“UTF-8”)”函数来使用主题标签。哈希标签显示得很好。

String originalMessage = "some message #MESSAGE";

String originalMessageEscaped = null;
try {
   originalMessageEscaped = String.format(
    "https://twitter.com/intent/tweet?source=webclient&text=%s",
    URLEncoder.encode(originalMessage, "UTF-8"));
} catch (UnsupportedEncodingException e) {
   e.printStackTrace();
}

if(originalMessageEscaped != null) {
   Intent i = new Intent(Intent.ACTION_VIEW);
   i.setData(Uri.parse(originalMessageEscaped));
   startActivity(i);
}
else {
   // Some Error
}