I'm working on a project and i aim to create a button that display on top of other applications and when we click on it, would change the activity on the screen, for this i made researchs and found that i had to use a "Service".
I managed to create an imageView that is on top of other applications but i cant interact with it and use an OnClickListener.
If you got any idea let me know please !
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Settings.canDrawOverlays(this)){
} else {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Activity context = this;
context.startActivity(intent);
}
Button start_button = findViewById(R.id.start);
start_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent startBubble = new Intent(MainActivity.this, BubbleService.class);
startService(startBubble);
}
});
}
And here is the Service :
public class BubbleService extends Service {
private WindowManager windowManager;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
ImageView mFloatingImage = new ImageView(this);
mFloatingImage.setImageResource(R.mipmap.ic_launcher_round);
mFloatingImage.setClickable(true);
int LAYOUT_FLAG;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
}
WindowManager.LayoutParams params = new WindowManager.LayoutParams(150,
150,
LAYOUT_FLAG,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.x = 0;
params.y = 0;
params.gravity = Gravity.END | Gravity.CENTER;
windowManager.addView(mFloatingImage, params);
mFloatingImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("clicked");
}
});
return START_STICKY;
}
}