Monday 14 February 2022

Alarm Manager Example in Android

 



activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 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"

    tools:context=".MainActivity">


    <Button

        android:id="@+id/btn_start_alarm"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"

        android:text="Start Alarm"

        android:textAllCaps="false"/>


</RelativeLayout>



MainActivity.java

import androidx.appcompat.app.AppCompatActivity;


import android.app.AlarmManager;

import android.app.PendingIntent;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;


public class MainActivity extends AppCompatActivity {


    private Button mBtnStart;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        mBtnStart = findViewById(R.id.btn_start_alarm);

        mBtnStart.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                startAlarm(MainActivity.this);

            }

        });

    }


    public static void startAlarm(Context context) {

        Intent intent = new Intent(context, MyAlarmReceiver.class);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(

                context.getApplicationContext(), 0 , intent, 0);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);

        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()

                + (10 * 1000), pendingIntent); //10 seconds interval

    }

}



MyAlarmReceiver.java

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.widget.Toast;


public class MyAlarmReceiver extends BroadcastReceiver {

    @Override

    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context, "Alarm Started Successfully", Toast.LENGTH_SHORT).show();

    }

}  



AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.surabhiglobal.alarmexample">


    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />


    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/Theme.AlarmExample">

        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>


        <receiver android:name=".MyAlarmReceiver" />


    </application>


</manifest>

Monday 7 February 2022

Foreground Service Example in Android

 


 

activity_main.xml

<?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:orientation="vertical"

    tools:context=".MainActivity">


    <Button

        android:id="@+id/btn_start"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Start Service"

        android:layout_margin="20sp"/>


    <Button

        android:id="@+id/btn_stop"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Stop Service"

        android:layout_margin="20sp"/>


</LinearLayout>


MainActivity.java


import androidx.appcompat.app.AppCompatActivity;


import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;


public class MainActivity extends AppCompatActivity {

    private Button btn_start,btn_stop;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        btn_start = findViewById(R.id.btn_start);

        btn_stop = findViewById(R.id.btn_stop);


        btn_start.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                startService(new Intent(MainActivity.this,ForegroundService.class));

            }

        });

        btn_stop.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                stopService(new Intent(MainActivity.this,ForegroundService.class));

            }

        });

    }

}


ForegroundService.java


import android.app.NotificationChannel;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.app.Service;

import android.content.Intent;

import android.os.Binder;

import android.os.Build;

import android.os.IBinder;


import androidx.core.app.NotificationCompat;


public class ForegroundService extends Service {


    private final IBinder mBinder = new MyBinder();

    private static final String CHANNEL_ID = "2";


    @Override

    public IBinder onBind(Intent intent) {

        return mBinder;

    }


    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {

        return START_STICKY;

    }


    @Override

    public void onCreate() {

        super.onCreate();

        buildNotification();

    }


    private void buildNotification() {

        String stop = "stop";

        PendingIntent broadcastIntent = PendingIntent.getBroadcast(

                this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);

        // Create the persistent notification

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)

                .setContentTitle(getString(R.string.app_name))

                .setContentText("Foreground service is working")

                .setOngoing(true)

                .setContentIntent(broadcastIntent);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, getString(R.string.app_name),

                    NotificationManager.IMPORTANCE_DEFAULT);

            channel.setShowBadge(false);

            channel.setDescription("Foreground service is working");

            channel.setSound(null, null);

            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            manager.createNotificationChannel(channel);

        }

        startForeground(1, builder.build());

    }

    public class MyBinder extends Binder {

        public ForegroundService getService() {

            return ForegroundService.this;

        }

    }

}


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.surabhiglobal.foregroundserviceexample">

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ForegroundServiceExample">

        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".ForegroundService"
            android:enabled="true"
            android:exported="false"/>

    </application>

</manifest>

Background location tracking in android even if the app get closed

  


activity_main.xml

