How to Create Floating Widget in AndroidAndroid Development
October 04, 20203 minutesuserVivek Beladiya
How to Create Floating Widget in Android
Today I’m going to write on Create Floating Widget never stop closing the app from the background. First of all, you must know what is the service in Android.

What is a service in Android?

A service is a component that runs in the background without direct interaction with the user. Since the service has no user interface, it is not bound to the life cycle of the activity. If you want to repeat a task, using the service is the best way.
Service stops are one of the biggest problems when you clear the application from background functions.


My service is below:

public class FloatingViewService extends Service  {

    private WindowManager mWindowManager;
    private View mFloatingView;
    private View floatingButton;
    private final static float CLICK_DRAG_TOLERANCE = 10;

    private float downRawX, downRawY;
    private float dX, dY;
    int LAYOUT_FLAG;
    private SpeechRecognizer speechRecognizer;

    public FloatingViewService() {
    }
		Context context;

    public FloatingViewService(Context applicationContext) {
        super();
        context = applicationContext;
        Log.i("HERE", "here service created!");
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
					 KeyguardManager myKM = (KeyguardManager) this.getSystemService(Context.KEYGUARD_SERVICE);
              if( myKM.inKeyguardRestrictedInputMode()) {
                  Intent i = new Intent(this,FloatingViewService.class);
                  startService(i);
//            //it is locked
                } else {
                    Intent i = new Intent(this, FloatingViewService.class);
                    startService(i);
        //it is not locked
             }
            return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mFloatingView = LayoutInflater.from(this).inflate(R.layout.floating_layout, null);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
        }

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

        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        mWindowManager.addView(mFloatingView, params);

        floatingButton.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();

                        downRawX = event.getRawX();
                        downRawY = event.getRawY();
                        dX = v.getX() - downRawX;
                        dY = v.getY() - downRawY;

                        return true;

                    case MotionEvent.ACTION_UP:

                        float upRawX = event.getRawX();
                        float upRawY = event.getRawY();

                        float upDX = upRawX - downRawX;
                        float upDY = upRawY - downRawY;
                        return true;

                    case MotionEvent.ACTION_MOVE:
                        params.x = initialX + (int) (event.getRawX() - initialTouchX);
                        params.y = initialY + (int) (event.getRawY() - initialTouchY);
                        mWindowManager.updateViewLayout(mFloatingView, params);
                        return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
AndroidManifest.xml  file and update your service declarations under the application tag. Also, add  FOREGROUND_SERVICE, INTERNET and  WAKE_LOCK .Make sure you don't forget to include them as they won't work otherwise.

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

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">

        <service
                android:name=".FloatingViewService"
                android:enabled="true"
                android:exported="false">
        </service>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

You can use the following code to check if the service is running. If the service is already in running mode, it does not need to be restarted otherwise start in your MainActivity.

FloatingViewService mFloatingService = new FloatingViewService(getApplicationContext());
  Intent mServiceIntent = new Intent(getApplicationContext(), mFloatingService.getClass());
if (!isMyServiceRunning(mFloatingService.getClass())) {
    startService(mServiceIntent);
}

Method isMyServiceRunning() is below add this in your MainActivity.

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            Log.i ("isMyServiceRunning?", true+"");
            return true;
        }
    }
    Log.i ("isMyServiceRunning?", false+"");
    return false;
}
Then Create a Floating Widget design. Create File floating_layout.xml Like This

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <RelativeLayout
        android:id="@+id/rl_close_button"
        android:layout_width="100dp"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:id="@+id/relativeLayoutParent"
            android:layout_width="80dp"
            android:layout_height="70dp">

            <RelativeLayout
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:background="@drawable/floating_round_main_shape">

                <RelativeLayout
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_centerInParent="true"
                    android:background="@drawable/floating_inner_round_shape">

                    <ImageView
                        android:layout_width="25dp"
                        android:layout_height="25dp"
                        android:layout_centerInParent="true"
                        android:src="@drawable/ic_voice_icon" />

                </RelativeLayout>

            </RelativeLayout>

        </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>

I hope it will help these services. 
Note:-This service will run better in Oreo and above versions.