Home Blog Page 2

How to programmatically take a screenshot in android

0
Programmatically take screenshot
Programmatically take screenshot

Hi Guys, Welcome to Proto Coders Point. In this Android Article will learn how to implement taking screenshot in your android application, Now every mobile device has a inbuilt feature by which users can easily capture screenshots.

Suppose you want to implement programmatically take screenshot in your android application as a special feature of your app then this article will help you.

Take Screenshot in android programmatically

Final Output of below code implementation

Implementation Step by Step

Step 1: Open or Create new Android Project

Create a new android project in android studio or open any existing android project where you want to implement screenshot taking feature.


Step 2: Add storage read & Write permission

As we are going to take screenshot and store the capture image in storage, we need to add permission to access storage, Therefore open AndroidManifest.xml file

Android > app > Manifest > AndroidManifest.xml

Within Manifest tag add below 3 storage permission

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.on.take_screenshot">    
    
    //add this 3 permission
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />



</manifest>

Then next you need to enable requestLegacyExternalStorage inside <application.> as show below:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.on.take_screenshot">    
    
    //add this 3 permission
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

     <application
        android:requestLegacyExternalStorage="true"     //add this line
        android:allowBackup="true"
        .......
        .......
        .......
       >


</manifest>

Step 3: Layout design

Now, Let’s create a layout view or page of which our program will take screenshot programmatically.

activity_main.xml

Copy the below code in activty_main.xml file as UI design.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:id="@+id/parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:src="@mipmap/ic_launcher_round"
        android:layout_marginBottom="15dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="To Capture Hit below Button"
        android:textColor="#302F2F"
        android:textSize="20dp"
        android:textStyle="bold|italic" />

    <Button
        android:id="@+id/takeshot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="#11BFD6"
        android:text="Take Shot" />

</LinearLayout>

Step 4: Giving Life to UI, Working on MainActivity.java

Refer below MainActivity.java code , Comment are been added for better understanding while code go through.

package example.on.take_screenshot;

import static android.content.ContentValues.TAG;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    Button take;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] permissionstorage = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        take = findViewById(R.id.takeshot);
        checkpermissions(this); // check or ask for storage permission
        take.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //pass layout view to method to perform capture screenshot and save it.
                takeScreenshot(getWindow().getDecorView().getRootView());
            }
        });
    }

    protected File takeScreenshot(View view) {
        Date date = new Date();
        try {
            String dirpath;
            // Initialising the directory of storage
            dirpath= MainActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString() ;
            File file = new File(dirpath);
            if (!file.exists()) {
                boolean mkdir = file.mkdir();
            }
            // File name : keeping file name unique using data time.
            String path = dirpath + "/"+ date.getTime() + ".jpeg";
            view.setDrawingCacheEnabled(true);
            Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
            view.setDrawingCacheEnabled(false);
            File imageurl = new File(path);
            FileOutputStream outputStream = new FileOutputStream(imageurl);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
            outputStream.flush();
            outputStream.close();
            Log.d(TAG, "takeScreenshot Path: "+imageurl);
            Toast.makeText(MainActivity.this,""+imageurl,Toast.LENGTH_LONG).show();
            return imageurl;

        } catch (FileNotFoundException io) {
            io.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // check weather storage permission is given or not
    public static void checkpermissions(Activity activity) {
        int permissions = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        // If storage permission is not given then request for External Storage Permission
        if (permissions != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, permissionstorage, REQUEST_EXTERNAL_STORAGE);
        }
    }

}

Result

Android FileNotFoundException: open failed EPERM Operation not permitted

0
eperm operation not permitted
eperm operation not permitted

Hi Guys, Welcome to Proto Coders Point. So once i was trying to implement programmatically taking screenshot in android ap development and I faced a problem while saving the captured screenshot to gallery, & this is the error i got FileNotFoundException: open failed: EPERM (Operation not permitted), After lot’s of trial & error, finally got the solution to solve EPERM issue in android while saving file in android.

 Let’s start to solve operation not permitted issue in android

