Android+Sqlite 實現古詩閱讀應用(三),androidsqlite
往期傳送門: Android+Sqlite 實現古詩閱讀應用(一) Android+Sqlite 實現古詩閱讀應用(二) 加入分享的功能。
很多應用都有分享的功能,我也想在我的古詩App裡加入這個功能,單純的發送文字看起來太遜了,我決定模仿UC瀏覽器那樣發送古詩的,使用官方的分享需要授權KEY,太過麻煩所以打算使用系統的分享。
1.在meau裡添加這個item:
1 <item2 android:id="@+id/menu_item_share"3 android:showAsAction="ifRoom"4 android:title="分享"5 />
2.建立全域變數Intent:
1 private void setshare(){2 sendIntent = new Intent();3 sendIntent.setAction(Intent.ACTION_SEND);4 sendIntent.putExtra(Intent.EXTRA_STREAM, shot());5 sendIntent.setType("image/jpeg");6 }
然後在meau的onOptionsItemSelected()方法裡設定按下運行setshare()方法,建立一個intent,設定活動為send,然後傳入的參數,是一個圖片的uri通過shot產生。
1 private Uri shot() { 2 View view = getWindow().getDecorView(); 3 Display display = this.getWindowManager().getDefaultDisplay(); 4 view.layout(0, 0, display.getWidth(), display.getHeight()); 5 view.setDrawingCacheEnabled(true);//允許當前視窗儲存緩衝資訊,這樣getDrawingCache()方法才會返回一個Bitmap 6 7 Rect frame = new Rect(); 8 this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); 9 int statusBarHeight = frame.top;10 // 擷取螢幕長和高11 int width = this.getWindowManager().getDefaultDisplay().getWidth();12 int height = this.getWindowManager().getDefaultDisplay()13 .getHeight();14 TypedArray actionbarSizeTypedArray = this.obtainStyledAttributes(new int[]{ //測量actionbar的寬度15 android.R.attr.actionBarSize});16 int h = (int)actionbarSizeTypedArray.getDimension(0, 0);17 Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(),0, statusBarHeight+h, width, height //傳入的幾個參數分別為,資料來源(要截的view),x軸座標,y軸座標,寬,長(螢幕-srarusbar-actionbar)18 - statusBarHeight-h);19 File f = new File(Environment.getExternalStorageDirectory(), //寫入檔案流20 "output_image.jpg");21 FileOutputStream fOut = null;22 try {23 fOut = new FileOutputStream(f);24 } catch (FileNotFoundException e) {25 e.printStackTrace();26 }27 bmp.compress(Bitmap.CompressFormat.JPEG, 100, fOut); 28 try {29 assert fOut != null;30 fOut.flush();31 } catch (IOException e) {32 e.printStackTrace();33 }34 try {35 fOut.close();36 } catch (IOException e) {37 e.printStackTrace();38 }39 return Uri.fromFile(f); //返回產生的檔案的URI40 }
然後:
case R.id.menu_item_share: setmShareActionProvider(); startActivity(Intent.createChooser(sendIntent,"圖片")); break;
設定點擊啟動,就大功告成了,我們就能截到圖片,而且沒有actionbar和statusbar的幹擾了。
發送了圖片
接收到圖片
嗯,有朋友反映之前的一篇內容太多了,看代碼感覺特別亂,這次的就減少了很多,不過這個小功能雖然小,但是還是很有用的,很多東西都會用到分享的功能哦。
喜歡的請點贊吧!!!