如何在安卓APP中添加分享按钮?

最近想给一个APP添加分享屏幕截图的功能,就尝试找了一圈相关的Package,最后找倒是没找到,倒是在StackOverflow找到了一个解决方法。

布局及相关权限

  • AndroidManifest.xml权限添加
<!--    STORAGE PERMISSION FOR SCREEN SHOT-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
  • 存储路径配置provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>
  • 布局
...
<LinearLayout android:id="@+id/shared_preferences_container"
			  android:layout_width="match_parent"
			  android:layout_height="wrap_content"
			  android:background="#7E03A9F4">
	<TextView android:layout_width="wrap_content"
			  android:layout_height="wrap_content"
			  android:textAlignment="center"
			  android:layout_weight="10"
			  android:text="@string/share_info"/>
	<Button android:id="@+id/share"
			android:background="@drawable/ic_share"
			android:layout_weight="1"
			android:layout_width="32dp"
			android:layout_height="32dp"
			android:layout_marginRight="10dp"/>
</LinearLayout>
...

Code

  • 主要引用
...
Button share = (Button) findViewById(R.id.share);
share.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
		Bitmap bitmap = takeScreenshot(gameWeb);
		saveBitmap(bitmap);
		shareIt(GameActivity.this);
	}
});
...
  • 截图
public Bitmap takeScreenshot(View v) {
	View rootView = findViewById(android.R.id.content);
	Bitmap bitmap = Bitmap.createBitmap(rootView.getWidth(),
										rootView.getHeight(), Bitmap.Config.ARGB_8888);
	Canvas canvas = new Canvas(bitmap);
	rootView.draw(canvas);
	return bitmap;
}
  • 存图
public void saveBitmap(Bitmap bitmap) {
	Date dNow = new Date( );
	SimpleDateFormat ft = new SimpleDateFormat("yyyyMMddhhmmss");
	imagePath = new File(Environment.getExternalStorageDirectory() + "/DCIM/Share_"+ft.format(dNow)+".png");
	if (!imagePath.exists()) {
		Log.d("path", imagePath.toString());
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(imagePath);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			Log.e("GREC", e.getMessage(), e);
		} catch (java.io.IOException e) {
			e.printStackTrace();
			Log.e("GREC", e.getMessage(), e);
		}

	}
}
  • 分享

如需了解更多请访问: https://www.emperinter.info/2022/05/03/how-to-add-a-share-button-in-android-app/