How To Solve FileNotFoundException open failed: EPERM (Operation not permitted) Error

Here is a very simple soltion to easily solve FileNotFoundException open Failed: EPERM: You have to has a permission where you are allowing you android appliation to access External Storage, add it.

To add requestLegacyExternalStorage, just go to AndroidManifest.xml

Project > app > manifest > AndroidManifest.xml

Open it, then inside application tag add

 android:requestLegacyExternalStorage=”true” 

For Reference image:

make legacy extenal storage to true

Now, just Uninstall app and reinstall app it again & you will see your eror got successfully solved.

How to take screenshots programmatically in flutter

0
Programmatically take screenshot in flutter

Hi Guys, Welcome to Proto Coders Point, In this flutter article will learn how can we programmatically take a screenshot in flutter. Add this feature into your flutter app so that users can take screenshot of the app screen when they want to, just by clicking a button.

Let’s get started – Taking Screenshot in flutter app

To capture our app screen will make use of flutter inBuilt widget i.e. RepaintBoundry.

Using RepaintBoundry widget

RePaintBoundry widget in flutter will capture the view of the child it wrapped with, For Example: if you wrap RepaintBoundry with Container Widget then your app will only capture that widget, suppose if you want to take screenshot of complete app screen then you need to wrap RePaintBoundry to Scaffold widget as done in below complete code.
Then attach a GlobalKey to RepaintBoundry.
Next, by using GlobalKey currentContext we can use .findRenderObject() method helps us in finding current render object.
Next, will use toImage() method to convert render object to image.
then, will convert image into byteData which will again get converted to asUint8List().
Next, will use the Uint8List format to save the screenshot by using ImageGallerySaver package.

Below method take screenshowt and save it.

void _CaptureScreenShot() async{
    //get paint bound of your app screen or the widget which is wrapped with RepaintBoundary.
    RenderRepaintBoundary bound = _key.currentContext!.findRenderObject() as RenderRepaintBoundary;

    if(bound.debugNeedsPaint){
      Timer(Duration(seconds: 1),()=>_CaptureScreenShot());
      return null;
    }

    ui.Image image = await bound.toImage();
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);

    // this will save image screenshot in gallery
    if(byteData != null ){
      Uint8List pngBytes = byteData.buffer.asUint8List();
      final resultsave = await ImageGallerySaver.saveImage(Uint8List.fromList(pngBytes),quality: 90,name: 'screenshot-${DateTime.now()}.png');
      print(resultsave);
    }
  }

Programmatically take screenshot in flutter

Complete Code implement to take screenshot in flutter in step

Step 1: Add ImageGallerySaver

In your flutter project, open pubspec.yaml file and under dependencies section add the image gallery saver flutter library.

dependencies:
  image_gallery_saver: '^1.7.1'

Step 2: Add Permission to save image in galery

Android External Storage permission

Open manifest file, and under application tag add:

<application android:requestLegacyExternalStorage="true" .....>

iOS Photo Library usage permission

Navigate to <project>/ios/Runner/info.plist, then between <dict></dict> add below lines

<key>NSPhotoLibraryAddUsageDescription</key>
<string>This app need access to your gallery to save screenshots</string>


Step 3: Complete Code

Refer comment in code for better understanding

main.dart

import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui' as ui;
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomepage(),
    );
  }
}

class MyHomepage extends StatefulWidget {
  const MyHomepage({Key? key}) : super(key: key);

  @override
  State<MyHomepage> createState() => _MyHomepageState();
}

class _MyHomepageState extends State<MyHomepage> {
  final GlobalKey _key = GlobalKey();

  void _CaptureScreenShot() async{
    //get paint bound of your app screen or the widget which is wrapped with RepaintBoundary.
    RenderRepaintBoundary bound = _key.currentContext!.findRenderObject() as RenderRepaintBoundary;

    if(bound.debugNeedsPaint){
      Timer(Duration(seconds: 1),()=>_CaptureScreenShot());
      return null;
    }

    ui.Image image = await bound.toImage();
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);

    // this will save image screenshot in gallery
    if(byteData != null ){
      Uint8List pngBytes = byteData.buffer.asUint8List();
      final resultsave = await ImageGallerySaver.saveImage(Uint8List.fromList(pngBytes),quality: 90,name: 'screenshot-${DateTime.now()}.png');
      print(resultsave);
    }
  }

  @override
  Widget build(BuildContext context) {
    //Here i have wrapped whole app screen scaffold widget, to take full screenshot
    return RepaintBoundary(
      key: _key,
      child: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(color:Colors.blue,width: 220,height: 220,),
              SizedBox(height: 25,),
              ElevatedButton(onPressed: (){
                _CaptureScreenShot(); // Method called to take screenshot on wrapped widget and save it.
              }, child: Text("Capture & Save"))
            ],
          )
        ),
      ),
    );
  }
}

Video Tutorial

How to upgrade node version ubuntu

0
update node version ubuntu
upgrade node version Ubuntu

Hi Guys, Welcome to Proto Coders point. Here is a quick step by step guide to update nodejs in ubuntu OS.

Time needed: 3 minutes.

update node version

  1. use n module

    To upgrade node version in ubuntu will make use of n module from npm package.

  2. Install n module

    Firstly install n module using npm run below command.
    sudo npm cache clean -f
    sudo npm install -g n
    sudo n stable
    …so now we have successfully install n module of npm package.

  3. update node version ubuntu to latest

    Now simply run below command, to upgrade nodejs and to update npm version.
    sudo n latest
    Note: this will update your nodejs and npm version to latest version(not to stable current version).

  4. Now check nodejs version

    run below command
    node --version
    npm --version

  5. Optional – update node to specific version

    curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
    sudo apt-get install --reinstall nodejs-legacy # fix /usr/bin/node


If node --version showing you old version still then simply, close and re-open new terminal and run node --version to check nodejs version updated or no.

Flutter Cascade Operator (..) cascade notation in dart

0
flutter dart cascade opetator notation
cascade operator in dart language

Estimated reading time: 1 minute

The Cascade operator notation in flutter dart (..) is two dots, using cascade in dart we can make a sequence of operation using same object & we can even call a function & easily access field or parameter value. By using dart cascade notation (..) we can keep dart code neat & clean as it removes unnecessary temporary variable creation to store data.

Video Tutorial on Flutter Cascade Operator

Cascade Operator in dart example code

In below example We have created a class by name Person which has 2 variable and 1 method to print on console:

  • int? age;
  • String? name;
  • printDetails()

class person

class Person{
  int? age;
  String? name;
  
  void printDetails(){
    print("$name age is $age");
  }
}

In Below Code,

Line No: 3 – > Create an object of Person as p1.

void main(){
  
  Person p1 = Person(); // object creation

  p1..name = "Rajat Palankar"..age = 26 ..printDetails(); 
  // using cascade, initialize the value and call print function
  
}

Then, In line No: 5 -> using object, initialize the value to class variable and call printDetails method of Person Class.

Output : Rajat Palankar age is 26

How to show git brand name on terminal

0
How to show git branch name in Terminal Ubuntu

Time needed: 2 minutes.

In this Article will learn how to show git branch name with color in terminal (ubuntu)

  1. Open bashrc file

    Firstly open bashrc file by below cmd.
    gedit ~/.bashrc

  2. Comment old color prompt

    In ~/.bashrc file, you will find a code starting with if[“$color_prompt = yes”] and end’s with fi, just comment this like as shown in below screenshot for reference.ubuntu git bashrc edit

  3. Add below line of code

    parse_git_branch() {
        git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
       }
       
       if [ "$color_prompt" = yes ]; then
        PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(parse_git_branch)\[\033[00m\]\$ '
       else
        PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git_branch)\$ '
       fi


    Reference Screenshot
    show git branch name on terminal

  4. Final done

    Here is how your terminal shows branch name when you are into git repository project folder, In below screenshot as you can see we can easily get to know on which github branch we are working on(No need to keep on checking git branch -a).how to show git branch name in prompt terminal ubuntu