Tuesday 18 June 2019

Device's Estimated Battery Time calculation

How to Calculate Android Estimated Battery Remaining Time. 


within your AppCompatActivity

need to do register Battery change event listener with BroadcastReceiver like  
this.registerReceiver(this.mBatInfoReceiver, 
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
Now you need to declare with Activity or where you need BroadcastReceiver 
int expectedlevel;
boolean isFirstAllow = true;
int second;

String strFirstTime,strSecondTime;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override    public void onReceive(Context ctxt, Intent intent) {
        
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);

        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Calendar c = Calendar.getInstance();

        if(isFirstAllow) {

            String formattedDate = format.format(c.getTime());
            strFirstTime  = formattedDate;

            expectedlevel = level - 1;
            isFirstAllow = false;
            second = new Time(System.currentTimeMillis()).getSeconds();
        }

        if(!isFirstAllow && level == expectedlevel){

            strSecondTime  = format.format(c.getTime());

            Date d1 = null;
            Date d2 = null;

            try {
                d1 = format.parse(strFirstTime);
                d2 = format.parse(strSecondTime);

                //in milliseconds               
               long diff = d2.getTime() - d1.getTime();

                long diffSeconds = diff / 1000 % 60;
                long diffMinutes = diff / (60 * 1000) % 60;
                long diffHours = diff / (60 * 60 * 1000) % 24;
                long diffDays = diff / (24 * 60 * 60 * 1000);

                System.out.print(diffDays + " days, ");
                System.out.print(diffHours + " hours, ");
                System.out.print(diffMinutes + " minutes, ");
                System.out.print(diffSeconds + " seconds.");

       // Now again we need percentage * difference time  = total long time value.
                long totalMinues =  diffMinutes * expectedlevel;
                long totalSecond  = diffSeconds * expectedlevel;
                long converttoMinutes = totalSecond/60;
                long addedAllMinues = totalMinues + converttoMinutes;

                // Now convert total minitues to millisecond;                
                 long AllMillisond = addedAllMinues * 60000;
     // Now Again convert this total Millisond to hours,minutes, second
                // for Battery Hours;
                long FinaldiffSeconds = AllMillisond / 1000 % 60;
                long FinaldiffMinutes = AllMillisond / (60 * 1000) % 60;
                long FinaldiffHours = AllMillisond / (60 * 60 * 1000) % 24;
                long FinaldiffDays = AllMillisond / (24 * 60 * 60 * 1000);

                System.out.print(FinaldiffDays + " days, ");
                System.out.print(FinaldiffHours + " hours, ");
                System.out.print(FinaldiffMinutes + " minutes, ");
                System.out.print(FinaldiffSeconds + " seconds.");

new AlertDialog.Builder(mcontext)
.setTitle("Battery Remaning Time") .setMessage(FinaldiffDays + " days, "+""+FinaldiffHours + " hours," + ""+""+FinaldiffMinutes + " minutes, "+FinaldiffSeconds + " seconds.") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Continue with delete operation } }) .setNegativeButton(android.R.string.no, null) .setIcon(android.R.drawable.ic_dialog_alert) .show();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }
};

Apply Multiple Permissions RunTime

How to  give and apply run time multiple permissions in android,

First yo have to add permissions in Manifest file like below.

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

Then, you have to code for the check permissions,add button in activitymain.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout    
xmlns:android="http://schemas.android.com/apk/res/android"    
android:id="@+id/root_layout"    
android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:padding="16dp"    
android:orientation="vertical"    
android:background="#e5ead3"   
android:gravity="center" >
    
<Button        
android:id="@+id/btn_do_task"        
android:layout_width="wrap_content"        
android:layout_height="wrap_content"        
android:text="Check Permissions"        
android:layout_gravity="center"/>
</LinearLayout>

