`
tmj_159
  • 浏览: 707441 次
  • 性别: Icon_minigender_1
  • 来自: 永州
社区版块
存档分类
最新评论

上官网学android之八(Interacting with Other Apps)

 
阅读更多

官网地址

http://developer.android.com/training/basics/intents/index.html

 

转眼间到了,Getting Started的最后一小节了,这次要学的是如何和其它的APP进行交互

一、发送动作到其它APP(原文是Sending the user to Another App)

 

1.1 建立一个Intent

在Android 中Intent是一种运行时绑定机制它可以再运行时连接两个不同的组件。

下面代码是官网上各种不同的Intent小例子

 

//拨电话
Uri number = Uri.parse("tel:5551234");
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
//地图
Uri location = Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);
//网页
Uri webpage = Uri.parse("http://www.android.com");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
//email
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType(HTTP.PLAIN_TEXT_TYPE);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"jon@example.com"}); // recipients
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message text");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://path/to/email/attachment"));
//日历
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");

 

1.2 验证是否有一个Activity去接收Intent

 

 

PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
boolean isIntentSafe = activities.size() > 0;
//如果isIntentSafe ==true 说明至少有一个Activity接收

 

1.3 启动一个有Intent的Activity

很简单调用startActivity(intent)方法,里面接收一个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);
}

 

1.4 显示一个APP选择框

如果有N个Activity可以接收你的Intent,这时候你得让用户选择一个他最喜欢的。

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().getString(R.string.chooser_title);
// Create intent to show chooser
Intent chooser = Intent.createChooser(intent, title);

// Verify the intent will resolve to at least one activity
if (intent.resolveActivity(getPackageManager()) != null) {
    startActivity(chooser);
}

 

二、从一个Activity得到一个结果

有时候我们启动一个Activity是喜欢得到它的结果,比如说选择联系人:)

下面是一个选择电话联系人的例子

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		getIntentResultTest();
	}

	static final int PICK_CONTACT_REQUEST = 1; // The request code

	private void getIntentResultTest() {
		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);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PICK_CONTACT_REQUEST) {
			if (resultCode == RESULT_OK) {
				Uri contactUri = data.getData();
				String[] projection = { Phone.NUMBER };

				Cursor cursor = getContentResolver().query(contactUri,
						projection, null, null, null);
				cursor.moveToFirst();

				int column = cursor.getColumnIndex(Phone.NUMBER);
				String number = cursor.getString(column);

				Log.i("intent_result_test", "number is :" + number);
			}
		}
	}
......

 

三、允许其它的APP启动你的Activity

前面都是调用别的Activity,现在反过来,让别人调用你的

3.1 添加一个Activity Filter

你需要定义下你能处理什么样的Intent,比如下面定义的Activity可以处理ACTION_SEND的Intent,data type 是text 或者 图像(image)

<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>

 如果你的Activity能处理两种Action呢比如,ACTION_SEND  和 ACTION_SENDTO,你需要定义两个intent filters.

<activity android:name="ShareActivity">
    <!-- filter for sending text; accepts SENDTO action with sms URI schemes -->
    <intent-filter>
        <action android:name="android.intent.action.SENDTO"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:scheme="sms" />
        <data android:scheme="smsto" />
    </intent-filter>
    <!-- filter for sending text or images; accepts SEND action and text or image data -->
    <intent-filter>
        <action android:name="android.intent.action.SEND"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:mimeType="image/*"/>
        <data android:mimeType="text/plain"/>
    </intent-filter>
</activity>

 

3.2 在Activity中处理Intent

上面已经告诉系统我们的Activity可以处理那些Intent,接下来我们要真正处理这些Intent了。

我们可以在Activity任何生命周期阶段,但是通常在onCreate()或者onStart()方法。

 

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

 

3.3  返回一个结果

还记得之前有选择联系人的情况,所以有的时候你可能需要返回一个结果。

返回一个结果很简单, setResult()方法即可完成任务

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

 通常总会返回一个Result code在一个result中,比如RESULT_OK,RESULT_CANELED。

也有的情况只需要一个简单的整形值而已

setResult(RESULT_COLOR_RED);
finish();

 

 

 

 

分享到:
评论

相关推荐

    与其他应用程序进行交互 - Interacting with Other Apps.

    在Android开发中,应用程序通常由多个Activity组成,每个Activity对应一个用户界面,并负责完成特定的任务。例如,一个Activity可以专门用于显示地图,而另一个可能用于拍照功能。当需要在不同的Activity之间转换,...

    Androidnteracting with Other Apps

    在Android操作系统中,应用间的交互(Interacting with Other Apps)是一项关键功能,它允许不同的应用程序之间共享数据、服务和功能,提升用户体验。Android系统通过多种机制实现这一目标,包括Intent、...

    The Android Developer’s Cookbook: Building Applications with the Android SDK

    Interacting with other devices via SMS, web browsing, and social networkingStoring data efficiently with SQLite and its alternatives Accessing location data via GPS Using location-related services ...

    The Android Developer's Cookbook Building Applications and Source Project

    Interacting with other devices via SMS, web browsing, and social networkingStoring data efficiently with SQLite and its alternatives Accessing location data via GPS Using location-related services ...

    Android.Recipes.A.Problem-Solution.Approach.5th

    Crammed with insightful instruction and helpful examples, this fifth edition of Android Recipes is your guide to writing apps for one of today’s hottest mobile platforms. It offers pragmatic advice ...

    Android Recipes: A Problem-Solution Approach, 3rd Edition

    Android continues to be one of the leading mobile OS and development platforms driving today’s mobile innovations and the apps ecosystem. Android appears complex, but offers a variety of organized ...

    The Android Developer‘s Cookbook 2nd Edition

    Do you want to get started building apps for Android, today's number one mobile platform? Are you already building Android apps but want to get better at it? The Android(TM) Developer's Cookbook, ...

    drozer2.3.4

    drozer allows you to search for security vulnerabilities in apps and devices by assuming the role of an app and interacting with the Dalvik VM, other apps' IPC endpoints and the underlying OS. ...

    IonicFramework手册

    Interacting with remote APIs is a common requirement for mobile apps. Ionic apps can use Angular's HttpClient service to fetch data from RESTful APIs. For offline storage, Ionic provides integration ...

Global site tag (gtag.js) - Google Analytics