在使用intent共享数据时,我们可以将所需的全部类型都打包于ShareCompt类中
在数据类型中,有一种类型叫媒体类型 Media Type String,媒体类型字符串由类型,子类型和可选参数组成。例如text/html; charset = URF-8
当你想在应用之间共享数据时 ,你必须说明它的媒体类型。以使android确定如何以及是否可以完成请求。
String mimeType = "text/plain";
String title = "Learning How to Share"
String textToShare = "Hello there"
ShareCompat.IntentBuilder.from(this).setChooserTitle(title).setType(mimeType).setText(textToShare).startChooser();;
public class DetailActivity extends AppCompatActivity {
private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
private String mForecast;
private TextView mWeatherDisplay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
mWeatherDisplay = (TextView) findViewById(R.id.tv_display_weather);
Intent intentThatStartedThisActivity = getIntent();
if (intentThatStartedThisActivity != null) {
if (intentThatStartedThisActivity.hasExtra(Intent.EXTRA_TEXT)) {
mForecast = intentThatStartedThisActivity.getStringExtra(Intent.EXTRA_TEXT);
mWeatherDisplay.setText(mForecast);
}
}
}
private Intent createShareForecastIntent() {
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
.setType("text/plain")
.setText(mForecast + FORECAST_SHARE_HASHTAG)
.getIntent();
return shareIntent;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.detail, menu);
MenuItem menuItem = menu.findItem(R.id.action_share);
menuItem.setIntent(createShareForecastIntent());
return true;
}
}