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

后端 未结 3 1678
情话喂你
情话喂你 2020-11-22 04:30

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

3条回答
  •  春和景丽
    2020-11-22 05:02

    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.

提交回复
热议问题