public class FloatingButtonService extends Service {
private WindowManager windowManager;
private WindowManager.LayoutParams layoutParams;
private Button button;
BatteryManager bm;
String value="";
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
handler.removeMessages(0);
float a = ToMA(bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW));
value="电流" + a + "毫安";
button.setText("电流" + a + "毫安");
handler.sendEmptyMessageDelayed(0, 1000);
static float ToMA(float maOrua)
return maOrua < 10000 ? maOrua : maOrua / 1000f;
@Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
layoutParams = new WindowManager.LayoutParams();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
layoutParams.format = PixelFormat.RGBA_8888;
layoutParams.gravity = Gravity.CENTER;
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
layoutParams.width = 500;
layoutParams.height = 100;
layoutParams.x = 300;
layoutParams.y = 300;
bm = (BatteryManager)getSystemService(BATTERY_SERVICE);
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
showFloatingWindow();
return super.onStartCommand(intent, flags, startId);
private void showFloatingWindow() {
if (Settings.canDrawOverlays(this)) {
button = new Button(getApplicationContext());
button.setBackgroundColor(Color.BLUE);
button.setAlpha(0.8f);
button.setPadding(0,0,0,0);
windowManager.addView(button, layoutParams);
handler.sendEmptyMessage(0);
button.setOnTouchListener(new FloatingOnTouchListener());
private class FloatingOnTouchListener implements View.OnTouchListener {
private int x;
private int y;
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x = (int) event.getRawX();
y = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int nowX = (int) event.getRawX();
int nowY = (int) event.getRawY();
int movedX = nowX - x;
int movedY = nowY - y;
x = nowX;
y = nowY;
layoutParams.x = layoutParams.x + movedX;
layoutParams.y = layoutParams.y + movedY;
windowManager.updateViewLayout(view, layoutParams);
break;
default:
break;
return false;