Tuesday 4 August 2015

Chat Head like Facebook messenger android

You have seen in many application have the feature of rounded chat icon on the screen which will be always on screen above all applications as shown in the screen shots . The app that provide this feature is Facebook messenger app where there is a chat icon on the screen .

                                 


Step1) Add Permission in manifest file 

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

Step2) Make a class that extends the service 

public class ServiceChatHead extends Service {

  private WindowManager windowManager;
  private ImageView chatImage;

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

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

    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

    chatImage = new ImageView(this);
    chatImage.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;
  chatImage.setOnTouchListener(new View.OnTouchListener() {
  private int initialX;
  private int initialY;
  private float initialTouchX;
  private float initialTouchY;

  @Override public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        initialX = params.x;
        initialY = params.y;
        initialTouchX = event.getRawX();
        initialTouchY = event.getRawY();
        return true;
      case MotionEvent.ACTION_UP:
        return true;
      case MotionEvent.ACTION_MOVE:
        params.x = initialX + (int) (event.getRawX() - initialTouchX);
        params.y = initialY + (int) (event.getRawY() - initialTouchY);
        windowManager.updateViewLayout(chatHead, params);
        return true;
    }
    return false;
  }
});
    windowManager.addView(chatImage, params);
  }

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


Step 3) Declare service in manifest file 

<service   android:name=".ServiceChatHead"></service>

Step4) Start the service that will display the icon and icon can be dragable to any position on screen

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



Enjoy Coding and share your knowledge 

2 comments:

  1. hey dude..i have created chathead..but how can i open my application through my chat head

    ReplyDelete
  2. where implement chat head implement function? please help me

    ReplyDelete