After add button in xml file now add code in MainActivity.java file

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private Activity mActivity;

    private Button btn_checkpermi;

    private static final int MY_PERMISSIONS_REQUEST_CODE = 123;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = getApplicationContext();
        mActivity = MainActivity.this;
        
        btn_checkpermi = findViewById(R.id.btn_checkpermi);

        btn_checkpermi.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    checkPermission();
                }
            }
        });
    }

    protected void checkPermission(){
        if(ContextCompat.checkSelfPermission(mActivity,Manifest.permission.CAMERA)
                + ContextCompat.checkSelfPermission(
                mActivity,Manifest.permission.READ_CONTACTS)
                + ContextCompat.checkSelfPermission(
                mActivity,Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){

            // when permissions not granted            
             if(ActivityCompat.shouldShowRequestPermissionRationale(
                    mActivity,Manifest.permission.CAMERA)
                    || ActivityCompat.shouldShowRequestPermissionRationale(
                    mActivity,Manifest.permission.READ_CONTACTS)
                    || ActivityCompat.shouldShowRequestPermissionRationale(
                    mActivity,Manifest.permission.READ_EXTERNAL_STORAGE)){
                // If we should give explanation of requested permissions
                // Show an alert dialog for request explanation                
                AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                builder.setMessage("Camera, Read Contacts and Read External" +
                        " Storage permissions are required to do the task.");
                builder.setTitle("Please grant those permissions");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() 
                {
                    @Override                    
                public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityCompat.requestPermissions(
                                mActivity,
                                new String[]{
                                        Manifest.permission.CAMERA,
                                        Manifest.permission.READ_CONTACTS,
                                        Manifest.permission.READ_EXTERNAL_STORAGE },
                                MY_PERMISSIONS_REQUEST_CODE  );
                    }
                });
                builder.setNeutralButton("Cancel",null);
                AlertDialog dialog = builder.create();
                dialog.show();
            }else{
                //  request directly required permissions                
                        ActivityCompat.requestPermissions(
                        mActivity,
                        new String[]{
                                Manifest.permission.CAMERA,
                                Manifest.permission.READ_CONTACTS,
                                Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_CODE );
            }
        }else {
            // Do your stuff here, permissions are already granted            
     Toast.makeText(mContext,"Permissions already granted",Toast.LENGTH_SHORT).show();
        }
    }

    @Override    
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
        switch (requestCode){
            case MY_PERMISSIONS_REQUEST_CODE:{
                // When request is cancelled, the results array are empty                
                    if(
                        (grantResults.length >0) &&
                                (grantResults[0]
                                        + grantResults[1]
                                        + grantResults[2]
                                        == PackageManager.PERMISSION_GRANTED                                )
                ){
                    // Permissions are granted                    
                    Toast.makeText(mContext,"Permissions granted.",Toast.LENGTH_SHORT).show();
                }else {
                    // Permissions are denied                    
                   Toast.makeText(mContext,"Permissions denied.",Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }
}

How to Bitmap Compress reduce size and Compress format

Here you can reduce Bitmap Size and Compress in specific file format

Button click take Camera Picture in Fragment and Save on External Storage

Fragment 
do with below Button Click code


mCamerabtn.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());


        if (checkPermission(wantCameraPermission)) {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File file = new File(Environment.getExternalStorageDirectory(),"test.jpg");

            outputFileUri = Uri.fromFile(file);

            Log.d("TAG", "outputFileUri intent" + outputFileUri);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivityForResult(intent, 111);

        } else {

            requestPermission(wantCameraPermission, PERMISSION_REQUEST_CODE_Camera);
        }

        dialog.cancel();

    }

});

Check for require permission above 6.0

private boolean checkPermission(String permission) {
    if (Build.VERSION.SDK_INT >= 23) {
        int result = ContextCompat.checkSelfPermission(mcontext, permission);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {

            return false;
        }
    } else {
        return true;
    }
}

private void requestPermission(String permission, int permission_requestcode) {

        requestPermissions(new String[]{permission}, permission_requestcode);
}

