您的位置:首页 > 移动开发 > Android开发

Android+Sqlite 实现古诗阅读应用(三)

2015-06-02 21:14 645 查看

  往期传送门:

  Android+Sqlite 实现古诗阅读应用(一)  

  Android+Sqlite 实现古诗阅读应用(二)

  加入截图分享的功能。

   很多应用都有分享的功能,我也想在我的古诗App里加入这个功能,单纯的发送文字看起来太逊了,我决定模仿UC浏览器那样发送古诗的截图,使用官方的分享需要授权KEY,太过麻烦所以打算使用系统的分享。

   1.在meau里添加这个item:

<item
android:id="@+id/menu_item_share"
android:showAsAction="ifRoom"
android:title="分享"
/>


   


   2.新建全局变量Intent:

   

private void setshare(){
sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM, shot());
sendIntent.setType("image/jpeg");
}


  然后在meau的onOptionsItemSelected()方法里设置按下运行setshare()方法,新建一个intent,设置活动为send,然后传入的参数,是一个图片的uri通过shot生成。

  

private Uri shot() {
View view = getWindow().getDecorView();
Display display = this.getWindowManager().getDefaultDisplay();
view.layout(0, 0, display.getWidth(), display.getHeight());
view.setDrawingCacheEnabled(true);//允许当前窗口保存缓存信息,这样getDrawingCache()方法才会返回一个Bitmap

Rect frame = new Rect();
this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
// 获取屏幕长和高
int width = this.getWindowManager().getDefaultDisplay().getWidth();
int height = this.getWindowManager().getDefaultDisplay()
.getHeight();
TypedArray actionbarSizeTypedArray = this.obtainStyledAttributes(new int[]{      //测量actionbar的宽度
android.R.attr.actionBarSize});
int h = (int)actionbarSizeTypedArray.getDimension(0, 0);
Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(),0, statusBarHeight+h, width, height  //传入的几个参数分别为,数据源(要截的view),x轴坐标,y轴坐标,宽,长(屏幕-srarusbar-actionbar)
- statusBarHeight-h);
File f = new File(Environment.getExternalStorageDirectory(),      //写入文件流
"output_image.jpg");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fOut);            
try {
assert fOut != null;
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
return Uri.fromFile(f);                           //返回生成的文件的URI
}


  然后:

  

case R.id.menu_item_share:
setmShareActionProvider();
startActivity(Intent.createChooser(sendIntent,"图片"));
break;


  设置点击启动,就大功告成了,我们就能截到图片,而且没有actionbar和statusbar的干扰了。

  


    

  发送了图片

    

  接收到图片

    


  嗯,有朋友反映之前的一篇内容太多了,看代码感觉特别乱,这次的就减少了很多,不过这个小功能虽然小,但是还是很有用的,很多东西都会用到截图分享的功能哦。

  喜欢的请点赞吧!!!

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: