Interacting with Other Apps

http://www.cnblogs.com/gcg0036/p/4321279.html

Build an Implicit Intent:

implicit Intent不声明要调用的类的组件的具体名称,只声明要执行的动作

通常也包含和action有关的数据

1.如果你的数据是URI,可以使用一个很简单的Intent()构造器,来定义action和data

Uri number = Uri.parse("tel:5551234");
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);

当你的应用通过调用startActivity()引用上面这个intent的时候,拨号应用就会拨打上面这个电话了。

2.其他implicit intent可能需要“extra”数据来提供不同的数据类型,比如一个string类型,我们可以使用很多种重载的putExtra ()添加一种或几种额外的数据

默认情况下:系统根据包含的Uri数据来为intent选择合适的MIME类型。如果intent不包含Uri,就需要使用setType()来指定intent所关联的数据类型。确定MIME类型进一步确定了哪一种activity可以接收这个intent。

Intent calendarIntent = new Intent(Intent.ACTION_INSERT, Events.CONTENT_URI);
Calendar beginTime = Calendar.getInstance().set(2012, 0, 19, 7, 30);
Calendar endTime = Calendar.getInstance().set(2012, 0, 19, 10, 30);
calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis());
calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis());
calendarIntent.putExtra(Events.TITLE, "Ninja class");
calendarIntent.putExtra(Events.EVENT_LOCATION, "Secret dojo");

