《安卓开发官方文档》学习笔记五使用intent与其他activity交互

     《安卓开发官方文档》学习笔记五使用intent与其他activity交互

文章开始把我喜欢的这句话送个大家:这个世界上还有什么比自己写的代码运行在一亿人的电脑上更酷的事情吗,如果有那就是让这个数字再扩大十倍

intent

使用intent来在同一个app的两个activity行切。通常是定一个式(explicit)的intent,它指定了需要启动组件的名。然而,当想要起不同的app行某个作(比如看地),使用implicit)的intent

 

emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"jon@example.com"});

//(键,值)

警告:如果触了一个意,而且没有任何一个app会去接收个意app会崩

为了验证是否有合适的活动会响应这个目的,需要执queryIntentActivities()取到能接收个意的所有活的列表若返回的

PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
boolean isIntentSafe = activities.size() > 0;

使用intent启

startActivity(intent);完整例子:
// Build the intent
Uri location = Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);

// Verify it resolves
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(mapIntent, 0);
boolean isIntentSafe = activities.size() > 0;

// Start an activity if it's safe
if (isIntentSafe) {
    startActivity(mapIntent);
}

为了显示选择器,需要使createChooser()建意

Intent intent = new Intent(Intent.ACTION_SEND);
...

// Always use string resources for UI text. This says something like "Share this photo with"
String title = getResources().getText(R.string.chooser_title);
// Create and start the chooser
Intent chooser = Intent.createChooser(intent, title);
startActivity(chooser);

接收Activity返回的

另外一个activity并不一定是向的。我也可以启另外一个activity然后接受一个返回的result为接受result,我需要使用startActivityForResult()而不是startActivity()

activity需要在onActivityResult()的回方法里面去接收result

对于startActivityForResult() 方法中的intent与之前介绍的并无太大差异,不过是需要在这个方法里面多添加一个int类型的参数。integer参数称"request code",用于标识请。当我接收到result Intent时,可从回调方法里面的参数去判断这个result是否是我想要的。

static final int PICK_CONTACT_REQUEST = 1;  // The request code
...
private void pickContact() {
    Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
    pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
    startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == PICK_CONTACT_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // Get the URI that points to the selected contact
            Uri contactUri = data.getData();
            // We only need the NUMBER column, because there will be only one row in the result
            String[] projection = {Phone.NUMBER};

            // Perform the query on the contact to get the NUMBER column
            // We don't need a selection or sort order (there's only one result for the given URI)
            // CAUTION: The query() method should be called from a separate thread to avoid blocking
            // your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
            // Consider using CursorLoader to perform the query.
            Cursor cursor = getContentResolver()
                    .query(contactUri, projection, null, null, null);
            cursor.moveToFirst();

            // Retrieve the phone number from the NUMBER column
            int column = cursor.getColumnIndex(Phone.NUMBER);
            String number = cursor.getString(column);

            // Do something with the phone number...
        }
    }
}

接收方intent

当用在其他app分享功能的候,我app在待选对话框。

manifest文件中的<activity>标签下添<intent-filter>的属性,使其他的appactivity

activity中的intent filter满足以下intent对象的标准,系统就能够把特定的intent发送给activity

  • Action:一个想要执行的动作的名称。通常是系统已经定义好的值,如ACTION_SENDACTION_VIEWintent filter中通过<action>指定它的值,值的类型必须为字符串,而不是API中的常量(看下面的例子)
  • Data:Intent附带数据的描述。在intent filter中通过<data>指定它的值,可以使用一个或者多个属性,我们可以只定义MIME type或者是只指定URI prefix,也可以只定义一个URI scheme,或者是他们综合使用。

Note: 如果不想handle Uri 类型的数据,那么应该指定android:mimeType 属性。例如text/plain or image/jpeg.

  • Category:提供一个附加的方法来标识这个activity能够handle的intent。通常与用户的手势或者是启动位置有关。系统有支持几种不同的categories,但是大多数都很少用到。而且,所有的implicit intents都默认是CATEGORY_DEFAULT 类型的。在intent filter中用<category>指定它的值。

 

<activity android:name="ShareActivity">
    <intent-filter>
        <action android:name="android.intent.action.SEND"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:mimeType="text/plain"/>
        <data android:mimeType="image/*"/>
    </intent-filter>
</activity>

为了接受implicit intents,在我intent filter中包含CATEGORY_DEFAULTcategory。如果没有在的intent filter中声明CATEGORY_DEFAULTactivity将无法implicit intent做出响

 

ActivityHandle发送过来的Intent

为了决定采用哪个action,我们可以读取Intent的内容。

可以执行getIntent()来获取启动我们activity的那个intent。我们可以在activity生命周期的任何时候去执行这个方法,但最好是在onCreate()或者onStart()里面去执行。@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    // Get the intent that started this activity
    Intent intent = getIntent();
    Uri data = intent.getData();

    // Figure out what to do based on the intent type
    if (intent.getType().indexOf("image/") != -1) {
        // Handle intents with image data ...
    } else if (intent.getType().equals("text/plain")) {
        // Handle intents with text ...
    }
}

Note:没有必要在意自己的activity是被用startActivity()还是startActivityForResult()方法所叫起的。系会自去判断如何传递result。在不需要的resultcase下,result会被自忽略。

返回Result

如果想返回一个result给启动的那个activity,仅仅需要执行setResult(),通过指定一个result coderesult intent。操作完成之后,用户需要返回到原来的activity,通过执行finish() 关闭被唤起的activity

// Create intent to deliver some kind of result data
Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_uri");
setResult(Activity.RESULT_OK, result);
finish();

Note:没有必要在意自己的activity是被用startActivity() 还是startActivityForResult()方法所叫起的。系会自去判断如何传递result。在不需要的resultcase下,result会被自忽略。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值