问题 1
在描述中,他们只显示了要放入清单中的内容,并提到使用“ChooserTargetService”。为了提供文本和图像应该做什么?
从扩展开始ChooserTargetService
。您需要返回 a List
ofChooserTarget
以及如何创建这些目标完全取决于您。
public class YourChooserTargetService extends ChooserTargetService {
@Override
public List<ChooserTarget> onGetChooserTargets(ComponentName targetActivityName, IntentFilter matchedFilter) {
final List<ChooserTarget> targets = new ArrayList<>();
for (int i = 0; i < length; i++) {
// The title of the target
final String title = ...
// The icon to represent the target
final Icon icon = ...
// Ranking score for this target between 0.0f and 1.0f
final float score = ...
// PendingIntent to fill in and send if the user chooses this target
final PendingIntent action = ...
targets.add(new ChooserTarget(title, icon, score, action));
}
return targets;
}
}
AndroidManifest
现在你需要在你的中声明你ChooserTargetService
的AndroidManifest
并做两件事:
- 绑定
Service
使用android.permission.BIND_CHOOSER_TARGET_SERVICE
权限
IntentFilter
在android.service.chooser.ChooserTargetService
动作中包含一个
例如:
<service
android:name=".YourChooserTargetService"
android:label="@string/yourLabel"
android:permission="android.permission.BIND_CHOOSER_TARGET_SERVICE">
<intent-filter>
<action android:name="android.service.chooser.ChooserTargetService" />
</intent-filter>
</service>
在Activity
要处理的 中Intent
,您需要添加meta-data
标签android.service.chooser.chooser_target_service
。例如:
<activity android:name=".YourShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<meta-data
android:name="android.service.chooser.chooser_target_service"
android:value=".YourChooserTargetService" />
</activity>
从这里开始,如果用户选择您的应用程序,则主要是调用Intent.createChooser
然后处理数据的问题。
final Intent target = new Intent(Intent.ACTION_SEND);
target.setType("text/plain");
target.putExtra(Intent.EXTRA_TITLE, "Your title");
target.putExtra(Intent.EXTRA_TEXT, "Your text");
startActivity(Intent.createChooser(target, "ChooserTargetService Example"));
结果

注意事项
每个排名分数用于ChooserTarget
对目标进行排序,但仅在 UI 决定使用它时使用。按照ChooserTarget.getScore
在对来自多个源的目标进行排序和合并时,显示目标的 UI可能会考虑此分数
此外,据我所知,此功能实际上尚未在 Android MNC 预览版中实现。ChooserActivity
包含一个它TODO
:
TODO:按排名分数保持排序
创建一个 newandroid.graphics.drawable.Icon
时,您需要使用其中一个static
初始化程序。
Icon.createWithBitmap();
Icon.createWithContentUri()
Icon.createWithData()
Icon.createWithFilePath()
Icon.createWithResource()
问题2
我想知道如何做相反的事情:如何查询所有这些“直接共享”项目(图像、文本和意图)并能够在自定义对话框中显示它们?
提供给的数据ChooserTargetService.onGetChooserTargets
是动态的。因此,据我所知,没有直接的方法可以访问这些项目。