@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grants) {
    List<Fragment> fragments = getChildFragmentManager().getFragments();

    //==================Start
    switch (requestCode) {

        case PERMISSION_REQUEST_CODE_Camera:


            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File file = new File(Environment.getExternalStorageDirectory(),

                    "test.jpg");

            outputFileUri = Uri.fromFile(file);
            Log.d("TAG", "outputFileUri intent" + outputFileUri);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            getActivity().startActivityForResult(intent, 111);

            break;
        case PERMISSION_REQUEST_CODE:
            if (grants.length > 0 && grants[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(mcontext, "Permission Granted. Now you can Read data.",
                        Toast.LENGTH_LONG).show();

                ImageLoad();
            } else {
                Toast.makeText(mcontext, "Permission Denied. You cannot Read data.",
                        Toast.LENGTH_LONG).show();
            }
            break;
    }

    //================End
    if (fragments != null) {
        for (Fragment fragment : fragments) {
            if (fragment != null) {
                fragment.onRequestPermissionsResult(requestCode, permissions, grants);


            }
        }
    }
}


After Intent pass, we can Create Bitmap from Uri Code within onActivityResult


@Overridepublic void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {

        case 111:
if (resultCode == RESULT_OK) {

    Log.d("TAG", "outputFileUri RESULT_OK" + outputFileUri);

    if (outputFileUri != null) {

    Bitmap bitmap = decodeSampledBitmapFromUri(outputFileUri300400);

      // Now this Bitmap you can set as per need in Imageview  imagePhoto
    imagePhoto.setImageBitmap(bitmap);

 break;
}
}


Here in below function we  need to pass Uri, int reqWidth, int reqHeight

public Bitmap decodeSampledBitmapFromUri(Uri uri, int reqWidth, int reqHeight) {
        Bitmap bm = null;

        try {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(((AppCompatActivity) mcontext).getContentResolver().openInputStream(uri), null, options);
            // Calculate inSampleSize            
           options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
            // Decode bitmap with inSampleSize set            
            options.inJustDecodeBounds = false;

            bm = BitmapFactory.decodeStream(((AppCompatActivity) mcontext).getContentResolver().openInputStream(uri), null, options);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(mcontext, e.toString(), Toast.LENGTH_LONG).show();
        }
        return bm;

    }
      

Saturday 15 June 2019

Android TextToSpeech

Android Text to Speech is the speech the text which ever you want.

below is the code for Text to speech. 


public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener{
TextToSpeech textToSpeech;
@Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);
    textToSpeech = new TextToSpeech(mcontext, MainActivity.this);
TextToSpeechFunction();
}
public void TextToSpeechFunction() {     String textholder = "Test the TextToSpeech";
    textToSpeech.speak(textholder, TextToSpeech.QUEUE_FLUSH, null);   //  Toast.makeText(MainActivity.this , textholder, Toast.LENGTH_LONG).show(); } @Override public void onDestroy() {     textToSpeech.shutdown();     super.onDestroy(); } public void onInit(int Text2SpeechCurrentStatus) {     if (Text2SpeechCurrentStatus == TextToSpeech.SUCCESS) {         textToSpeech.setLanguage(Locale.US);         TextToSpeechFunction();     } }
}

Friday 14 June 2019

Recycle Listview with dynamic listview raw

Recycle listview is the listview better than a simple list view now here is the code to create Recycle listview with dynamic listview raw. 

First need to add Recycle listview library in build.gradle(Module:app) file


dependencies {

implementation 'androidx.recyclerview:recyclerview:1.1.0'

}


Then in activity_main.xml file add below code


<androidx.recyclerview.widget.RecyclerView
 android:id="@+id/rvalphabets"  
 android:layout_width="match_parent"
 android:layout_height="match_parent"/>

Then make new xml file recycleview_row.xml and add below code


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"    
 android:layout_height="wrap_content" 
 android:orientation="horizontal"
 android:padding="10dp"    
 android:layout_gravity="center"    
 android:gravity="center">

 <TextView android:id="@+id/tvandroidversionname"
  android:layout_width="match_parent"        
  android:layout_height="wrap_content"        
  android:layout_gravity="center"        
  android:gravity="center"        
  android:text=""        
  android:textSize="35sp"        
  android:textStyle="bold"        
  android:textColor="@color/colorPrimary"/>
    
 <ImageView android:id="@+id/imgview"
  android:layout_width="200dp"        
  android:layout_height="200dp"        
  android:layout_gravity="center"        
  android:gravity="center"        
  android:visibility="gone"/>
</LinearLayout>

Then make new xml file customdialog.xml and add below code


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"    
    android:layout_height="200dp"    
    android:padding="10dp"    
    android:background="@android:color/white">

    <FrameLayout android:id="@+id/frmcustom"
      android:layout_width="match_parent"        
      android:layout_height="200dp"        
      android:background="@color/colorPrimary">
    <ImageButton  android:id="@+id/closebtn"        
         android:layout_width="25dp"        
         android:layout_height="25dp"        
         android:layout_gravity="top|right"        
         android:layout_margin="10dp"
        android:background="@android:drawable/ic_menu_close_clear_cancel"/>

    <TextView  android:id="@+id/tvdialogName"        
       android:layout_width="match_parent"        
       android:layout_height="wrap_content"        
       android:layout_gravity="center"        
       android:gravity="center"        
       android:layout_below="@+id/closebtn"        
       android:text=""        
       android:textSize="25sp"        
       android:padding="10dp"        
       android:textStyle="bold"        
       android:layout_marginTop="20dp"        
       android:textColor="@android:color/white"/>
    </FrameLayout>
</RelativeLayout>

And then make one Adapter for recycle list view 
MyRecycleViewAdapter.java and add below code


import android.content.Context;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class MyRecyclerViewAdapter extends 
RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private List<String> mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;
    Context mContext;

    // data is passed into the constructor    
MyRecyclerViewAdapter(Context context, List<String> data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
        mContext = context;
    }

    // inflates the row layout from xml when needed    
@Override    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each row    
@Override    public void onBindViewHolder(ViewHolder holder, int position) {
        String alphabet = mData.get(position);
        holder.myTextView.setText(alphabet);
    }

    // total number of rows    @Override    public int getItemCount() {
        return mData.size();
    }


    // stores and recycles views as they are scrolled off screen    
