質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Android

Androidは、Google社が開発したスマートフォンやタブレットなど携帯端末向けのプラットフォームです。 カーネル・ミドルウェア・ユーザーインターフェイス・ウェブブラウザ・電話帳などのアプリケーションやソフトウェアをひとつにまとめて構成。 カーネル・ライブラリ・ランタイムはほとんどがC言語/C++、アプリケーションなどはJavaSEのサブセットとAndroid環境で書かれています。

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Kotlin

Kotlinは、ジェットブレインズ社のアンドリー・ブレスラフ、ドミトリー・ジェメロフが開発した、 静的型付けのオブジェクト指向プログラミング言語です。

Q&A

解決済

1回答

3266閲覧

オーバーレイ表示したViewをメインアクティビティが非表示になっても操作したい

wkt1227

総合スコア12

Android

Androidは、Google社が開発したスマートフォンやタブレットなど携帯端末向けのプラットフォームです。 カーネル・ミドルウェア・ユーザーインターフェイス・ウェブブラウザ・電話帳などのアプリケーションやソフトウェアをひとつにまとめて構成。 カーネル・ライブラリ・ランタイムはほとんどがC言語/C++、アプリケーションなどはJavaSEのサブセットとAndroid環境で書かれています。

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Kotlin

Kotlinは、ジェットブレインズ社のアンドリー・ブレスラフ、ドミトリー・ジェメロフが開発した、 静的型付けのオブジェクト指向プログラミング言語です。

0グッド

0クリップ

投稿2019/06/25 15:47

前提・実現したいこと

Androidでメインウィンドウが閉じても、サブウィンドウが常駐アプリとして画面に残り続けるアプリ(フローティングアプリ)を作りたいです。そのために次の機能を持つアプリをこのサイトを参考にして作成しました。

・メインウィンドウでは、サブウィンドウを作成するボタンがある。
・サブウィンドウでは、メインウィンドウ、サブウィンドウのそれぞれを閉じるボタンがある。

発生している問題・エラーメッセージ

作成したアプリをLollipop(API Level 22),Marshmallow(API Level 23),Oreo(API Level 26)の3種類のバージョンのエミュレータで動かしてみました。Lollipop,Oreoでは問題なく動いたのに対し、Marshmallowで以下の問題が起きてしまいました。

・サブウィンドウを表示させたまま、メインウィンドウを閉じると、サブウィンドウを操作できなくなる(ボタンが押せない)。
・メインウィンドウを再度表示させると、サブウィンドウが操作可能になる。

該当のソースコード

MainActivity.kt

kotlin