<?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:orientation="vertical"

    tools:context=".MainActivity">


    <Button

        android:id="@+id/btn_get"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Get Location"

        android:layout_margin="20sp"/>


</LinearLayout>


MainActivity.java

import androidx.appcompat.app.AppCompatActivity;


import android.Manifest;

import android.app.AlertDialog;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.content.IntentSender;

import android.location.LocationManager;

import android.net.Uri;

import android.os.Bundle;

import android.provider.Settings;

import android.view.View;

import android.widget.Button;


import com.google.android.gms.common.api.ResolvableApiException;

import com.google.android.gms.location.LocationRequest;

import com.google.android.gms.location.LocationServices;

import com.google.android.gms.location.LocationSettingsRequest;

import com.google.android.gms.location.LocationSettingsResponse;

import com.karumi.dexter.Dexter;

import com.karumi.dexter.MultiplePermissionsReport;

import com.karumi.dexter.PermissionToken;

import com.karumi.dexter.listener.PermissionRequest;

import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

import java.util.List;


public class MainActivity extends AppCompatActivity {

    private Button btn_get;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


        btn_get = findViewById(R.id.btn_get);

        btn_get.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

                    enableLocationSettings();

                } else {

                    requestAppPermissions();

                }

            }

        });

    }

    private void requestAppPermissions() {

        Dexter.withActivity(MainActivity.this)

                .withPermissions(

                        Manifest.permission.ACCESS_FINE_LOCATION,

                        Manifest.permission.ACCESS_COARSE_LOCATION)

                .withListener(new MultiplePermissionsListener() {

                    @Override

                    public void onPermissionsChecked(MultiplePermissionsReport report) {

                        // check if all permissions are granted

                        if (report.areAllPermissionsGranted()) {

                            // do you work now

                            //interact.downloadImage(array);

                            startService(new Intent(MainActivity.this, ForegroundService.class));

                        }


                        // check for permanent denial of any permission

                        if (report.isAnyPermissionPermanentlyDenied()) {

                            // permission is denied permenantly, navigate user to app settings

                            showSettingsDialog();

                            //finish();

                        }

                    }

                    @Override

                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {

                        token.continuePermissionRequest();

                    }

                })

                .onSameThread()

                .check();

    }

    private void showSettingsDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        builder.setTitle("Need Permissions");

        builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");

        builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();

                openSettings();

            }

        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();

            }

        });

        builder.show();

    }

    private void openSettings() {

        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);

        Uri uri = Uri.fromParts("package", getPackageName(), null);

        intent.setData(uri);

        startActivityForResult(intent, 101);

    }

    protected void enableLocationSettings() {

        LocationRequest locationRequest = LocationRequest.create()

                .setInterval(1000)

                .setFastestInterval(3000)

                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()

                .addLocationRequest(locationRequest);

        LocationServices

                .getSettingsClient(this)

                .checkLocationSettings(builder.build())

                .addOnSuccessListener(this, (LocationSettingsResponse response) -> {

                    // startUpdatingLocation(...);

                })

                .addOnFailureListener(this, ex -> {

                    if (ex instanceof ResolvableApiException) {

                        // Location settings are NOT satisfied,  but this can be fixed  by showing the user a dialog.

                        try {

                            // Show the dialog by calling startResolutionForResult(),  and check the result in onActivityResult().

                            ResolvableApiException resolvable = (ResolvableApiException) ex;

                            resolvable.startResolutionForResult(this, 123);

                        } catch (IntentSender.SendIntentException sendEx) {

                            // Ignore the error.

                        }

                    }

                });

    }

}


ForegroundService.java


import android.Manifest;

import android.app.NotificationChannel;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.app.Service;

import android.content.Intent;

import android.content.pm.PackageManager;

import android.os.Binder;

import android.os.Build;

import android.os.IBinder;

import android.widget.Toast;


import androidx.core.app.NotificationCompat;

import androidx.core.content.ContextCompat;


import com.google.android.gms.location.FusedLocationProviderClient;

