Friday, July 31, 2020

JAVA Code to find distance between two GPS Coordinates

Here is a JAVA Program to find the distance between two GPS Coordinates.



       static double latitude1 = 40.6971494;
       static double latitude2 = 19.0821978;
       static double longitude1 = -74.2598702;
       static double longitude2 = 72.7410985;


 public static void findDistance()
        {

            double lon1 = Math.toRadians(longitude1);
            double lon2 = Math.toRadians(longitude2);
            double  lat1 = Math.toRadians(latitude1);
            double  lat2 = Math.toRadians(latitude2);

 
            double dlon = lon2 - lon1;
            double dlat = lat2 - lat1;
            double a = Math.pow(Math.sin(dlat / 2), 2)
                    + Math.cos(lat1) * Math.cos(lat2)
                    * Math.pow(Math.sin(dlon / 2),2);

            double c = 2 * Math.asin(Math.sqrt(a));

            // Radius of earth in kilometers. Use 3956
            // for miles
            double r = 6371;

            // calculate the result
            double distance = c * r;
       
            System.out.println("Distance in KM : "+ Math.floor(distance));
            System.out.println("Distance in Miles : "+ Math.floor(distance*.621371));
            System.out.println("Distance in Nautical Miles : "+ Math.floor(distance*.539957));

        }

    

JAVA Code to convert Bytes into MB

Here is the JAVA Code to convert bytes in MB upto 1 decimal place.

public void getSizeInMB()
    {
        long sizeinBytes = 200*1024;
                long sizeInKB = sizeinBytes/1024;
                long sizeInMBInt = sizeInKB/1024;
                float sizeInMB = sizeInKB/1024.0f;
                String size = sizeInMB+"";

                int k = size.indexOf('.');
                size = sizeInMBInt+"."+size.charAt(k+1);
   
      System.out.print(size);
    }

JAVA Code to get Date with Month and Time



                                GregorianCalendar  gc=new GregorianCalendar();
    gc.setTimeInMillis(System.currentTimeMillis());

    int day=gc.get(Calendar.DAY_OF_MONTH);
    int month=gc.get(Calendar.MONTH)+1;
    int year=gc.get(Calendar.YEAR);
    int hour = gc.get(Calendar.HOUR_OF_DAY);
                                int minute = gc.get(Calendar.MINUTE);
                         
    String date="Date: "+day+"/"+month+"/"+year+" Time : "+hour+":"+minute;
                               
                                System.out.print(date);

Friday, July 24, 2020

Customizing a Snackbar in Android

In Android we can customize a Snackbar
We can change the Text Color, Action text color, Background color and chnage/add an image



 TextView mainTextView = (TextView) (mSnackBar.getView()).findViewById(android.support.design.R.id.snackbar_text);
            TextView actionTextView = (TextView) (mSnackBar.getView()).findViewById(android.support.design.R.id.snackbar_action);

// change background color
            mSnackBar.getView().setBackgroundColor(Color.WHITE);
            Typeface font = Typeface.createFromAsset(getAssets(), "LatoRegular.ttf");
// Change the Font
            mainTextView.setTypeface(font);
            actionTextView.setTypeface(font);
// Change the colors
            mainTextView.setTextColor(Color.BLACK);
            actionTextView.setTextColor(Color.BLACK);

Snackbar in Android

How to use Snackbar in Android


Snackbar is used to show some information or feedback about an operation.
Toasts can also be used for the same purpose, but Snackbar privides more features and optiona than Toasts.

There are basically 3 parts of Snackbar

View : The view used to make the snackbar
Text : The message, Feedback or Info that you want to shoe
Time : How long the Snackbar is to show.

   There are 3 options for time

LENGTH_INDEFINITE (Show the snackbar until it's either dismissed or another snackbar is shown)
LENGTH_LONG (Show the snackbar for a long period of time)
LENGTH_SHORT (Show the snackbar for a short period of time)

you can see detail aboy Snackbar class and methods here at   Snackbar in Android

How to make a Snackbar

Snackbar.make(view, R.string.text_label, Snackbar.LENGTH_SHORT) .show()
How to add an action to Snackbar

Snackbar.make(view, R.string.text_label, Snackbar.LENGTH_LONG)
    .setAction(R.string.action_text) {
        // Responds to click on the action
    }
    .show()

Positioning a Snackbar

By default, Snackbars will be placed at  the bottom edge of their parent view. However, you can use the setAnchorView method to make a Snackbar appear above a specific view within your layout, e.g. a Button.

Snackbar.make(...)
    .setAnchorView(button)

Sunday, July 19, 2020

How to Check GPS Status in Android

How to check GPS/ Location Service is Enabled in Android



In Android, It is very easy to check whether GPS or Location Service are enabled or not.

For this we need to declare Location related permission in Manifest

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


Method to check GPS in ANDROID


public boolean checkGPSGPSEnabled()
{

    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    boolean isGPSenabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    Log.i("KAMLESH","Location Enabled "+isGPSenabled);
    return isGPSenabled;
}

Tuesday, July 14, 2020

How to check Internet Connection in Android

How to check Internet is Connected or not In Android


In Android Internet Connection can be checked by using  ConnectivityManager class.

Note : to use this you need to declare ACCESS_NETWORK_STATE 


Android Manifest

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



CODE :

boolean isInternetConnected()
{

   ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE );

   NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
   boolean isConncted = activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();

   return isConncted;
}

