when my application run in background. It need to monitoring others application swaping in the foreground and get their name. How to implement? i.e. When an app goto the for
Accessibility services provide a means to get the current foreground service.
Extend the Accessibility Service and create a new class. Listen for AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED event. This event is triggered whenever the foreground activity is changed. The event object passed with the callback contains the package name of the foreground app.
AccessibilityService.java
public class AccessibilityService extends android.accessibilityservice.AccessibilityService{
public static AccessibilityService instance;
@Override
public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
// Note : This event is sometimes called more than one for a foreground service
if (accessibilityEvent.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED){
Log.d("Event","TYPE_WINDOW_STATE_CHANGED");
Log.d("Pkg",accessibilityEvent.getPackageName().toString());
}
}
@Override
public void onInterrupt() {
}
@Override
protected void onServiceConnected() {
super.onServiceConnected();
Log.d("Accessibility","Service Connected");
}
}
To successfully implement the service the manifest file must also contain the following declaration in the application section along with a config file in the res/xml folder
serviceconfig.xml
Ensure accessibility services permission are granted by the user. It requires manual enabling from the side of the user.
The complete code for sample app to get the foreground process name is available at https://github.com/abinpaul1/Android-Snippets/tree/master/GetForegroundService