Android Useful Methods and Functions

A fully featured Android application has a lot of functionality going on to provide a user-friendly interface to the user. For example, we can Indicate if the device is still connected to a network of if connected is it Wifi or mobile network, check GPS status on the device, battery status like a battery percentage or if connected to power source etc. In this post, I am going to list some similar handy and useful methods which are needed most of the time in an Android application.

To give an idea I have listed methods which we will discuss further:

1) Check if Device is Connected to Network.
2) Check GPS Status of the device.
3) Show/ Remove Notification.
4) Convert Google Geocode Address Object into Comma Separated String.
5) Check Battery Status is it connected to Power.
6) Convert Date into a required format.

To keep these methods available to every activity in the application, its preferable to keep them in a Utils Class.

1) How to Check if Device is Connected to Network?

To check connectivity we will use ConnectivityManager service, this will return Network Info, type of network and other information. You can check more details here.

...
...
import android.net.ConnectivityManager;
....
....
public class Utils {

   static ConnectivityManager connectivityManager;
   ....
   ....

    public static String isOnline(Context context) {
        JSONArray array = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("connected","false");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            Log.i("networkInfo", networkInfo.toString());
            jsonObject.put("connected",(networkInfo != null && networkInfo.isAvailable() &&
                    networkInfo.isConnected()));
            jsonObject.put("isAvailable",(networkInfo.isAvailable()));
            jsonObject.put("isConnected",(networkInfo.isConnected()));
            jsonObject.put("typeName",(networkInfo.getTypeName()));
            array.put(jsonObject);
            return array.toString();


        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        array.put(jsonObject);
        return array.toString();
    }

}

Also add permission in AndroidManifest file

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

 

This method will return an object in string format.

2) How to check if device GPS is turned On/ Off?

This method will use the LocationManager service.

    //Check GPS Status true/false
    public static boolean checkGPSStatus(Context context){
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
        boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return statusOfGPS;
    };

3) How to create and remove Custome Notifications in Android Application?

Following method will show Notification, having big text and freeze enabled( Notification will not get removed even after user swipes ). We need NotificationManager service, you can read more about the Notification service here

    public static void showNotificationOngoing(Context context,String title) {
            NotificationManager notificationManager =
                    (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

            PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                    new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

            Notification.Builder notificationBuilder = new Notification.Builder(context)
                    .setContentTitle(title + DateFormat.getDateTimeInstance().format(new Date()) + ":" + accuracy)
                    .setContentText(addressFragments.toString())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(contentIntent)
                    .setOngoing(true)
                    .setStyle(new Notification.BigTextStyle().bigText(addressFragments.toString()))
                    .setAutoCancel(true);
            notificationManager.notify(3, notificationBuilder.build());
    }

Method to Remove Notifications

    public static void removeNotification(Context context){
        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
    }

4) How to Convert Google Geocode Address Object into Comma Separated String.

After getting Address Object from Geocoder service we will pass it to the following method, which will return comma separated string of address. You can check Background Geolocation and Geocoder Application Example tutorial for information on these location services.

public class Utils {
     ...
     ...
     static String addressFragments = "";
     static List<Address> addresses = null;

     ....
     ....

    public static String getAddress(Location location,Context context){
        Geocoder geocoder = new Geocoder(context, Locale.getDefault());

        // Address found using the Geocoder.
        addresses = null;
        Address address = null;
        addressFragments="";
        try {
            addresses = geocoder.getFromLocation(
                    location.getLatitude(),
                    location.getLongitude(),
                    1);
            address = addresses.get(0);
        } catch (IOException ioException) {
            Log.e(TAG, "error", ioException);
        } catch (IllegalArgumentException illegalArgumentException) {
            Log.e(TAG, "Latitude = " + location.getLatitude() +
                    ", Longitude = " + location.getLongitude(), illegalArgumentException);
        }

        if (addresses == null || addresses.size()  == 0) {
            Log.i(TAG, "EROORRRRRR");
            addressFragments = "NO ADDRESS FOUND";
        } else {
            for(int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
                addressFragments = addressFragments+String.valueOf(address.getAddressLine(i));
            }
        }
        return addressFragments;
    }
}

5) How to Check Battery Status is it connected to Power.

To check battery percentage we use BatteryManager, the following method will return battery percentage.

    public static float getBatteryLevel(Context context, Intent intent) {
        Intent batteryStatus = context.registerReceiver(null,
                new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int batteryLevel = -1;
        int batteryScale = 1;
        if (batteryStatus != null) {
            batteryLevel = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, batteryLevel);
            batteryScale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, batteryScale);
        }
        return batteryLevel / (float) batteryScale * 100;
    }

6) How to Get Formatted Date in Android Application?

Calendar.getInstance().getTime() gives

Thu Jul 26 15:54:13 GMT+05:30 2018

Use

String oldDate = "Thu Jul 26 15:54:13 GMT+05:30 2018";
DateFormat format = new SimpleDateFormat("EEE LLL dd HH:mm:ss Z yyyy");
Date updateLast = format.parse(oldDate);

 

So we discussed some commonly used methods in Android application. These are parts of some my application. You may have a different approach for some functionalities, you can change and give feedback if for any suggestions or correction is most welcome 🙂

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments