What APIs are used to draw over other apps (like Facebook's Chat Heads)?

Daniel A. White picture Daniel A. White · Apr 12, 2013 · Viewed 75.2k times · Source

How does Facebook create the Chat Heads on Android? What is the API to create the floating views on top of all other views?

Answer

Waza_Be picture Waza_Be · Apr 12, 2013

This one:

Allows an application to open windows using the type TYPE_SYSTEM_ALERT, shown on top of all other applications. Very few applications should use this permission; these windows are intended for system-level interaction with the user.

Constant Value: "android.permission.SYSTEM_ALERT_WINDOW"

//EDIT: The full code here:

public class ChatHeadService extends Service {

  private WindowManager windowManager;
  private ImageView chatHead;

  @Override public IBinder onBind(Intent intent) {
    // Not used
    return null;
  }

  @Override public void onCreate() {
    super.onCreate();

    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

    chatHead = new ImageView(this);
    chatHead.setImageResource(R.drawable.android_head);

    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.TYPE_PHONE,
        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
        PixelFormat.TRANSLUCENT);

    params.gravity = Gravity.TOP | Gravity.LEFT;
    params.x = 0;
    params.y = 100;

    windowManager.addView(chatHead, params);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    if (chatHead != null) windowManager.removeView(chatHead);
  }
}

Don't forget to start the service somehow:

startService(new Intent(context, ChatHeadService.class));

.. And add this service to your Manifest.