Friday, June 16, 2017

android - Get app first install time

activity_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"
    tools:context="com.cfsuman.me.androidcodesnippets.MainActivity"
    >
    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.129"
        android:textSize="20sp"
        android:textStyle="bold"
        />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get First Install Time"
        android:layout_marginTop="54dp"
        app:layout_constraintTop_toBottomOf="@+id/text_view"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        />
</android.support.constraint.ConstraintLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Date;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private Button mButton;
    private TextView mTextView;

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

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widget reference from xml layout
        mButton = (Button) findViewById(R.id.button);
        mTextView = (TextView) findViewById(R.id.text_view);

        // Set up the button click listener
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    /*
                        firstInstallTime
                            long firstInstallTime

                            The time at which the app was first installed.
                            Units are as per currentTimeMillis().
                    */
                    long installedTime = mContext.getPackageManager()
                            .getPackageInfo(mContext.getPackageName(),0)
                            .firstInstallTime;

                    // Format the date time
                    String dateString = DateFormat
                                        .format("MM/dd/yyyy hh:mm:ss", new Date(installedTime))
                                        .toString();

                    // Get the time difference between now and app first install time
                    String timeDifference = getTimeDifference(new Date(installedTime));

                    // Display the app install date time on text view
                    mTextView.setText("First Install Time\n"+dateString);

                    // Display app first install time ago
                    mTextView.append("\n\n Time ago\n");
                    mTextView.append(timeDifference);
                }catch(PackageManager.NameNotFoundException e){
                    e.printStackTrace();
                }
            }
        });
    }

    // Custom method to get seconds difference between to date objects
    protected static int getSecondsDifference(Date then){
        Date now = new Date(System.currentTimeMillis());
        long dateDiff = now.getTime() - then.getTime();
        return (int) dateDiff/1000; // 1000 milliseconds = 1 second
    }

    // Custom method to get seconds to readable time
    protected static String getReadableTime(int seconds){
        String readableTime = "";

        int hours = (int) seconds / 3600;
        int remainder = (int) seconds - hours * 3600;
        int mins = remainder / 60;
        remainder = remainder - mins * 60;
        int secs = remainder;

        if(hours>0){
            readableTime = hours + " hour ";
        }
        if(mins>0){
            readableTime += mins + " min ";
        }
        if (secs>0){
            readableTime += secs + " sec";
        }
        return readableTime;
    }

    // Custom method to get readable time difference between two date objects
    protected static String getTimeDifference(Date then){
        return getReadableTime(getSecondsDifference(then));
    }
}