注意:定义的intent越具体越好,如果你想浏览图片,通过ACTION_VIEW intent,你就需要指定MIME类型为image/*,这样可以防止用于访问其他类型数据的app(比如地图app)被这个intent所激发。因为你指定了MIME类型以后,其他app因为数据类型不一致,所以不会被这个intent所trigger了。

尽管系统平台会将特定的intent对应到内置的app,但是在引用一个intent之前,最好还是验证一下是否可用。

因为如果你引用了一个没有app能对其响应的intent的时候,后果很严重,app会崩溃

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

注意: 当你的activity第一次启动的时候,你需要做这个检查,从而可以屏蔽一些功能,因为这些功能没有activity响应这些功能发出的intent。这样就可以避免app的crash。如果你知道是什么app可以handle这个你app里无法handle的intent的话,你还可以提供Google Play里的下载链接。

Start an Activity with the Intent:

build好一个intent,并且录入了相关信息以后,可以调用startActivity()方法,就可以向系统发送这个intent啦。如果系统发现不止一个app可以handle这个 intent的时候,系统就会提供一个列表来让你选择,如果只有一个的话,就不用选择啦,那就直接启动了。

下面代码是一个查看地图的完整代码:包括新建intent,验证是否有handle它的activity,启动等

// 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);
}

Getting a Result from an Activity:

注意:当你调用startActivityForResult()方法时,明确的和隐藏的intent都可以使用,但是用来接受其他activity返回结果的activity,必须使用明确的intent,以确保它接收到。

以下代码是选取一个联系人的activity,返回一个contact:

static final int PICK_CONTACT_REQUEST = 1;  // The request code
...
private void pickContact() {
    Intent pickContactIntent = new Intent(Intent.ACTION_PICK, new Uri("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) {
            // The user picked a contact.
            // The Intent‘s data Uri identifies which contact was selected.

            // Do something with the contact here (bigger example below)
        }

比如,联系人app返回选定的联系人信息contact URI作为结果,camera返回一个Bitmap作为结果。

Handle the Intent in Your Activity

@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 ...
    }
}

如果想要使自己的activity返回一个值,只需要调用setResult()方法来指定result code和result intent 就可以。当用户在这个activity里操作完毕以后,就需要返回原来的activity了,调用finish()方法就可以关闭这个activity,回到原来的。

// Create intent to deliver some kind of result data

//两个参数:1.result code即Activity.RESULT_OK  2. result intent  默认值是RESULT_CANCELED

Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_uri");
setResult(Activity.RESULT_OK, result);
finish();

没有必要检验你的activity是用哪个方法启动的,有没有返回值都一样,都用 setResult()设置好返回值,如果本来的activity使用需要返回值的方法startActivityForResult()来调用你的 activity,则就按照设置好的返回值返回给它,如果用 startActivity()调用你的activity,则就当没设置返回值一样,直接忽略原来设置的返回值就行。

http://blog.sina.com.cn/s/blog_8191005601019yci.html

时间: 2024-07-29 01:20:20

Interacting with Other Apps的相关文章

跟Google学写代码:Interacting with Other Apps【Capture Photo from phone】

本文概述 翻译Interacting with Other Apps相关课程,并通过复习该文档的知识,完成如下功能: 与其他应用交互 我们开发的Android 应用一般具有若干个Activity.每个Activity显示一个用户界面,用户可通过该界面执行特定任务(比如,查看地图或拍照).要将用户从一个Activity转至另一Activity,必须使用 Intent 定义当前应用做某事的"意向". 当使用诸如 startActivity() 的方法将 Intent 传递至系统时,系统会使

详解 Android 通信【史上最全】

什么是通信? 通信 ,顾名思义,指的就是信息的传递或者交换 看完本文能收获什么? 按目录索引,你可以学习到 1. 组件间的通信,Activity,fragment,Service, Provider,Receiver 2. 进程间的通信,AIDL 3. 线程间的通信,Handler,AnsycTask,IntentService 4. 多个App间的通信 5. 使用大型开源框架完成组件通信,EventBus,otto 6. 网络通信基础篇:Google 课程–AnsycTask+HttpClie

Android开发文档---中文版

http://hukai.me/android-training-course-in-chinese/connectivity/volley/index.html Android入门基础:从这里开始 编写:kesenhoo - 原文:http://developer.android.com/training/index.html 欢迎来到为Android开发者准备的培训项目.在这里你会找到一系列的课程,这些课程会演示你如何使用可重用的代码来完成特定的任务.所有的课程分为若干不同的小组.你可以通过

Android学习路线(五)开启另一个Activity

在完成了 上一篇课程后,你已经有了一个应用.这个应用展示了一个包含一个文本框和一个按钮的activity(一个单独的界面).在这次的课程中,你将会通过在MainActivity中添加一些代码,来让当给你点击Send按钮时能够跳转到另一个activity中. 响应Send按钮 为了响应按钮的点击事件,打开fragment_main.xml 布局文件,然后在 <Button> 元素中加入android:onClick属性: <Button     android:layout_width=&

Android开发入门

Getting Started Welcome to Training for Android developers. Here you'll find sets of lessons within classes that describe how to accomplish a specific task with code samples you can re-use in your app. Classes are organized into several groups you ca

【译】Permissions Best Practices Android M权限最佳做法

Permissions Best Practices PreviousNext In this document Consider Using an Intent Don't Overwhelm the User Explain Why You Need Permissions Test for Both Permissions Models You should also read Interacting with Other Apps It's easy for an app to over

API翻译 --- Intent and Intent Filters

IN THIS DOCUMENT Intent Types           目的类型 Building an Intent        构建一个意图 Example explicit intent       例子显式意图 Example implicit intent      例隐式意图 Forcing an app chooser 迫使应用程序选择器 Receiving an Implicit Intent           收到一个隐式意图 Example filters   

Android官方文档training中英文翻译目录大全:29篇已翻译,45篇未翻译

Android官方文档training中英文翻译目录大全:29篇已翻译,45篇未翻译 1. Getting Started Building Your First App: 原文: https://developer.android.com/training/basics/firstapp/index.html译文:http://wiki.eoeandroid.com/Building_Your_First_AppAdding the Action Bar:原文:https://develope

Android文档 学习目录

Building Your First App After you've installed the Android SDK, start with this class to learn the basics about Android app development. Creating an Android Project Running Your Application Building a Simple User Interface Starting Another Activity A