Sunday, July 12, 2020

Switch Example in Android

Working with Switch in Android


A Switch is a two-state toggle button. A user can select between two options.

Add switch in layout :

<Switch    
android:layout_marginTop="5dp"    
android:id="@+id/switchs"    
android:layout_width="wrap_content"    
android:layout_height="wrap_content"    
android:text="Show System Apps  "    
android:textSize="15dp"    
android:layout_gravity="right"    
android:layout_marginRight="5dp"    
android:textColor="#4d4d4d"/>






in Activity handle the click event


Switch switch = (Switch)findViewById(R.id.switch);

switchShowSystemApps.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

      
        if(isChecked == true)
        {
            // your code
        }
        else        {
           // your code
        }
    }
});

List of Android normal permissions and dangerous permissions in API 23

List of Android permissions normal permissions and dangerous permissions in API 23

From Android API 23, permission has been classified in two categories.

Normal Permissions : To get these permission, just we need to declare them in Manifest File and Android will allow to use these permission.

Dangerous Permission : For these permission, you need to declare then in manifest and also need to explicitly request in Activity, when user clicks on "Allow" then only these permission can be used.

Here we are providing a list of Normal and Dangerous permissions.



Normal Permission

ACCESS_LOCATION_EXTRA_COMMANDS
ACCESS_NETWORK_STATE
ACCESS_NOTIFICATION_POLICY
ACCESS_WIFI_STATE
BLUETOOTH
BLUETOOTH_ADMIN
BROADCAST_STICKY
CHANGE_NETWORK_STATE
CHANGE_WIFI_MULTICAST_STATE
CHANGE_WIFI_STATE
DISABLE_KEYGUARD
EXPAND_STATUS_BAR
GET_PACKAGE_SIZE
INSTALL_SHORTCUT
INTERNET
KILL_BACKGROUND_PROCESSES
MODIFY_AUDIO_SETTINGS
NFC
READ_SYNC_SETTINGS
READ_SYNC_STATS
RECEIVE_BOOT_COMPLETED
REORDER_TASKS
REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
REQUEST_INSTALL_PACKAGES
SET_ALARM
SET_TIME_ZONE
SET_WALLPAPER
SET_WALLPAPER_HINTS
TRANSMIT_IR
UNINSTALL_SHORTCUT
USE_FINGERPRINT
VIBRATE
WAKE_LOCK
WRITE_SYNC_SETTINGS
Dangerous Permissions

READ_CALENDAR
WRITE_CALENDAR
CAMERA
READ_CONTACTS
WRITE_CONTACTS
GET_ACCOUNTS
ACCESS_FINE_LOCATION
ACCESS_COARSE_LOCATION
RECORD_AUDIO
READ_PHONE_STATE
READ_PHONE_NUMBERS 
CALL_PHONE
ANSWER_PHONE_CALLS 
READ_CALL_LOG
WRITE_CALL_LOG
ADD_VOICEMAIL
USE_SIP
PROCESS_OUTGOING_CALLS
BODY_SENSORS
SEND_SMS
RECEIVE_SMS
READ_SMS
RECEIVE_WAP_PUSH
RECEIVE_MMS
READ_EXTERNAL_STORAGE
WRITE_EXTERNAL_STORAGE

How to request permissions in Android API 23 and above.

From Android API 23, we need to request for permission in Activity class and user has "Allow" for permission in order to use the permission.

You need to declare the permission in manifest file and need to request in Activity as well.

In this blog we will request for 2 permissions   "READ_PHONE_STATE" and "ACCESS_FINE_LOCATION"

Declare the permissions in manifest inside application TAG
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>


String permissionsRequired[];

@Overrideprotected void onCreate(Bundle savedInstanceState)
{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);

        permissionsRequired = new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, 
        Manifest.permission.READ_PHONE_STATE};

     if (android.os.Build.VERSION.SDK_INT >= 23) {
     if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != 
        PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != 
          PackageManager.PERMISSION_GRANTED) {
        showPermissionDialog();
    }

}
void showPermissionDialog()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Need Permission");
    builder.setMessage("This app needs following permission.\n" +
            "1: Location Permission \n" +
            "2: Phone Permission\n\n"+
            "Please click on allow to give permissions.");
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            requestForPermissions(permissionsRequired);


        }
    });

    builder.show();
}

