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

来源:互联网 发布:discuz省市区数据库 编辑:程序博客网 时间:2024/06/07 17:07

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));//拉起ActivitystartActivity(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();    }});..............

0 0
原创粉丝点击