Wednesday 10 September 2014

Check Current Running Activity

             Check Current Running Activity | Task | Application - Android Example

Check Current Running Activity | Task | Application - Android Example

Androidmanifest xml

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


step: 1

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.checkcurrentrunningapplication"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.checkcurrentrunningapplication.Main"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
         
        <receiver android:name=".StartupReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="StartupReceiver_Manual_Start" />
            </intent-filter>
        </receiver>
         
        <receiver android:name = ".CheckRunningApplicationReceiver"/>
         
    </application>
    <uses-permission android:name="android.permission.GET_TASKS" />
</manifest>

Step:2
File : src/Main.java
Inside This class Start Broadcast reciever to check current running activity/task/application.


package com.example.checkcurrentrunningapplication;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;

public class Main extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
          
        // Start broadcast receiver may be StartupReceiver not started on BOOT_COMPLETED
        // Check AndroidManifest.xml file
        initialize();
    }

    private void initialize() {
         
        // Start receiver with the name StartupReceiver_Manual_Start
        // Check AndroidManifest.xml file
        getBaseContext().getApplicationContext().sendBroadcast(
                new Intent("StartupReceiver_Manual_Start"));
    }
}





Step:3
File : src/StartupReceiver.java

This receiver will on phone boot time (see AndroidMainifest.xml). Creating alarm that will call broadcast receiver CheckRunningApplicationReceiver.class after each 5 seconds.


package com.example.checkcurrentrunningapplication;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;

public class StartupReceiver extends BroadcastReceiver {

    static final String TAG = "SR";
     
    final int startupID = 1111111;

     
    @Override
    public void onReceive(Context context, Intent intent) {
         
        // Create AlarmManager from System Services
        final AlarmManager alarmManager = (AlarmManager) context
                    .getSystemService(Context.ALARM_SERVICE);
        try{
                // Create pending intent for CheckRunningApplicationReceiver.class 
                // it will call after each 5 seconds
                 
                Intent i7 = new Intent(context, CheckRunningApplicationReceiver.class);
                PendingIntent ServiceManagementIntent = PendingIntent.getBroadcast(context,
                        startupID, i7, 0);
                alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
                        SystemClock.elapsedRealtime(), 
                        5000, ServiceManagementIntent);
                 
                 
            } catch (Exception e) {
                Log.i(TAG, "Exception : "+e);
            }
             
        }
     
}


Step:4
File : src/CheckRunningApplicationReceiver.java

This broadcast receiver will call after each 5 seconds and check CALL/SMS/THIS example screen is open or not. if CALL/SMS/THIS example screen open then show alert message on screen.


package com.example.checkcurrentrunningapplication;

import java.util.List;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class CheckRunningApplicationReceiver extends BroadcastReceiver {

    public final String TAG = "CRAR"; // CheckRunningApplicationReceiver

    @Override
    public void onReceive(Context aContext, Intent anIntent) {
         
        try {
             
            // Using ACTIVITY_SERVICE with getSystemService(String) 
            // to retrieve a ActivityManager for interacting with the global system state.
             
            ActivityManager am = (ActivityManager) aContext
                    .getSystemService(Context.ACTIVITY_SERVICE);
             
            // Return a list of the tasks that are currently running, 
            // with the most recent being first and older ones after in order.
            // Taken 1 inside getRunningTasks method means want to take only 
            // top activity from stack and forgot the olders.
             
            List<ActivityManager.RunningTaskInfo> alltasks = am
                    .getRunningTasks(1);

            // 
            for (ActivityManager.RunningTaskInfo aTask : alltasks) {

                 
                // Used to check for CALL screen  
                 
                if (aTask.topActivity.getClassName().equals("com.android.phone.InCallScreen")
                    || aTask.topActivity.getClassName().equals("com.android.contacts.DialtactsActivity"))
                {
                    // When user on call screen show a alert message
                    Toast.makeText(aContext, "Phone Call Screen.", Toast.LENGTH_LONG).show();   
                }
                 
                // Used to check for SMS screen
                 
                if (aTask.topActivity.getClassName().equals("com.android.mms.ui.ConversationList")
                        || aTask.topActivity.getClassName().equals("com.android.mms.ui.ComposeMessageActivity"))
                {
                    // When user on Send SMS screen show a alert message
                    Toast.makeText(aContext, "Send SMS Screen.", Toast.LENGTH_LONG).show(); 
                }
                 
                 
                // Used to check for CURRENT example main screen
                 
                String packageName = "com.example.checkcurrentrunningapplication";
                 
                if (aTask.topActivity.getClassName().equals(
                        packageName + ".Main"))
                {
                   // When opens this example screen then show a alert message
                   Toast.makeText(aContext, "Check Current Running Application Example Screen.", 
                                   Toast.LENGTH_LONG).show();   
                }
                 
                 
                // These are showing current running activity in logcat with 
                // the use of different methods
                 
                Log.i(TAG, "===============================");
                 
                    Log.i(TAG, "aTask.baseActivity: "
                                + aTask.baseActivity.flattenToShortString());
                     
                    Log.i(TAG, "aTask.baseActivity: "
                                + aTask.baseActivity.getClassName());
                     
                    Log.i(TAG, "aTask.topActivity: "
                                + aTask.topActivity.flattenToShortString());
                     
                    Log.i(TAG, "aTask.topActivity: "
                                + aTask.topActivity.getClassName());
                 
                Log.i(TAG, "===============================");
                 
                 
            }

        } catch (Throwable t) {
            Log.i(TAG, "Throwable caught: "
                        + t.getMessage(), t);
        }
         
    }

}

Step 5

File : main.xml


<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"
    tools:context=".Main" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Starting broadcast reciever to check current running tasks." />

</RelativeLayout>



No comments:

Post a Comment