// request for permissions
void requestForPermissions(String permissions[])
{
    ActivityCompat.requestPermissions(GPSCoordinatesMainActivity.this, permissions, 1);
}

// handle whether user allowed and denied the permission
@Overridepublic void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    permissionDeniedCount++;
   
    if (requestCode == 1) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            //The External Storage Write Permission is granted to you... Continue your left job...            getGPSLocation();
        }  else {
            //Show Information about why you need the permission            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("You denied the required Permission");
            builder.setMessage(""Please click on allow to give permissions.");
            builder.setPositiveButton("Give Permissions", new DialogInterface.OnClickListener() {
                @Override                public void onClick(DialogInterface dialog, int which) {
                    requestForPermissions(permissionsRequired);
                    dialog.cancel();

                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                    finish();
                }
            });
            builder.show();

        }
    }

}




How to set a custom layout in Alert Dialog In Android

How to set a custom layout in Alert Dialog In Android.


In Android we can set a custom layout in Alert Dialog making it look better.
For this we need to create layout file and inflate this layout file in Alert Dialog.


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#004d66">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal"
        android:gravity="center_vertical"
        android:background="#00394d"
        android:padding="5dp">


        <TextView
            android:id="@+id/textViewDialogSingleButtonTitle"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:textStyle="bold"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:text="Dilaog Details"
            android:textColor="#ffffff"
            android:gravity="center_vertical"
            android:textSize="18dp" />


    </LinearLayout>


    <TextView
        android:id="@+id/textViewDialogSingleButtonMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="Dilaog Title"
        android:textColor="#ffffff"
        android:textSize="16dp" />

        <Button
            android:id="@+id/buttonOKDialogSingleButton"
            android:background="@drawable/button_gradient"
            android:layout_marginTop="15dp"
            android:textColor="#FFFFFF"
            android:textSize="18dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="         OK         "
            android:layout_marginBottom="10dp"
            />
    </LinearLayout>



Inflate the layout in Alert Dialog



AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
ViewGroup viewGroup = findViewById(android.R.id.content);
View dialog = LayoutInflater.from(this).inflate(R.layout.custom_dialog_single_button, viewGroup, false);
builder.setView(dialog);
final AlertDialog alertDialog = builder.create();

TextView textViewTtile=(TextView) dialog.findViewById(R.id.textViewDialogSingleButtonTitle);
TextView textViewMessage=(TextView) dialog.findViewById(R.id.textViewDialogSingleButtonMessage);
Button btnOK=(Button)dialog.findViewById(R.id.buttonOKDialogSingleButton);

textViewTtile.setText("  Title");
textViewMessage.setText("Dialog Message");

alertDialog.show();

btnOK.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View view) {
        if(alertDialog.isShowing())
            alertDialog.dismiss();
    }
});



Screenshot


How to get the Date with Month Name and Year In Java or Android

How to get the Date with Month Name and Year In Java or Android


In Java And Android we can get proper Date with Month name.
The following method return Date like "2 Jan 2020".
You just need to pass miliSeconds as parameter.


public static String getDateWithMonthName(long miliseconds)
{
         GregorianCalendar gc=new GregorianCalendar();
         gc.setTimeInMillis(miliseconds);

         int day=gc.get(Calendar.DAY_OF_MONTH);
         int month=gc.get(Calendar.MONTH)+1;
         int year=gc.get(Calendar.YEAR);
         String date=day+" "+getMonth(month)+" "+year;
         return date;
}


public static String getMonth(int month)
{
 switch(month)
 {
      case 1:
         return "Jan";
      case 2:
         return "Feb";
      case 3:
         return "Mar";

      case 4:
         return "April";

      case 5:
         return "May";

      case 6:
         return "June";

      case 7:
         return "July";

      case 8:
         return "Aug";

      case 9:
         return "Sep";

      case 10:
         return "Oct";

      case 11:
         return "Nov";

      case 12:
         return "Dec";

   }
 return "";
}

How to open an APP in Google Play Store

How the open an APP in Google Play Store Programatically


In Android Programming we can open Play Store with a Given App Package Name.
The following method opens Apps' playstore page

void openAppInPlaystore(String appPackageName )
{
    
     
        try {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
        } catch (android.content.ActivityNotFoundException anfe) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
        }
    
}

How to get All Apps List Installed in Phone

How to get All Apps Icon, Package Name, App Name and Size.


In our Android phone there are 2 types of Apps

