本文共 2278 字,大约阅读时间需要 7 分钟。
application 可以很容易的接收其他application发送过来的数据。具体要怎么做呢? Update Your Manifest manifest文件中的Intent filter 可以指定application愿意接收的数据类型和需要响应的action,下面就是一个例子. <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEND_MULTIPLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> </activity> 在这个例子中我们可以响应的SEND和SEND_MULTIPLE。期待的数据类型为image/* 和 text/plain。个人感觉第一个intent-filter 可以和第二个intent-filter合并,毕竟他们的action是相同的,只是数据类型不一样. Handle the Incoming Content 为了接受Intent发送来的数据可以通过getIntent 获得Intent,然后在由Intent.getAction 和Intent.getType来获得action和数据类型,再走不同的case 如下所示: void onCreate (Bundle savedInstanceState) { ... // Get intent, action and MIME type Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); if (Intent.ACTION_SEND.equals(action) && type != null) { if ("text/plain".equals(type)) { handleSendText(intent); // Handle text being sent } else if (type.startsWith("image/")) { handleSendImage(intent); // Handle single image being sent } } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) { if (type.startsWith("image/")) { handleSendMultipleImages(intent); // Handle multiple images being sent } } else { // Handle other intents, such as being started from the home screen } ... } void handleSendText(Intent intent) { String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT); if (sharedText != null) { // Update UI to reflect text being shared } } void handleSendImage(Intent intent) { Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (imageUri != null) { // Update UI to reflect image being shared } } void handleSendMultipleImages(Intent intent) { ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (imageUris != null) { // Update UI to reflect multiple images being shared } } 需要注意的是,如果接受到的是binary数据,尽量在一个独立的线程中工作,否则可能造成UI线程的卡死.转载地址:http://qvcmi.baihongyu.com/