要求:
我的应用程序中有一个“分享”按钮。我需要通过 Facebook 分享。我需要选择是否安装原生 Facebook 应用程序。我们的决定是,如果未安装该应用程序,则将用户发送到 facebook.com 进行分享。
目前状态:
我可以检测何时未安装本机应用程序(通过包名称),并向选择器添加其他意图。
问题:
用户必须选择通过“Facebook 网站”共享的项目显示“浏览器”并具有 Android 浏览器图标。 LabeledIntent 项目未出现,并且我收到“未找到 Intent { act=android.intent.action.VIEW dat=...} 的活动”
代码(简化...):
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_SUBJECT, "check this out");
intent.putExtra(Intent.EXTRA_TEXT, urlToShare);
boolean facebookInstalled = false;
Intent chooser = Intent.createChooser(intent, "Share this link!");
if (!facebookInstalled)
{
Intent urlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.facebook.com/sharer/sharer.php?u=" + Uri.encode(urlToShare)));
Intent niceUrlIntent = new LabeledIntent(urlIntent, context.getApplicationContext().getPackageName(), "Facebook's Website", R.drawable.icon);
// Ideally I would only add niceUrlIntent in the end, but that doesn't add anything to the chooser as-is
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[urlIntent, niceUrlIntent]);
}
context.startActivity(chooser);
解决方案
@CommonsWare 指出的解决方案是使用 LabeledIntent 来包装一个发送到我创建的新 Activity 的意图,该意图只需将 ACTION_VIEW 意图发送到适当的 Uri。
Intent myActivity = new Intent(context, ViewUriActivity.class);
myActivity.putExtra(ViewUriActivity.EXTRA_URI, "http://...");
Intent niceUrlIntent = new LabeledIntent(myActivity, context.getApplicationContext().getPackageName(), "Facebook's Website", R.drawable.icon);
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{niceUrlIntent});
ViewUriActivity 看起来像这样:
public final class ViewUriActivity extends Activity
{
public static final String EXTRA_URI = ViewUriActivity.class.getSimpleName() + "EXTRA_URI";
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent urlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getIntent().getExtras().getString(EXTRA_URI)));
startActivity(urlIntent);
finish();
}
}
虽然没有记录,但看起来 LabeledIntents 只适用于已解析的 Intents。因此,除非意图已经定义了特定的活动和包,否则您将无法使用它。
这并不奇怪,因为可能有许多 Activity 可能会针对一个 LabeledIntent 得到解析,并且您的选择器Activity 将显示相同的所有图标和名称。
因此,在您的情况下,您必须首先解决活动,然后使用 LabeledIntent。但这可能会导致用户无法选择自己喜欢的浏览器。 使用下面的函数从您的意图中获取 LabeledIntent。
Intent urlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.facebook.com/sharer/sharer.php?u=" + Uri.encode(urlToShare)));
Intent niceUrlIntent = getLabelintent(urlIntent, "Facebook's Website", R.drawable.icon);
并获取LabelIntent
public LabeledIntent getLabelintent(Intent in, String name, int drawable) {
PackageManager pm = getPackageManager();
ComponentName launchname = in.resolveActivity(pm);
if (launchname != null) {
Intent resolved = new Intent();
resolved.setComponent(launchname);
resolved.setData(in.getData());
LabeledIntent niceUrlIntent = new LabeledIntent(resolved,
getPackageName(), name, drawable);
return niceUrlIntent;
}
return null;
}