【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之间传递一些数据,之前做的都是些字符 ...
随机推荐
- [c#.net]遍历一个对象中所有的属性和值
利用反射 SpDictItem sp = GetCFHObject.GetSpItem("); PropertyInfo[] propertys = sp.GetType().GetProp ...
- Python_day8
多态 class Animal(object): def run(self): print('animal is running') class Dog(Animal): def run(self): ...
- 线程中的join方法
join方法的作用是同步线程. 1.不使用join方法:当设置多个线程时,在一般情况下(无守护线程,setDeamon=False),多个线程同时启动,主线程执行完,会等待其他子线程执行完,程序才会退 ...
- 基于接口的 InvocationHandler 动态代理(换种写法)
InvocationHandler is the interface implemented by the invocation handler of a proxy instance. Each p ...
- Think twice before starting the adventure
杂文一篇. 1. 取名字真心是一件特别困难的事情.这位独立开发者花了将近两天的时间,给他的私人项目取了个名字:这篇博客<为何我不鸟你的开源项目>里显然还忽视了一个原因,就是名字取得太烂以至 ...
- Matlib
>>> name1=input('请输入第一个名字;') 请输入第一个名字;陈汉彬 >>> name2=input('请输入第二个名字;') 请输入第二个名字;钟宇 ...
- HTML5元素标记释义
HTML5元素标记释义 标记 类型 意义 介绍 文件标记 <html> ● 根文件标记 让浏览器知道这是HTML 文件 META标记 <head> ● 开头 提供文件整体信息 ...
- 不适合使用hadoop来解决的问题
1.Hadoop能解决的问题必须是可以mapreduce的.一是问题可以拆分,二是子问题必须独立.比如斐波那契数列就不适合. 2.数据结构不满足key-value形式的.比如结构化的数据查询. 3.不 ...
- jsp页面时间戳转换为时间格式
jstl中格式化时间戳 在jsp页面中使用jstl标签将long型的时间戳转换为格式化后的时间字符串 1.通过<jsp:useBean /> 导入java.util.Date类2.通过 ...
- Spring Boot使用AOP实现REST接口简易灵活的安全认证
我们继续上一篇文章的分析,本文将通过AOP的方式实现一个相对更加简易灵活的API安全认证服务. 我们先看实现,然后介绍和分析AOP基本原理和常用术语. 一.Authorized实现 1.定义注解 pa ...