import com.google.android.gms.location.LocationCallback;

import com.google.android.gms.location.LocationRequest;

import com.google.android.gms.location.LocationResult;

import com.google.android.gms.location.LocationServices;


public class ForegroundService extends Service {


    private final IBinder mBinder = new MyBinder();

    private static final String CHANNEL_ID = "2";


    @Override

    public IBinder onBind(Intent intent) {

        return mBinder;

    }


    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {

        return START_STICKY;

    }


    @Override

    public void onCreate() {

        super.onCreate();

        buildNotification();

        requestLocationUpdates();

    }


    private void buildNotification() {

        String stop = "stop";

        PendingIntent broadcastIntent = PendingIntent.getBroadcast(

                this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);

        // Create the persistent notification

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)

                .setContentTitle(getString(R.string.app_name))

                .setContentText("Location tracking is working")

                .setOngoing(true)

                .setContentIntent(broadcastIntent);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, getString(R.string.app_name),

                    NotificationManager.IMPORTANCE_DEFAULT);

            channel.setShowBadge(false);

            channel.setDescription("Location tracking is working");

            channel.setSound(null, null);

            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            manager.createNotificationChannel(channel);

        }


        startForeground(1, builder.build());

    }

    private void requestLocationUpdates() {

        LocationRequest request = new LocationRequest();

        request.setInterval(1000);

        request.setFastestInterval(3000);

        request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);

        int permission = ContextCompat.checkSelfPermission(this,

                Manifest.permission.ACCESS_FINE_LOCATION);

        if (permission == PackageManager.PERMISSION_GRANTED) {

            // Request location updates and when an update is

            // received, store the location in Firebase

            client.requestLocationUpdates(request, new LocationCallback() {

                @Override

                public void onLocationResult(LocationResult locationResult) {


                    String location = "Latitude : " + locationResult.getLastLocation().getLatitude() +

                            "\nLongitude : " + locationResult.getLastLocation().getLongitude();


                    Toast.makeText(ForegroundService.this, location, Toast.LENGTH_SHORT).show();

                }

            }, null);

        } else {

            stopSelf();

        }

    }

    public class MyBinder extends Binder {

        public ForegroundService getService() {

            return ForegroundService.this;

        }

    }

}


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.surabhiglobal.foregroundserviceexample">


    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />


    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/Theme.ForegroundServiceExample">


        <activity

            android:name=".MainActivity"

            android:configChanges="orientation|screenSize">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

        <service

            android:name=".ForegroundService"

            android:enabled="true"

            android:exported="false"/>

    </application>

</manifest>


build.gradle (app level file)

plugins {
    id 'com.android.application'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.surabhiglobal.foregroundserviceexample"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

    //add this two dependencies
    implementation 'com.google.android.gms:play-services-location:18.0.0'
    implementation 'com.karumi:dexter:4.2.0'

}

Capture photos in android without opening camera

 



activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 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"

    tools:context=".MainActivity">


    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:orientation="horizontal"

        android:weightSum="2"

        android:layout_margin="10dp">


        <Button

            android:id="@+id/btn_front"

            android:layout_width="0dp"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            android:text="Front Camera"

            android:layout_marginEnd="10dp" />


        <Button

            android:id="@+id/btn_back"

            android:layout_width="0dp"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            android:text="Back Camera" />

    </LinearLayout>


    <ImageView

        android:id="@+id/iv_image"

        android:layout_width="250dp"

        android:layout_height="250dp"

        android:layout_centerInParent="true"/>


</RelativeLayout>


MainActivity.java

package com.surabhiglobal.example;


import android.Manifest;

import android.app.AlertDialog;

import android.content.DialogInterface;

import android.content.Intent;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.graphics.SurfaceTexture;

import android.hardware.Camera;

import android.net.Uri;

import android.os.Bundle;

import android.provider.Settings;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.ImageView;


