您的位置:首页 > 产品设计 > UI/UE

Android中隐式Intent及支持库中的IntentBuilder使用示例

2017-02-21 10:33 323 查看
Android 5.0以后,不能以隐式Intent的方式启动Service,

但仍然可以用隐式Intent来启动Activity。

对应的代码类似于:

..........
//指定动作
Intent i = new Intent(Intent.ACTION_SEND);

//指定数据类型
i.setType("text/plain");

//放入数据
i.putExtra(Intent.EXTRA_TEXT, getCrimeReport());
i.putExtra(Intent.EXTRA_SUBJECT,
getString(R.string.crime_report_subject));

//隐式Intent可能被多个Activity响应,因此可以显示创建一个选择器
i = Intent.createChooser(i, getString(R.string.send_report));

//拉起Activity
startActivity(i);
..........


上面的内容比较容易,我们主要看看Intent的createChooser方法:

public static Intent createChooser(Intent target, CharSequence title) {
return createChooser(target, title, null);
}

public static Intent createChooser(Intent target, CharSequence title, IntentSender sender) {
//实际上就是显示的拉起Chooser
Intent intent = new Intent(ACTION_CHOOSER);

//将目的Intent当作数据放入chooser
intent.putExtra(EXTRA_INTENT, target);

//chooser将处理title信息
if (title != null) {
intent.putExtra(EXTRA_TITLE, title);
}

//根据target中的信息,进一步调整intent
.............

return intent;
}


从这段代码可以看出,显示创建选择器,其实就是显示的拉起系统的Chooser Activity,

不过可以自己定制Chooser Activity的title(个人测试,并不是每个厂商的机器都可以完成定制功能)。

P.S. :

对于构建发送信息的Intent而言,Android的兼容库中定义了ShareCompat.IntentBuilder类。

Android的支持文档中,对应的描述如下:

IntentBuilder is a helper for constructing ACTION_SEND and ACTION_SEND_MULTIPLE sharing intents and starting activities to share content.

The ComponentName and package name of the calling activity will be included.

对于上述的代码,使用IntentBuilder的示例代码如下:

.............
mReportButton = (Button) v.findViewById(R.id.crime_report);
mReportButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ShareCompat.IntentBuilder intentBuilder = ShareCompat.IntentBuilder.from(getActivity());
intentBuilder.setType("text/plain");
intentBuilder.setSubject(getString(R.string.crime_report_subject));
intentBuilder.setText(getCrimeReport());
intentBuilder.setChooserTitle(R.string.send_report);
//通过chooser来拉起真正的目的Activity
intentBuilder.startChooser();
}
});
..............
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: