Saturday, December 22, 2012

Home Screen Counter in Android, how to find home screen is active in Android

Source Code


package ranjit.checkhomescreen;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.app.ActivityManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class CheckHomeScreenCounter extends Activity {
public static int counter;
public static boolean home_screen_active = false;
ActivityManager activity_manager;
TextView tv;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_home_screen_counter);
activity_manager = (ActivityManager) getSystemService(getApplicationContext().ACTIVITY_SERVICE);
tv = (TextView) findViewById(R.id.textView1);

if (counter <= 0) {
new CountDownTimer(30000, 1000) {

@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
try {
checkLatestActi();
} catch (Exception e) {
e.printStackTrace();
Log.d("Ranjit check error", " " + e);
}
}

@Override
public void onFinish() {
// TODO Auto-generated method stub
start();
}
}.start();
}
tv.setText("Home Screen Counter:" + counter);

}

public void checkLatestActi() {
try {
if (activity_manager.getRunningTasks(Integer.MAX_VALUE).get(0).topActivity
.getPackageName().equals("com.android.launcher")) {
if (home_screen_active == true) {
home_screen_active = false;
Log.e("Got Home Screen", "In HomeScreen " + counter++);
}
} else {
home_screen_active = true;
Log.e("App Status", "Other App running...");
}
} catch (Exception e) {
Log.e("Error", "Error : " + e.getMessage());
}
}
}


Layout 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/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp"
        android:text="Home Screen Counter : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Add permition in an Android.Menifest file

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


I hope is this helpful for you.

Please reply, comment, like if is this helpful for you......

No comments:

Post a Comment