import androidx.appcompat.app.AppCompatActivity;


import com.karumi.dexter.Dexter;

import com.karumi.dexter.MultiplePermissionsReport;

import com.karumi.dexter.PermissionToken;

import com.karumi.dexter.listener.PermissionRequest;

import com.karumi.dexter.listener.multi.MultiplePermissionsListener;


import java.util.List;


public class MainActivity extends AppCompatActivity {


    private Button btn_front, btn_back;

    private String TAG = MainActivity.class.getName();

    private ImageView iv_image;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        btn_front = findViewById(R.id.btn_front);

        btn_back = findViewById(R.id.btn_back);

        iv_image = findViewById(R.id.iv_image);


        btn_front.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                requestAppPermissions("1");

            }

        });


        btn_back.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                requestAppPermissions("0");

            }

        });

    }


    private void requestAppPermissions(String type) {


        Dexter.withActivity(MainActivity.this)

                .withPermissions(

                        Manifest.permission.CAMERA)

                .withListener(new MultiplePermissionsListener() {

                    @Override

                    public void onPermissionsChecked(MultiplePermissionsReport report) {

                        if (report.areAllPermissionsGranted()) {

                            if (type.equals("0")) {

                                CaptureBackPhoto();

                            } else {

                                CaptureFrontPhoto();

                            }

                        }

                        // check for permanent denial of any permission

                        if (report.isAnyPermissionPermanentlyDenied()) {

                            // permission is denied permenantly, navigate user to app settings

                            showSettingsDialog();

                        }

                    }


                    @Override

                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {

                        token.continuePermissionRequest();

                    }


                })

                .onSameThread()

                .check();



    }


    private void showSettingsDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        builder.setTitle("Need Permissions");

        builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");

        builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();

                openSettings();

            }

        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();

            }

        });

        builder.show();


    }


    private void openSettings() {

        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);

        Uri uri = Uri.fromParts("package", getPackageName(), null);

        intent.setData(uri);

        startActivityForResult(intent, 101);

    }



    private void CaptureFrontPhoto() {


        Log.d(TAG, "Preparing to take photo");

        Camera camera = null;


        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();


        int frontCamera = 1;

        //int backCamera=0;


        Camera.getCameraInfo(frontCamera, cameraInfo);


        try {

            camera = Camera.open(frontCamera);

            camera.enableShutterSound(false);

        } catch (RuntimeException e) {

            Log.d(TAG, "Camera not available: " + 1);

            camera = null;

            //e.printStackTrace();

        }

        try {

            if (null == camera) {

                Log.d(TAG, "Could not get camera instance");

            } else {

                Log.d(TAG, "Got the camera, creating the dummy surface texture");

                try {

                    camera.setPreviewTexture(new SurfaceTexture(0));

                    camera.startPreview();

                } catch (Exception e) {

                    Log.d(TAG, "Could not set the surface preview texture");

                    e.printStackTrace();

                }

                camera.takePicture(null, null, new Camera.PictureCallback() {


                    @Override

                    public void onPictureTaken(byte[] data, Camera camera) {


                        try {

                            Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);

                            iv_image.setImageBitmap(bmp);


                        } catch (Exception e) {

                            System.out.println(e.getMessage());

                        }


                        camera.release();

                    }

                });

            }


        } catch (Exception e) {

            camera.release();

        }

    }


    private void CaptureBackPhoto() {


        Log.d(TAG, "Preparing to take photo");

        Camera camera = null;


        try {

            camera = Camera.open();

            camera.enableShutterSound(false);

        } catch (RuntimeException e) {

            Log.d(TAG, "Camera not available: " + 1);

            camera = null;

            //e.printStackTrace();

        }

        try {

            if (null == camera) {

                Log.d(TAG, "Could not get camera instance");

            } else {

                Log.d(TAG, "Got the camera, creating the dummy surface texture");

                try {

                    camera.setPreviewTexture(new SurfaceTexture(0));

                    camera.startPreview();

                } catch (Exception e) {

                    Log.d(TAG, "Could not set the surface preview texture");

                    e.printStackTrace();

                }

                camera.takePicture(null, null, new Camera.PictureCallback() {


                    @Override

                    public void onPictureTaken(byte[] data, Camera camera) {


                        try {

                            Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);


                            iv_image.setImageBitmap(bmp);


                        } catch (Exception e) {

                            System.out.println(e.getMessage());

                        }


                        camera.release();

                    }

                });

            }


        } catch (Exception e) {

            camera.release();

        }

    }

}


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.surabhiglobal.example">


    <uses-permission android:name="android.permission.CAMERA"/>

    <uses-feature android:name="android.hardware.camera" />


    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/Theme.ForegroundServiceExample">


        <activity

            android:name=".MainActivity"

            android:configChanges="orientation|screenSize">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

