Monday, 7 February 2022

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

Wednesday, 18 April 2018

TrackOne Mobile App


TrackOne

1) TrackOne is the Android App.

2) By using this app to track incoming and outgoing calls of others.

3) Install this app into others mobile.

4) Register your number and others name into this app.

5) Then after you got messages when others got incoming calls or other make outgoing calls (in message you got incoming and outgoing calls number of others)


Note: This is a paid app and this app is not available in playstore. anyone interest for this app send me your information to below details.


Contact:
7661000787
chanti.surabhi321@gmail.com

Saturday, 10 March 2018

Freelancing and Engineering Projects

Dear All,

              I am a leading senior android developer. I am very much interested to share my knowledge with u. All Engineering students please take this chance to create awesome mobile apps for your mini and main projects. All startups please take this chance to create new projects.

Note : I will give u any time support. Interested persons please contact me through below information.

Actually i am very much busy with my projects thats why i am not posting new tutorials. Sorry for delay from now i will post tutorials weekly once. Please support me.

Thank you all for reaching my blog viewers 10000+

My Contact Details,
Mobile no : 7661000787
Email ID : chanti.surabhi321@gmail.com

Saturday, 30 September 2017

Material Navigation Drawer example in Android




activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />


</android.support.v4.widget.DrawerLayout>


app_bar_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    tools:context="com.chantisandroid.exampleapp.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.chantisandroid.exampleapp.MainActivity"
    tools:showIn="@layout/app_bar_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>


nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        app:srcCompat="@android:drawable/sym_def_app_icon" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="Android Studio"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android.studio@android.com" />

</LinearLayout>


Create one menu folder under res folder 
Under menu folder create below two xml files

activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_camera"
            android:icon="@drawable/ic_menu_camera"
            android:title="Import" />
        <item
            android:id="@+id/nav_gallery"
            android:icon="@drawable/ic_menu_gallery"
            android:title="Gallery" />
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="Slideshow" />
        <item
            android:id="@+id/nav_manage"
            android:icon="@drawable/ic_menu_manage"
            android:title="Tools" />
    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_menu_share"
                android:title="Share" />
            <item
                android:id="@+id/nav_send"
                android:icon="@drawable/ic_menu_send"
                android:title="Send" />
        </menu>
    </item>

</menu>


main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>


MainActivity
package com.chantisandroid.exampleapp;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}



build.gradle(Module: app)
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.chantisandroid.exampleapp"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}



NOTE:

For images you can download your own PNG images and add to in drawable folder it is under res folder

Alarm Manager Example in Android