1 : System Apps : These are preinstalled Apps and can not be unInstalled without root access.
2 : User apps : These are 3rd party apps that we download from App Stores like Google Play Store.

In the Blog we will discuss how to get all Installed App and their Icon, Package Name, App Name and Size


Method to Fetch All Installed Apps

private void getInstalledApps() {
    PackageManager pm = getPackageManager();

         packs = getPackageManager().getInstalledPackages(0);
  
    for (int i = 0; i < packs.size(); i++) {
        PackageInfo p = packs.get(i);
        
            String appName = p.applicationInfo.loadLabel(getPackageManager()).toString();
            Drawable icon = p.applicationInfo.loadIcon(getPackageManager());
            String packageNAme = p.applicationInfo.packageName;
            File file = new File(p.applicationInfo.publicSourceDir);
            long sizeinBytes = file.length();
            

        
        }
        
    }


How to check whether an App is a System app or User App




boolean isSystemApp(PackageInfo pkgInfo)
{
    if((pkgInfo.applicationInfo.flags & (ApplicationInfo.FLAG_UPDATED_SYSTEM_APP | ApplicationInfo.FLAG_SYSTEM)) > 0)
     {
    
        return true;   // it is System app
    }
    else    {
          return false; // it is user App
     }
}

How to Launch An App

void launchApp(String appPackagneName)
{
    Intent intent1 = getPackageManager().getLaunchIntentForPackage(appPackagneName);
    if(intent1 != null){
        startActivity(intent1);
    }
    else {
        Toast.makeText(this, " Can't launch this.\nThe app may have been UnInstalled or Disabled.", Toast.LENGTH_SHORT).show();
    }
}

How to open App Info in Phone Setting


void showAppInfo(String appPackagneName)
{
    try {
        Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" +appPackagneName));
        //  Toast.makeText(MainActivity.this, installedApps.get(i).packages, Toast.LENGTH_SHORT).show();      startActivity(intent);
    }
    catch(Exception E){
        Toast.makeText(this, " Can't open App's Info.", Toast.LENGTH_SHORT).show();
    }
}

How to get and Share App's Play Store Link


void shareAppLink(String appPackagneName)
{
  
        String appLink = appItem.name + " Download Link : https://play.google.com/store/apps/details?id=" + appPackageName;
        Intent localIntent = new Intent();

        localIntent.setAction("android.intent.action.SEND");
        localIntent.putExtra("android.intent.extra.TEXT", appLink);
        localIntent.setType("text/plain");
        startActivity(Intent.createChooser(localIntent, "Share App Link"));
    

}

How the open an APP in Google Play Stor


void openAppInPlaystore(String appPackageName )
{
    
     
        try {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
        } catch (android.content.ActivityNotFoundException anfe) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
        }
    
}




I hope you enjoyed it.

Saturday, July 11, 2020

Add YouTube Video Player in Android App

How to Add Youtube Video in Android App


In our Android App we can easily add a youtube video link in our Android App.

For this we need to following things;

Step 1 : Create an API key

  1. You must  create an API key on https://console.developers.google.com/
  2. Go to the link
  3. Click on Credentials in Left Pane
  4. Click on "Create Credentials"


You need to enter your app package name and SHA Key, Click Save
Your API key will be created

See the Screenshot below.





Step 2 :  Add YouTubePlayerView in layout


<?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="match_parent"
        android:orientation="vertical
"        android:background="#006080">

  
        <com.google.android.youtube.player.YouTubePlayerView 
           android:layout_marginTop="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible"
            android:layout_gravity="center_horizontal"
            android:id="@+id/youtube_player"      />


    </LinearLayout>


Loading Video in Activity


public class PlayYouTubeVideoActivity extends YouTubeBaseActivity
{

    YouTubePlayerView youTubePlayerView;
 
    YouTubePlayer.OnInitializedListener onInitializedListener;


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

        youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
      
        onInitializedListener = new YouTubePlayer.OnInitializedListener(){
            @Override            
             public void onInitializationSuccess(YouTubePlayer.Provider provider,
                                               
             YouTubePlayer youTubePlayer, boolean b) {

                youTubePlayer.loadVideo("XXXXXXX");//Enter your Youtube Video ID here
                youTubePlayer.play();
            }

            @Override           
           public void onInitializationFailure(YouTubePlayer.Provider provider, 
             YouTubeInitializationResult youTubeInitializationResult) {
                Log.i("KAMLESH","Youtube not initialized 
             "+youTubeInitializationResult.getErrorDialog(PlayYouTubeVideoActivity.this,5));
            }
        };

        youTubePlayerView.initialize("ENTER YOUR API KEY HERE",onInitializedListener);


    }

}



Screenshot