public class ViewHolder extends RecyclerView.ViewHolder 
implements View.OnClickListener {
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.tvAlphabetsName);
            itemView.setOnClickListener(this);

        }

        @Override        public void onClick(View view) {
            if (mClickListener != null) 
mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // convenience method for getting data at click position    
String getItem(int id) {
        return mData.get(id);
    }

    // allows clicks events to be caught    
void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events    
public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

And final code in MainActivity.java

import android.app.Dialog;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements 
MyRecyclerViewAdapter.ItemClickListener{

    Context mcontext;
    MyRecyclerViewAdapter adapter;
    String gettext;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mcontext =  MainActivity.this;

        // data to populate the RecyclerView with       
 ArrayList<String> alphabetsNames = new ArrayList<>();
        alphabetsNames.add("Android Cupcake.");
        alphabetsNames.add("Android Donut.");
        alphabetsNames.add("Android Eclair.");
        alphabetsNames.add("Android Froyo.");
        alphabetsNames.add("Android Gingerbread.");
        alphabetsNames.add("Android Honeycomb.");
        alphabetsNames.add("Android Ice Cream Sandwich.");
        alphabetsNames.add("Android Jelly Bean.");

        alphabetsNames.add("Android KitKat");
        alphabetsNames.add("Android Lollipop");
        alphabetsNames.add("Android Marshmallow");
        alphabetsNames.add("Android Nougat");
        alphabetsNames.add("Android Oreo");
        alphabetsNames.add("Android Pie");

        // set up the RecyclerView       
 RecyclerView recyclerView = findViewById(R.id.tvandroidversionname);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        adapter = new MyRecyclerViewAdapter(this, alphabetsNames);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);

    }
    @Override    public void onItemClick(View view, int position) {

        gettext = adapter.getItem(position);
        // custom dialog        final Dialog dialog = new Dialog(mcontext);
        dialog.setContentView(R.layout.customdialog);
        // set the custom dialog components - text, image and button        



TextView text = (TextView) dialog.findViewById(R.id.tvdialogName);
        ImageButton closebtn = (ImageButton)dialog.findViewById(R.id.closebtn);
        text.setText(gettext);
        closebtn.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();

    }
}



Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...