How to take and Share ScreenShot programmatically in Android Studio
Throughout this guide, we will explain how to take and share screenshots programmatically in Android Studio.
Recently working with my Projects where We need to add a Share Button that will take a complete screenshot and Share Image using an explicit intent.
Step 1: Create New Project
To create a new sample project, first, open Android Studio and Click on Create New Project
Step 2: Modify activity_main and string.xml
Once all required files get an imported copy, the below XML file to activity_main.xml.
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" tools:context=".MainActivity"> <ImageView android:id="@+id/scenicImage" android:layout_width="match_parent" android:layout_height="300dp" android:scaleType="fitXY" app:layout_constraintTop_toTopOf="parent" android:src="@drawable/ic_android_512dp" android:contentDescription="@string/background_scenic" /> <TextView android:id="@+id/dummyText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:text="@string/dummy_text" android:textAppearance="@style/TextAppearance.AppCompat.Body1" android:textSize="18sp" app:layout_constraintTop_toBottomOf="@id/scenicImage" /> <Button android:id="@+id/shareButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/share_btn" android:backgroundTint="#1EF85E" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="@+id/dummyText" app:layout_constraintStart_toStartOf="@+id/dummyText" app:layout_constraintTop_toBottomOf="@+id/dummyText" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Update AndroidManifest.xml
We need to update AndroidManifest.xml to add User Permission like Read and Write support to store and read files from Storage.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />This is an extra step for the device above AndroidSDK 29 to access a file from the External Directory file; else, the application will not be worked end up with ‘open failed: EACCES (Permission denied)’.
Please copy-paste the below code under the <application> </application> tag and you will get the error of missing Cannot resolve symbol ‘@xml/file_path’
<provider android:name="androidx.core.content.FileProvider" android:authorities="com.trendoceans.fileshare.MainActivity.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_path" /> </provider>To resolve the missing file_path.xml file, create a new XML folder under the res directory. After that, right-click on the XML directory, create a new XML resource file with a “file_path”, and press the OK.
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="external_files" path="."/> </paths>Step 4: Write code to MainActivity
When you complete the above process, let’s write the code and complete the application workflow.
The first step is to instantiate the view object to MainActivity class to instantiate follow the below code.
Inside the onCreate method, add a clickListener to the button; before that, we have created a method to verify file permissions.
Don’t bother about the missing method. We will create a method very soon. Inside the onClick, we have created a function to take a screenshot when the user clicks on Share Button.
Step 4a: Create Method to TakeScreenShot
To resolve Cannot resolve method ‘takeScreenShot(android.view.View)’, click on the red bulb or press Alt + Enter to create a new method.
import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.FileProvider; import android.Manifest; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.text.format.DateFormat; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; public class MainActivity extends AppCompatActivity { private ImageView imageView; private TextView textView; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.scenicImage); textView = findViewById(R.id.dummyText); button = findViewById(R.id.shareButton); verifyStoragePermission(MainActivity.this); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { takeScreenShot(getWindow().getDecorView()); } }); } private void takeScreenShot(View view) { Date date = new Date(); CharSequence format = DateFormat.format("MM-dd-yyyy_hh:mm:ss", date); try { File mainDir = new File( this.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "FilShare"); if (!mainDir.exists()) { boolean mkdir = mainDir.mkdir(); } String path = mainDir + "/" + "TrendOceans" + "-" + format + ".jpeg"; view.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); view.setDrawingCacheEnabled(false); File imageFile = new File(path); FileOutputStream fileOutputStream = new FileOutputStream(imageFile); bitmap.compress(Bitmap.CompressFormat.PNG, 90, fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); shareScreenShot(imageFile); } catch (IOException e) { e.printStackTrace(); } } //Share ScreenShot private void shareScreenShot(File imageFile) { Uri uri = FileProvider.getUriForFile( this, BuildConfig.APPLICATION_ID + "." + getLocalClassName() + ".provider", imageFile); Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/*"); intent.putExtra(android.content.Intent.EXTRA_TEXT, "Download Application from Instagram"); intent.putExtra(Intent.EXTRA_STREAM, uri); try { this.startActivity(Intent.createChooser(intent, "Share With")); } catch (ActivityNotFoundException e) { Toast.makeText(this, "No App Available", Toast.LENGTH_SHORT).show(); } } //Permissions Check private static final int REQUEST_EXTERNAL_STORAGE = 1; private static final String[] PERMISSION_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, }; public static void verifyStoragePermission(Activity activity) { int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( activity, PERMISSION_STORAGE, REQUEST_EXTERNAL_STORAGE); } } }
Post a Comment
0Comments