廖峰聖
廖峰聖

Reputation: 3

how to let a floating touch on all app

I'm trying to create a clickable-image which stays on top of all the app and decktop, like facebook messenger.

and it's my code

public class FloatService extends Service
{
    private WindowManager windowManager;
    private ImageView imageBtn;

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

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

        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        imageBtn = new ImageView(this);
        imageBtn.setImageResource(R.drawable.ic_launcher);

        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(imageBtn, params);
    }

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

and

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

there are two buttons in my activity, one of "start service", and the other is "stop service" i click "start service", it create a clickable-image, so it's all fine. but when i change to other app or leave this app, the clickable-image will disappear, until i open my app.

thanks for help

Upvotes: 0

Views: 194

Answers (3)

廖峰聖
廖峰聖

Reputation: 3

I find the solution

because my phone is MIUI, it default hide any floating window

so i need to turn on it by myself

and thank for all answer

Upvotes: 0

Feng Dai
Feng Dai

Reputation: 633

Change the window type from WindowManager.LayoutParams.TYPE_PHONE to WindowManager.LayoutParams.TYPE_SYSTEM_ALERT:

WindowManager.LayoutParams params = new WindowManager.LayoutParams(
    WindowManager.LayoutParams.
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, // modified
    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
    PixelFormat.TRANSLUCENT);

Upvotes: 1

Amit Kumar
Amit Kumar

Reputation: 547

it happen because your service has been destroyed when you exit from your app due to low memory issue

so 1. You can pass START_STICKY from Service.onStartCommand() Service.START_STICKY

2.You can start service as a foreground service Service.startForeground (int id, Notification notification)

android os dont kill the foreground service genreally.

this may help you

Upvotes: 0

Related Questions