【Android基础】利用Intent在Activity之间传递数据
前言:
从一个Activity获取返回结果:
启动一个Activity不仅仅是startActivity(Intent intent)一种方法,你也可以通过startActivityForResult()启动一个Activity并且在它退出的时候收到一个返回结果。
比如,你可以调用系统相机在你的应用中,拍了一张照片,然后返回到你的Activity,这个时候就可以通过这种方法把照片作为结果返回给你的Activity。再比如,你可以通过这种方法启动系统联系人应用,然后获取一个人的详细联系方式。
注意:在调用startActivityForResult()时你可以利用显示Intent或者隐式Intent,但是在你能够利用显式Intent的时候尽量利用显式Intent,这样能够保证返回的结果是你期待的正确结果。
启动一个Activity:
在用startActivityForResult()来启动一个Activity时,Intent的写法与startActivity()是一样的,没有任何区别,只是你需要传递一个额外的Integer的变量作为启动参数,当启动的那个Activity退出时这个参数会被作为回调函数的一个参数,用来区分返回结果,也就是说你启动Activity时传递的参数(requestCode)和返回结果时的那个参数(requestCode)是一致的。
下面是一个调用startActivityForResult()获取联系人的例子:
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);
}
startActivityForResult()函数在Activity源码中是这样的:
/**
* Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
* with no options.
*
* @param intent The intent to start.
* @param requestCode If >= 0, this code will be returned in
* onActivityResult() when the activity exits.
*
* @throws android.content.ActivityNotFoundException
*
* @see #startActivity
*/
public void startActivityForResult(Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
- 这个方法只能用来启动一个带有返回结果的Activity,Intent的参数设定需要注意一下,你不能启动一个Activity使用singleTask的launch mode,用singleTask启动Activity,那个Activity在另外的一个Activity栈中,你会立刻收到RESULT_CANCELED消息;
- 不能在Activity生命周期函数onResume之前调用startActivityForResult()方法,如果你在onResume之前调用了,那么所在的Activity就无法显示,直到启动的那个Activity退出然后返回结果,这是为了避免在重新定向到另外Activity时窗口闪烁;
接收返回结果:
当startActivityForResult()启动的Activity完成任务退出时,系统会回调你调用Activity的onActivityResult()方法,这个方法有三个参数:
- resquestCode : 启动Activity时传递的requestCode;
- resultCode: 表示调用成功或者失败的变量,值为下面二者之一;
/** Standard activity result: operation canceled. */public static final int RESULT_CANCELED = 0;/** Standard activity result: operation succeeded. */public static final int RESULT_OK = -1;
- Intent:包含返回内容的Intent;
@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) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected. // Do something with the contact here (bigger example below)
}
}
}
注意:为了正确的处理返回的Intent结果,你需要清楚的了解Intent返回结果的格式。如果是你自己写的Intent作为返回结果你会很清楚,但是如果是调用的系统APP(相机,联系人等),那么Intent返回结果格式你应该清楚的知道。比如:联系人应用是返回的联系人URI,相机返回的是Bitmap数据。
处理返回结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that 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...
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
获取启动Intent:
在被启动的Activity中你可以接收启动这个Activity的Intent,在生命周期范围内都能调用getIntent()来获取这个Intent,但是一般都是在onCreat和onStart函数中获取,下面就是一个获取Intent的例子:
@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 ...
}
}
设置返回Intent:
上面介绍了怎么在onActivityResult()中处理Intent,但是怎么在你的应用中设置这个返回Intent呢?如果你想给调用你的Activity返回一个结果可以通过调用setResult()设置返回内容,然后结束这个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();
以上就是使用Intent在不同Activity进行信息传递和沟通的讲解,到此Intent系列文章完结,前两篇文章是关于Intent详解和Intent使用的文章,有什么不明白的请留言,大家共同学习,共同进步,谢谢!
大家如果对编程感兴趣,想了解更多的编程知识,解决编程问题,想要系统学习某一种开发知识,我们这里有java高手,C++/C高 手,windows/Linux高手,android/ios高手,请大家关注我的微信公众号:程序员互动联盟or coder_online,大牛在线为您提供服务。

