Android使用 ACTION_SEND 事件 android.content.Intent 类,将数据从一个Activity发送到另一个Activity,并从当前Activity到应用程序外部。 Intent类需要指定要共享的数据及其类型。
最常见的是,ACTION_SEND操作发送浏览器应用程序的URL。在共享数据时,Intent调用 createChooser()方法,它采用Intent对象并指定对话框的标题。 Intent.createChooser()方法允许显示选择器。
在此示例中,无涯教程将共享纯文本,这是一个浏览器的URL。
文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.test.shareapp.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:id="@+id/textView" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Share App" android:id="@+id/button" android:layout_marginBottom="95dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" /> </RelativeLayout>
文件:mainActivity.java
package com.example.test.shareapp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { Button sharebutton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sharebutton=(Button)findViewById(R.id.button); sharebutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_SUBJECT,"Insert Subject here"); String app_url = " https://play.google.com/store/apps/details?id=my.example.learnfk"; shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,app_url); startActivity(Intent.createChooser(shareIntent, "Share via")); } }); } }
输出
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)