</manifest>


build.gradle (app level file)

plugins {

    id 'com.android.application'

}

android {

    compileSdkVersion 30

    buildToolsVersion "30.0.3"


    defaultConfig {

        applicationId "com.surabhiglobal.example"

        minSdkVersion 17

        targetSdkVersion 30

        versionCode 1

        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

    }

    buildTypes {

        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

        }

    }

    compileOptions {

        sourceCompatibility JavaVersion.VERSION_1_8

        targetCompatibility JavaVersion.VERSION_1_8

    }

}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.2.0'

    implementation 'com.google.android.material:material:1.3.0'

    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'

    testImplementation 'junit:junit:4.13.2'

    androidTestImplementation 'androidx.test.ext:junit:1.1.2'

    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

    //add this dependency

    implementation 'com.karumi:dexter:4.2.0'

}

Friday 16 November 2018

Keyboard Shortcut for Android Studio in Windows & Mac Osx

By using keyboard shortcuts of Android Studio you can increase the productivity and you can do so many tasks in short period of time.
Here you can see some of the shortcuts of android studio in windows and Mac.
Please comment shortcuts whatever i missed here.
thanking you..
DescriptionWindows/LinuxMac
General
Save allControl + SCommand + S
SynchronizeControl + Alt + YCommand + Option + Y
Maximize/minimize editorControl + Shift + F12Control + Command + F12
Add to favoritesAlt + Shift + FOption + Shift + F
Inspect current file with current profileAlt + Shift + IOption + Shift + I
Quick switch schemeControl + ` (backquote)Control + ` (backquote)
Open settings dialogueControl + Alt + SCommand + , (comma)
Open project structure dialogControl + Alt + Shift + SCommand + ; (semicolon)
Switch between tabs and tool windowControl + TabControl + Tab
Navigating and Searching Within
Studio
Search everything (including code and menus)Press Shift twicePress Shift twice
FindControl + FCommand + F
Find nextF3Command + G
Find previousShift + F3Command + Shift + G
ReplaceControl + RCommand + R
Find actionControl + Shift + ACommand + Shift + A
Search by symbol nameControl + Alt + Shift + NCommand + Option + O
Find classControl + NCommand + O
Find file (instead of class)Control + Shift + NCommand + Shift + O
Find in pathControl + Shift + FCommand + Shift + F
Open file structure pop-upControl + F12Command + F12
Navigate between open editor tabsAlt + Right/Left ArrowControl + Right/Left Arrow
Jump to sourceF4 / Control + EnterF4 / Command + Down Arrow
Open current editor tab in new windowShift + F4Shift + F4
Recently opened files pop-upControl + ECommand + E
Recently edited files pop-upControl + Shift + ECommand + Shift + E
Go to last edit locationControl + Shift + BackspaceCommand + Shift + Backspace
Close active editor tabControl + F4Command + W
Return to editor window from a tool windowEscEsc
Hide active or last active tool windowShift + EscShift + Esc
Go to lineControl + GCommand + L
Open type hierarchyControl + HControl + H
Open method hierarchyControl + Shift + HCommand + Shift + H
Open call hierarchyControl + Alt + HControl + Option + H
Writing Code
Generate code (getters, setters, constructors, hashCode/equals, toString, new file, new class)Alt + InsertCommand + N
Override methodsControl + OControl + O
Implement methodsControl + IControl + I
Surround with (if…else / try…catch / etc.)Control + Alt + TCommand + Option + T
Delete line at caretControl + YCommand + Backspace
Collapse/expand current code blockControl + minus/plusCommand + minus/plus
Collapse/expand all code blocksControl + Shift + minus/plusCommand + Shift + minus/plus
Duplicate current line or selectionControl + DCommand + D
Basic code completionControl + SpaceControl + Space
Smart code completion (filters the list of methods and variables by expected type)Control + Shift + SpaceControl + Shift + Space
Complete statementControl + Shift + EnterCommand + Shift + Enter
Quick documentation lookupControl + QControl + J
Show parameters for selected methodControl + PCommand + P
Go to declaration (directly)Control + B or Control + ClickCommand + B or Command + Click
Go to implementationsControl + Alt + BCommand + Alt + B
Go to super-method/super-classControl + UCommand + U
Open quick definition lookupControl + Shift + ICommand + Y
Toggle project tool window visibilityAlt + 1Command + 1
Toggle bookmarkF11F3
Toggle bookmark with mnemonicControl + F11Option + F3
Comment/uncomment with line commentControl + /Command + /
Comment/uncomment with block commentControl + Shift + /Command + Shift + /
Select successively increasing code blocksControl + WOption + Up
Decrease current selection to previous stateControl + Shift + WOption + Down
Move to code block startControl + [Option + Command + [
Move to code block endControl + ]Option + Command + ]
Select to the code block startControl + Shift + [Option + Command + Shift + [
Select to the code block endControl + Shift + ]Option + Command + Shift + ]
Delete to end of wordControl + DeleteOption + Delete
Delete to start of wordControl + BackspaceOption + Backspace
Optimize importsControl + Alt + OControl + Option + O
Project quick fix (show intention actions and quick fixes)Alt + EnterOption + Enter
Reformat codeControl + Alt + LCommand + Option + L
Auto-indent linesControl + Alt + IControl + Option + I
Indent/unindent linesTab/Shift + TabTab/Shift + Tab
Smart line joinControl + Shift + JControl + Shift + J
Smart line splitControl + EnterCommand + Enter
Start new lineShift + EnterShift + Enter
Next/previous highlighted errorF2 / Shift + F2F2 / Shift + F2
Build and Run
BuildControl + F9Command + F9
Build and runShift + F10Control + R
Apply changes (with Instant Run)Control + F10Control + Command + R
Debugging
DebugShift + F9Control + D
Step overF8F8
Step intoF7F7
Smart step intoShift + F7Shift + F7
Step outShift + F8Shift + F8
Run to cursorAlt + F9Option + F9
Evaluate expressionAlt + F8Option + F8
Resume programF9Command + Option + R
Toggle breakpointControl + F8Command + F8
View breakpointsControl + Shift + F8Command + Shift + F8
Refactoring
CopyF5F5
MoveF6F6
Safe deleteAlt + DeleteCommand + Delete
RenameShift + F6Shift + F6
Change signatureControl + F6Command + F6
InlineControl + Alt + NCommand + Option + N
Extract methodControl + Alt + MCommand + Option + M
Extract variableControl + Alt + VCommand + Option + V
Extract fieldControl + Alt + FCommand + Option + F
Extract constantControl + Alt + CCommand + Option + C
Extract parameterControl + Alt + PCommand + Option + P
Version Control / Local
History
Commit project to VCSControl + KCommand + K
Update project from VCSControl + TCommand + T
View recent changesAlt + Shift + COption + Shift + C
Open VCS popupAlt + ` (backquote)Control + V

Alarm Manager Example in Android