【Android基础】利用Intent在Activity之间传递数据的更多相关文章
- android中使用Intent在activity之间传递数据
android中intent传递数据的简单使用: 1.使用intent传递数据: 首先将需要传递的数据放入到intent中 Intent intent = new Intent(MainActivit ...
- 【Android 复习】 : Activity之间传递数据的几种方式
在Android开发中,我们通常需要在不同的Activity之间传递数据,下面我们就来总结一下在Activity之间数据传递的几种方式. 1. 使用Intent来传递数据 Intent表示意图,很多时 ...
- Android 笔记-Fragment 与 Activity之间传递数据
Fragment 与 Activity之间传递数据有两种方法.一种是使用setArgument,一种是使用接口回调.以下先学习第一种方法. (1)使用setArgument方法: 为了便于理解,我在这 ...
- Activity之间传递数据或数据包Bundle,传递对象,对象序列化,对象实现Parcelable接口
package com.gaojinhua.android.activitymsg; import android.content.Intent; import android.os.Bundle; ...
- 28、activity之间传递数据&批量传递数据
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android ...
- 在activity之间传递数据
在activity之间传递数据 一.简介 二.通过intent传递数据 1.在需要传数据的界面调用 intent.putExtra("data1", "我是fry&quo ...
- Activity之间传递数据的方式及常见问题总结
Activity之间传递数据一般通过以下几种方式实现: 1. 通过intent传递数据 2. 通过Application 3. 使用单例 4. 静态成员变量.(可以考虑 WeakReferences) ...
- Android中如何使用Intent在Activity之间传递对象[使用Serializable或者Parcelable]
http://blog.csdn.net/cjjky/article/details/6441104 在Android中的不同Activity之间传递对象,我们可以考虑采用Bundle.putSeri ...
- Android基础 -- Activity之间传递数据(bitmap和map对象)
原文:http://blog.csdn.net/xueerfei008/article/details/23046341 做项目的时候需要用到在2个activity之间传递一些数据,之前做的都是些字符 ...
随机推荐
- 从零开始学java (四)反射
反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意一个方法和属性:这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制. ...
- [C#.net]获取文本文件的编码,自动区分GB2312和UTF8
昨天生产突然反馈上传的结果查询出现了乱码,我赶紧打开后台数据库,发现果真有数据变成了乱码.这个上传程序都运行3个多月了,从未发生乱码现象,查看程序的运行日志,发现日志里的中文都变成了乱码,然后对比之前 ...
- JupyterLab绘制:柱状图,饼状图,直方图,散点图,折线图
JupyterLab绘图 喜欢python的同学,可以到 https://v3u.cn/(刘悦的技术博客) 里面去看看,爬虫,数据库,flask,Django,机器学习,前端知识点,JavaScrip ...
- 第48章:MongoDB-备份和恢复
①文件系统快照(snapshot) 生成文件系统快照这个方法需要满足两个条件: 1:文件系统本身支持快照技术 2:运行mongod时必须开启日记系统 其恢复就是快照的恢复,当然,恢复的时候,确保mon ...
- WebServices 注解汇总
Web Service 元数据注释 @WebService 1.serviceName: 对外发布的服务名,指定 Web Service 的服务名称:wsdl:service.缺省值为 Java 类的 ...
- Docker优势以及与传统虚拟机对比(1)
docker优势 1.更快速地交付和部署: 2.更高的虚拟化(不需要额外的hypervisor支持,是内核级的虚拟化,实现更高的性能呢和效率): 3.更轻松的迁移和扩展: 4.更简单的管理 与传统的 ...
- C++ Thrift服务端记录调用者IP和被调接口方法
Apache开源的Thrift(http://thrift.apache.org)有着广泛的使用,有时候需要知道谁调用了指定的函数,比如在下线一起老的接口之前,需要确保对这些老接口的访问已全部迁移到新 ...
- 汇总java生态圈常用技术框架、开源中间件,系统架构及经典案例等
转自:http://www.51testing.com/html/83/n-3718883.html 有人认为编程是一门技术活,要有一定的天赋,非天资聪慧者不能及也.非也,这是近几年,对于技术这碗饭有 ...
- jquery综合
1.选择器性能比较: http://www.jcodecraeer.com/a/javascript/2012/0418/112.html http://developer.51cto.com/art ...
- 洛谷P1064--金明的预算方案(简单背包)
https://www.luogu.org/problemnew/show/P1064 #include<iostream> #include<algorithm> #incl ...