笔记:与其他app共享Simple Data,和在ActionBar上简单地添加分享按钮

Lessons


Sending Simple Data to Other Apps
Learn how to set up your application to be able to send text and binary data to other applications with intents.
Receiving Simple Data from Other Apps
Learn how to set up your application to receive text and binary data from intents.
Adding an Easy Share Action
Learn how to add a "share" action item to your action bar.


Sending Simple Data to Other Apps


Sending and receiving data between applications with intents is most commonly used for social sharing of content. Intents allow users to share information quickly and easily, using their favorite applications.

Send Text Content  

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);

However, if you call Intent.createChooser(), passing it your Intent object, it returns a version of your intent that will always display the chooser. This has some advantages:

  • Even if the user has previously selected a default action for this intent, the chooser will still be displayed.
  • If no applications match, Android displays a system message.
  • You can specify a title for the chooser dialog.
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));

Send Binary Content

Binary data is shared using the ACTION_SEND action combined with setting the appropriate MIME type and placing the URI to the data in an extra named EXTRA_STREAM. This is commonly used to share an image but can be used to share any type of binary content:

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));

Note the following: //共享二进制数据的两种方式                                    确保接收请求的app有权限去access文件

  • You can use a MIME type of "*/*", but this will only match activities that are able to handle generic data streams.
  • The receiving application needs permission to access the data the Uri points to. The recommended ways to do this are:
    • Store the data in your own ContentProvider, making sure that other apps have the correct permission to access your provider.The preferred mechanism for providing access is to use per-URI permissions which are temporary and only grant access to the receiving application. An easy way to create a ContentProviderlike this is to use the FileProvider helper class.
    • Use the system MediaStore. The MediaStore is primarily aimed at video, audio and image MIME types, however beginning with Android 3.0 (API level 11) it can also store non-media types (seeMediaStore.Files for more info). Files can be inserted into the MediaStore using scanFile() after which acontent:// style Uri suitable for sharing is passed to the provided onScanCompleted() callback.Note that once added to the system MediaStore the content is accessible to any app on the device.

Send Multiple Pieces of Content

To share multiple pieces of content, use the ACTION_SEND_MULTIPLE action together with a list of URIs pointing to the content. The MIME type varies according to the mix of content you're sharing. For example, if you share 3 JPEG images, the type is still "image/jpeg". For a mixture of image types, it should be "image/*" to match an activity that handles any type of image. You should only use "*/*" if you're sharing out a wide variety of types. As previously stated, it's up to the receiving application to parse and process your data. Here's an example:

ArrayList<Uri> imageUris = new ArrayList<Uri>();
imageUris.add(imageUri1); // Add your image URIs here
imageUris.add(imageUri2);

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share images to.."));

As before, make sure the provided URIs point to data that a receiving application can access.

Receiving Simple Data from Other Apps

Update Your Manifest


Intent filters inform the system what intents an application component is willing to accept. Similar to how you constructed an intent with action ACTION_SEND in theSending Simple Data to Other Apps lesson, you create intent filters in order to be able to receive intents with this action. You define an intent filter in your manifest, using the <intent-filter> element. For example, if your application handles receiving text content, a single image of any type, or multiple images of any type, your manifest would look like:

<activity android:name=".ui.MyActivity" >
    <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>

Handle the Incoming Content

To handle the content delivered by an Intent, start by calling getIntent() to get Intent object. Once you have the object, you can examine its contents to determine what to do next. Keep in mind that if this activity can be started from other parts of the system, such as the launcher, then you will need to take this into consideration when examining the intent(1).

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(2)
    }
    ...
}

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
    }
}
,the wrong MIME type might be set, or the image being sent might be extremely large. Also, remember to process binary data in a separate thread rather than the main ("UI") thread.


Adding an Easy Share Action


Implementing an effective and user friendly share action in yourActionBar is made even easier with the introduction ofActionProvider in Android 4.0 (API Level 14). AnActionProvider, once attached to a menu item in the action bar, handles both the appearance and behavior of that item. In the case of ShareActionProvider, you provide a share intent and it does the rest.

Note:  ShareActionProvider is available starting with API Level 14 and higher.

Update Menu Declarations

To get started with ShareActionProviders, define the android:actionProviderClass attribute for the corresponding <item> in yourmenu resource file:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
            android:id="@+id/menu_item_share"
            android:showAsAction="ifRoom"
            android:title="Share"
            android:actionProviderClass="android.widget.ShareActionProvider" />
    ...
</menu>
This delegates responsibility for the item's appearance and function to ShareActionProvider . However, you will need to tell the provider what you would like to share.

Set the Share Intent

In order for ShareActionProvider to function, you must provide it a share intent. This share intent should be the same as described in the Sending Simple Data to Other Apps lesson,with action ACTION_SEND and additional data set via extras like EXTRA_TEXT and EXTRA_STREAM. To assign a share intent, first find the correspondingMenuItem while inflating your menu resource in your Activity or Fragment. Next, callMenuItem.getActionProvider() to retrieve an instance of ShareActionProvider. Use setShareIntent() to update the share intent associated with that action item. Here's an example:

private ShareActionProvider mShareActionProvider;
...

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate menu resource file.
    getMenuInflater().inflate(R.menu.share_menu, menu);

    // Locate MenuItem with ShareActionProvider
    MenuItem item = menu.findItem(R.id.menu_item_share);

    // Fetch and store ShareActionProvider
    mShareActionProvider = (ShareActionProvider) item.getActionProvider();

    // Return true to display menu
    return true;
}

// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
    if (mShareActionProvider != null) {
        mShareActionProvider.setShareIntent(shareIntent);
    }
}

You may only need to set the share intent once during the creation of your menus, or you may want to set it and then update it as the UI changes. For example, when you view photos full screen in the Gallery app, the sharing intent changes as you flip between photos.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Android 应用程序中实现顶部返回按钮,可以使用 ActionBar。ActionBar 是 Android 提供的一种 UI 控件,通常位于应用程序的顶部,用于显示应用程序名称、菜单和其他选项。 要实现 ActionBar 中的顶部返回按钮,请按照以下步骤操作: 1. 打开 Android Studio,创建一个新的空白项目。 2. 在 res/values/styles.xml 文件中添加以下代码: ``` <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> </style> ``` 这将为应用程序创建一个基本的主题,其中包含一个暗色 ActionBar。 3. 在 AndroidManifest.xml 文件中,将应用程序的主题设置为上一步中创建的主题: ``` <application android:theme="@style/AppTheme" ... ``` 4. 在 MainActivity.java 文件中,添加以下代码: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 启用 ActionBar 返回按钮 getSupportActionBar().setDisplayHomeAsUpEnabled(true); } // 处理 ActionBar 返回按钮点击事件 @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // 在此处添加返回按钮点击后的处理逻辑 finish(); return true; } return super.onOptionsItemSelected(item); } ``` 这将启用 ActionBar 中的返回按钮,并在用户点击该按钮时关闭当前活动。 5. 运行应用程序,并确保 ActionBar 中显示了返回按钮。单击该按钮,应该会关闭当前活动。 注意:如果您的应用程序需要导航到其他活动,则可以在 onOptionsItemSelected() 方法中添加相应的 Intent。例如: ``` case android.R.id.home: Intent intent = new Intent(this, OtherActivity.class); startActivity(intent); finish(); return true; ``` 这将使 ActionBar 返回按钮导航到 OtherActivity。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值