1package com.example.overlayapp 2 3import android.content.ComponentName 4import android.content.Context 5import android.content.Intent 6import android.content.ServiceConnection 7import android.graphics.PixelFormat 8import android.net.Uri 9import android.os.Build 10import androidx.appcompat.app.AppCompatActivity 11import android.os.Bundle 12import android.os.IBinder 13import android.provider.Settings 14import android.view.Gravity 15import android.view.View 16import android.view.WindowManager 17import android.widget.Button 18import kotlinx.android.synthetic.main.activity_main.* 19 20class MainActivity : AppCompatActivity() { 21 22 private var _windowManager: WindowManager? = null 23 private var _subWindowFragment: SubWindowFlagment? = null 24 private var _subWindowService: SubWindowService? = null 25 26 27 // Build.VERSION.SDK_INT < 22 の対応 28 private val _connection = object : ServiceConnection { 29 override fun onServiceConnected(componentName: ComponentName, iBinder: IBinder) { 30 _subWindowService = (iBinder as SubWindowService.SubWindowServiceBinder).service 31 openWindow() 32 } 33 34 override fun onServiceDisconnected(componentName: ComponentName) {} 35 } 36 37 /* 38 * メインの画面作成 39 */ 40 override fun onCreate(savedInstanceState: Bundle?) { 41 super.onCreate(savedInstanceState) 42 setContentView(R.layout.activity_main) 43 44 openWindowButton.setOnClickListener { openSubWindow() } 45 } 46 47 /* 48 * サブウィンドウを作成 49 */ 50 fun openSubWindow() { 51 if (Build.VERSION.SDK_INT >= 23) { 52 // Marshmallow 以上用の処理 53 if (Settings.canDrawOverlays(this)) { 54 if (_subWindowFragment != null && _subWindowFragment!!.overlayView != null) { 55 closeSubWindow() 56 } 57 58 val layoutFlag = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ 59 WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY 60 } else { 61 WindowManager.LayoutParams.TYPE_SYSTEM_ALERT 62 } 63 64 val params = WindowManager.LayoutParams( 65 WindowManager.LayoutParams.WRAP_CONTENT, 66 WindowManager.LayoutParams.WRAP_CONTENT, 67 layoutFlag, 68 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, 69 PixelFormat.TRANSLUCENT 70 ) 71 params.gravity = Gravity.TOP or Gravity.LEFT 72 73 _windowManager = this.getSystemService(Context.WINDOW_SERVICE) as WindowManager 74 _subWindowFragment = SubWindowFlagment() 75 _windowManager!!.addView(_subWindowFragment!!.loadView(this), params) 76 77 78 } else { 79 // サブウィンドウ生成の権限がなかった場合は、下記で権限を取得する 80 val intent = 81 Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:com.example.overlayapp")) 82 this.startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE) 83 } 84 } else { 85 // Lollipop 以前用の処理 86 startService(Intent(this@MainActivity, SubWindowService::class.java)) 87 // Binder によるサブウィンドウとの接続 88 bindService(Intent(this@MainActivity, SubWindowService::class.java), _connection, Context.BIND_ABOVE_CLIENT) 89 } 90 } 91 92 fun openWindow() { 93 _subWindowService!!.openWindow(this) 94 } 95 96 // Build.VERSION.SDK_INT >= 23 の対応 97 fun closeSubWindow() { 98 if (Build.VERSION.SDK_INT >= 23) { 99 if (_subWindowFragment != null && _subWindowFragment!!.overlayView != null) { 100 _windowManager!!.removeView(_subWindowFragment!!.overlayView) 101 _subWindowFragment!!.overlayView = null 102 } 103 } else { 104 _subWindowService!!.closeSubWindow() 105 stopService(Intent(this@MainActivity, SubWindowService::class.java)) 106 } 107 } 108 109 /* 110 * Lollipop までは、メインウィンドウをバックグランドに入れる際に onDestroy が実行されてしまう 111 */ 112 override fun onDestroy() { 113 super.onDestroy() 114 if (Build.VERSION.SDK_INT >= 23) { 115 closeSubWindow() 116 } 117 } 118 119 companion object { 120 private val ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 1234 // 適当な数字でOK? 121 } 122} 123 124

activity_main.xml

xml

1<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:layout_width="match_parent" 3 android:layout_height="match_parent"> 4 5 <Button 6 android:layout_width="wrap_content" 7 android:layout_height="wrap_content" 8 android:text="常駐" 9 android:id="@+id/openWindowButton" 10 android:layout_marginTop="10dp" 11 android:layout_alignParentTop="true" 12 android:layout_alignParentLeft="true" 13 android:layout_marginLeft="10dp" /> 14</RelativeLayout>

SubWindowFragment.kt

kotlin

1package com.example.overlayapp 2 3import androidx.fragment.app.Fragment 4import android.view.LayoutInflater 5import android.view.View 6import android.widget.Button 7 8internal class SubWindowFlagment : Fragment() { 9 var overlayView: View? = null 10 private var _activity: MainActivity? = null 11 12 /* 13 * 画面呼び出し 14 */ 15 fun loadView(mainActivity: MainActivity): View { 16 _activity = mainActivity 17 18 val inflater = LayoutInflater.from(_activity) 19 overlayView = inflater.inflate(R.layout.fragment_sub_window, null) 20 21 // メインウィンドウを閉じるボタン 22 val windowButton = overlayView?.findViewById<View>(R.id.closeMainButton) as Button 23 windowButton.setOnClickListener { closeMainWindow() } 24 25 // 常駐アプリを閉じるボタン 26 val closeButton = overlayView?.findViewById<View>(R.id.closeSubButton) as Button 27 closeButton.setOnClickListener { closeSubWindow() } 28 29 return overlayView as View 30 } 31 32 /* 33 * メインウィンドウを閉じる 34 */ 35 private fun closeMainWindow() { 36 _activity!!.moveTaskToBack(true) 37 } 38 39 /* 40 * サブウィンドウを閉じる 41 */ 42 private fun closeSubWindow() { 43 _activity!!.closeSubWindow() 44 } 45} 46

fragment_sub_window.xml

xml

1<?xml version="1.0" encoding="utf-8"?> 2<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="horizontal" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:background="@color/colorWindow"> 7 8 <Button 9 android:id="@+id/closeMainButton" 10 android:layout_width="wrap_content" 11 android:layout_height="wrap_content" 12 android:text="Close\nMain"/> 13 14 <Button 15 android:id="@+id/closeSubButton" 16 android:layout_width="wrap_content" 17 android:layout_height="wrap_content" 18 android:layout_toRightOf="@+id/closeMainButton" 19 android:layout_marginLeft="20dp" 20 android:text="close\nsub"/> 21</RelativeLayout>

AndroidManifest.xml

xml

1<?xml version="1.0" encoding="utf-8"?> 2<manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.example.overlayapp"> 4 5 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> 6 7 <application 8 android:allowBackup="true" 9 android:icon="@mipmap/ic_launcher" 10 android:label="@string/app_name" 11 android:roundIcon="@mipmap/ic_launcher_round" 12 android:supportsRtl="true" 13 android:theme="@style/AppTheme"> 14 <service 15 android:name=".SubWindowService" 16 android:enabled="true" 17 android:exported="true"> 18 </service> 19 20 <activity android:name=".MainActivity"> 21 <intent-filter> 22 <action android:name="android.intent.action.MAIN"/> 23 24 <category android:name="android.intent.category.LAUNCHER"/> 25 </intent-filter> 26 </activity> 27 </application> 28 29</manifest>

試したこと

・サブウィンドウのレイヤータイプをTYPE_PHONEにしてみた。
・Javaでコードを書き直してみた。
・レイヤータイプ以外にもLayoutParamsをいじってみた。

補足情報(FW/ツールのバージョンなど)

Android Gradle Plugin Version: 3.4.1
Gradle Version: 5.1.1

Lollipop エミュレータ: Pixel 2
Marshmallow エミュレータ: Pixel 2
Oreo エミュレータ: Pixel 3

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

おそらく問題の原因は、MainActivityのWindowManagerに対してサブウィンドウのViewを追加していることでしょう。MainActivityが死んだ時点でそれに紐づくWindowも操作を受け付けなくなります。Oreoでうまく動いているのはMainActivityがたまたますぐに破棄されなかったためでしょう。そのうち操作できなくなるはずです。

解決するには、SubWindowServiceから取得したWindowManagerに目的のViewを追加するようにしてください。Lollipop用のコードではそのように実装されていますから、他のバージョンも同じように調整するのがよいと思います。


また、参考にされている記事のコードがかなりひどいので、他の情報を探されることをおすすめします。

  • SubWindowFlagmentはFragment本来の使い方を無視していてFragmentとして利用するわけでもないのに、Fragmentを継承しているのが謎
  • WindowManagerへの追加のコードがActivity内/Service内にコピペしたようなものが2重に存在し、統一できていない
  • ActivityのContextを元にinflateしたViewをServiceのWindowManagerに追加している

投稿2019/06/26 05:07

kakajika

総合スコア3131

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

wkt1227

2019/06/26 08:44

おっしゃるようにすべてのバージョンで、WindowManagerをSubWindowService内で取得するようにしたら解決しました。ありがとうございます。 Fragmentを使わない方法を探してみたいと思います。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問