Thursday, December 20, 2012

How to count phone lock/unlock states in Android

Hello friends

This is simple code to count phone lock/unlock states in android

Source code


package ranjit.countlock_unlock;

import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.TextView;

public class Count_Lock_Unlock extends Activity {
KeyguardManager myKM;
int lock_counter = 0, unlock_counter = 0;
boolean screen_state = true;
TextView tvLock, tvUnlock;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_count__lock__unlock);

tvLock = (TextView) findViewById(R.id.txtLock);
tvUnlock = (TextView) findViewById(R.id.txtUnlock);
myKM = (KeyguardManager) getApplicationContext().getSystemService(
Context.KEYGUARD_SERVICE);

new CountDownTimer(60000, 1000) {

@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
if (myKM.inKeyguardRestrictedInputMode()) {
// it is locked
Log.e("LOCKED STATUS", "its LOCKED");
if (screen_state == true) {
lock_counter++;
tvLock.setText("LOCK : " + lock_counter);
Log.e("LOCK", "LOCK");
}
screen_state = false;
} else {
// it is not locked
Log.e("UN-LOCKED STATUS", "its UN-LOCKED");
if (screen_state == false) {
unlock_counter++;
tvUnlock.setText("UNLOCK : " + unlock_counter);
Log.e("UNLOCK", "UNLOCK");
}
screen_state = true;
}
}

@Override
public void onFinish() {
// TODO Auto-generated method stub
start();
}
}.start();
}
}


XML File


<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" >

    <TextView
        android:id="@+id/txtLock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="56dp"
        android:text="LOCK : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/txtUnlock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtLock"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="96dp"
        android:text="UNLOCK : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

No comments:

Post a Comment