package jackall.moncalc.service import android.app.Service import android.content.Context import android.content.Intent import android.graphics.PixelFormat import android.graphics.Point import android.os.Build import android.os.IBinder import android.support.v4.app.NotificationCompat import android.view.* import jackall.moncalc.Const import jackall.moncalc.R /** * Created by matsumoto_k on 2017/11/01. */ class MainService : Service() { val overlayView: ViewGroup by lazy { LayoutInflater.from(this).inflate(R.layout.overlay_layout, null) as ViewGroup } val windowManager: WindowManager by lazy { applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager } var params: WindowManager.LayoutParams? = null val displaySize: Point by lazy { val display = windowManager.defaultDisplay val size = Point() display.getSize(size) size } var isLongClick: Boolean = false override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { val notificationBuilder = NotificationCompat.Builder(this, Const.serviceChannelId) .setContentTitle("mainService") // TODO:タイトルをセット .setSmallIcon(R.mipmap.ic_launcher) // TODO:白抜きのアイコンをセット startForeground(Const.notificationId, notificationBuilder.build()) setInitOverlayView() return START_STICKY } private fun setInitOverlayView() { overlayView.apply(clickListener()) if (Build.VERSION.SDK_INT >= 26) { params = WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, PixelFormat.TRANSLUCENT) } else { params = WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, PixelFormat.TRANSLUCENT) } windowManager.addView(overlayView, params) } private fun clickListener(): View.() -> Unit { return { setOnLongClickListener { view -> isLongClick = true false }.apply { setOnTouchListener { view, motionEvent -> val x = motionEvent.rawX.toInt() val y = motionEvent.rawY.toInt() when (motionEvent.action) { MotionEvent.ACTION_MOVE -> { if (isLongClick) { val centerX = x - (displaySize.x / 2) val centerY = y - (displaySize.y / 2) params?.x = centerX params?.y = centerY windowManager.updateViewLayout(overlayView, params) } } MotionEvent.ACTION_UP -> { if (isLongClick) { } isLongClick = false } } false } } } } override fun onBind(intent: Intent?): IBinder? { return null } }