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

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

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

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

サービス

サービスとはバックグラウンド上に常駐し、長時間稼動し続ける実行可能ファイルを指します。

Q&A

0回答

1677閲覧

Android開発 onDestroyからはサービス停止はできないのですか?

gomiyasuo

総合スコア9

Android

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

サービス

サービスとはバックグラウンド上に常駐し、長時間稼動し続ける実行可能ファイルを指します。

0グッド

0クリップ

投稿2021/05/29 00:14

Serviceを利用したアプリを作りましたが
アプリ終了時にServiceが停止でできない状態で
困っており質問します

問題は
MainActivityのonDestroy内で
stopService()
を呼び出しても
サービスが停止しません
(操作は
「アプリ起動」(サービスが起動)→そのまま「アプリを終了」
だと、停止しない)

※通知アイコンは消えてくれて、一見終了したように見えるのですが
設定メニューから見てみると動いたままになっており
(正確にはサービスなのか他になにかメモリにあるのか・・
わからないのですが)
とりあえず、停止していない状態です

試しに
画面にボタンを作って
そのボタンを押すとサービスが停止するよう実装すると
(stopServiceを実行)
サービスは停止してくれます
(操作は
「アプリ起動」(サービスが起動)→「ボタンを押してサービスを停止」→「アプリを終了」
だと、問題ありません)

なぜonDestroy内で呼び出した
stopServiceではサービスが停止しないのでしょうか?
(そんな仕様なの?)

実機テストした端末は
Pixel2
OSはAndroid11です

以下、実際にテストしている簡略化したコードです
(MainActivityとServiceのソース2つ)

MainActivity

1 2public class MainActivity extends AppCompatActivity { 3 4 Button btnTest; 5 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 9 super.onCreate(savedInstanceState); 10 setContentView(R.layout.activity_main); 11 12 btnTest= (Button)findViewById(R.id.btnTest); 13 14 Intent intent = new Intent(getApplicationContext(), ServiceTest.class); 15 intent.putExtra("REQUEST_CODE", 1); 16 17 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ 18 startForegroundService(intent); 19 }else{ 20 startService(intent); 21 } 22 23 // サービス停止ボタン このボタンを押した場合はサービスは停止してくれます 24 btnTest.setOnClickListener(new View.OnClickListener() { 25 26 @SuppressLint("ResourceType") 27 @Override 28 public void onClick(View v) { 29 30 // 画面のボタンを押した場合の 31 // ここでは問題なくサービスが停止します 32 Intent intent = new Intent(getApplicationContext(), ServiceTest.class); 33 stopService(intent); 34 35 } 36 }); 37 38 } 39 40 public void onDestroy() { 41 42 super.onDestroy(); 43 44 // [ ここが問題! ] 45 // 上記のサービス停止ボタンを押さない状態で 46 // アプリを終了させたときはstopServiceを実行しているのにサービスが停止してくれません 47 Intent intent = new Intent(getApplication(), ServiceTest.class); 48 stopService(intent); 49 50 } 51 52} 53

※サービスは起動しているだけで、なにも実行していません

Service

1 2 3public class ServiceTest extends Service 4{ 5 6 public void onCreate() { 7 super.onCreate(); 8 } 9 10 public int onStartCommand(Intent intent, int flags, int startid) { 11 super.onStartCommand(intent, flags, startid); 12 13 14 Notification notification; 15 NotificationManager mNotificationManager=null; 16 17 int smallIcon; 18 Bitmap largeIcon; 19 20 super.onStartCommand(intent, flags, startid); 21 22 23 Context context = getApplication(); 24 25 largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.notification_icon ); 26 smallIcon = R.drawable.notification_icon; 27 28 int requestCode = intent.getIntExtra("REQUEST_CODE",0); 29 String channelId = "ChannelIです"; 30 31 String title = context.getString(R.string.app_name); 32 Intent intent2 = new Intent(context, MainActivity.class); 33 PendingIntent pendingIntent = 34 PendingIntent.getActivity(context, requestCode, intent2, PendingIntent.FLAG_UPDATE_CURRENT); 35 36 37 mNotificationManager= 38 (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); 39 40 41 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 42 43 int importance = NotificationManager.IMPORTANCE_LOW; 44 NotificationChannel channel = new NotificationChannel(channelId, title, importance); 45 46 channel.enableVibration(false); 47 mNotificationManager.createNotificationChannel(channel); 48 49 notification = new Notification.Builder(context, channelId) 50 .setContentTitle(title) 51 .setSmallIcon(smallIcon) 52 .setLargeIcon(largeIcon) 53 .setContentText("メッセージ") 54 .setAutoCancel(true) 55 .setContentIntent(pendingIntent) 56 .setWhen(System.currentTimeMillis()) 57 .build(); 58 59 60 }else { 61 62 notification = new NotificationCompat.Builder(context) 63 .setContentTitle(title) 64 .setSmallIcon(smallIcon) 65 .setLargeIcon(largeIcon) 66 .setContentText("メッセージ") 67 .setAutoCancel(true) 68 .setContentIntent(pendingIntent) 69 .setWhen(System.currentTimeMillis()) 70 .build(); 71 72 73 74 } 75 76 77 notification.flags |= Notification.FLAG_ONGOING_EVENT; 78 notification.flags |= Notification.FLAG_NO_CLEAR; 79 80 startForeground(20190918, notification); 81 82 83 return START_NOT_STICKY; 84 85 } 86 87 public void onDestroy() { 88 89 super.onDestroy(); 90 91 92 } 93 protected final IBinder binder = new Binder() { 94 @Override 95 protected boolean onTransact(int code, Parcel data, Parcel reply, int flags ) throws RemoteException 96 { 97 return super.onTransact(code, data, reply, flags); 98 } 99 }; 100 101 public IBinder onBind(Intent intent) { 102 return binder; 103 } 104 105 106} 107 108

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

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

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

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

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

gomiyasuo

2021/06/06 05:08

一応、ログを取るとonDestroyは通過しているので 今回の質問の件とはすこし違うような・・ (もちろん、おっしゃる通りonDestotyが呼ばれない場合もあると思います) 問題は 「onDestroyでstopServiceを呼び出してもサービスが停止しないのはなぜか?」という点 (回答を参考にonStop内でstopServiceを呼び出したら正常に終了しました)
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.47%

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

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

質問する

関連した質問