import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.app.Activity; import android.content.Intent; import android.view.ActionProvider; import android.view.Menu; import android.view.MenuItem; import android.widget.ShareActionProvider; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); // 获取菜单项 MenuItem item = menu.findItem(R.id.action_fuck_share); // 获取provider 的对象 /** * ShareActionProvider 分享动作的提供者 */ ShareActionProvider provider = (ShareActionProvider) item .getActionProvider(); // 设置分享的意图 Intent shareIntent = new Intent(); shareText(provider, shareIntent); return true; } private void shareText(ShareActionProvider provider, Intent shareIntent) { // 隐式跳转 shareIntent.setAction(Intent.ACTION_SEND); /** * 设置Intent的 */ shareIntent.putExtra(Intent.EXTRA_TEXT, "分享的内容"); shareIntent.setType("text/*"); provider.setShareIntent(shareIntent); } private void shareImage(ShareActionProvider provider, Intent shareIntent) { // 隐式跳转 shareIntent.setAction(Intent.ACTION_SEND); // 目的: 将assets 的文件,放在sd上面,再分析sd卡的图片,注意:必须要写到sd才能共享出去 try { // 获取Assets下面的img文件,得到一个输入流 InputStream is = getAssets().open("beijin.jpeg"); // 判断挂载,和权限 if (!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { return; } //放在外部存储的根路径下 File file = new File(Environment.getExternalStorageDirectory() .getAbsolutePath()+File.separator+"img.jpg"); //不存在就创建一个文件 if(!file.exists()){ file.createNewFile(); } FileOutputStream fos = new FileOutputStream(file); int len = 0; byte[] buff = new byte[1024]; while((len=is.read(buff))!=-1){ fos.write(buff, 0, len); } fos.close(); is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //标识符,文件对应着的Uri Uri uri = Uri.fromFile(new File(Environment .getExternalStorageDirectory() .getAbsolutePath()+File.separator+"img.jpg")); /** * 设置Intent的 */ shareIntent.putExtra(Intent.EXTRA_STREAM, uri.toString()); shareIntent.setType("image/*"); provider.setShareIntent(shareIntent); } }
时间: 2024-10-25 21:06:16