Androidで特定のIntentServiceを停止する方法を解説
IntentServiceとは?
サンプルコードに入る前に、AndroidにおけるIntentServiceの基本を確認しておきましょう。IntentServiceは、バックグラウンド処理を非同期で実行するためのコンポーネントです。ActivityからstartService()を呼び出しても、リクエストごとにインスタンスが新しく生成されるわけではなく、サービスクラス内の処理が完了すると自動的にサービスが停止します。また、必要に応じてstopSelf()を呼び出すことで、手動でサービスを停止させることも可能です。
本記事では、Androidアプリで指定したIntentServiceを停止させる方法を、実際のサンプルコードとともに段階的に解説します。
手順1:新しいプロジェクトを作成する
Android Studioを開き、「File」→「New Project」から新規プロジェクトを作成します。必要な項目をすべて入力して、プロジェクトのセットアップを完了させてください。
手順2:レイアウトファイル(activity_main.xml)の編集
res/layout/activity_main.xmlに以下のコードを追加します。
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "https://schemas.android.com/apk/res/android"
xmlns:app = "https://schemas.android.com/apk/res-auto"
xmlns:tools = "https://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Start Service"
android:textSize = "25sp"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>このコードではTextViewを配置しています。ユーザーがIntentServiceからデータを受け取ると、このTextViewの表示内容が更新される仕組みです。
手順3:MainActivity.javaの実装
src/MainActivity.javaに以下のコードを追加します。
package com.example.andy.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView text;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String s1 = intent.getStringExtra("DATAPASSED");
text.setText(s1);
}
};
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.andy.myapplication");
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(MainActivity.this, service.class));
}
});
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(broadcastReceiver);
}
}上記のコードでは、サービスクラスの起動と、動的なBroadcastReceiverの登録を行っています。該当部分を抜粋すると以下の通りです。
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.andy.myapplication");
registerReceiver(broadcastReceiver, intentFilter);
}
…………………………………………..
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String s1 = intent.getStringExtra("DATAPASSED");
text.setText(s1);
}
};
………………………………………………………………………..
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(broadcastReceiver);
}serviceクラスの作成
次に、service.classという名前のクラスファイルを作成し、以下のコードを記述します。
package com.example.andy.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
public class service extends IntentService {
public static volatile boolean shouldStop = false;
public service() {
super(service.class.getSimpleName());
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
Intent intent1 = new Intent();
intent1.setAction("com.example.andy.myapplication");
intent1.putExtra("DATAPASSED", "Tutorialspoint.com");
sendBroadcast(intent1);
if(shouldStop) {
stopSelf();
return;
}
}
}サービスを停止したい場合は、サービスクラス内で以下のコードを使用します。
stopSelf();
ポイントは、volatile修飾子を付けたboolean型フラグ「shouldStop」を用意し、このフラグがtrueになったタイミングでstopSelf()を呼び出してIntentServiceを明示的に停止させている点です。
手順4:manifest.xmlの編集
manifest.xmlに以下のコードを追加します。
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
package = "com.example.andy.myapplication">
<uses-permission android:name = "android.permission.WAKE_LOCK"/>
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name = ".service"/>
</application>
</manifest><service android:name = ".service"/>の宣言により、作成したサービスクラスがマニフェストに登録され、システムが認識できるようになります。
アプリの実行と動作確認
それでは、実際にアプリを実行してみましょう。ここでは、Android端末を実機でPCに接続しているものとして説明を進めます。Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーのRunアイコン(緑色の再生ボタン)をクリックします。表示された選択肢から接続済みのモバイルデバイスを選択してください。
実行すると、まずアプリの初期画面が表示されます。
画面上の「Start Service」と表示されたテキストをタップすると、サービスが起動し、TextViewの表示内容が更新されます。
その後、MainActivityへブロードキャストが送信されると、IntentServiceは処理を完了して自動的に停止します。
まとめ
本記事では、Androidで特定のIntentServiceを停止する方法を紹介しました。ポイントは以下の3点です。
・IntentServiceはonHandleIntent()内の処理が完了すると自動的に停止する
・手動で停止したい場合はstopSelf()を呼び出す
・volatileなbooleanフラグを使えば、外部からの制御も柔軟に行える
バックグラウンド処理を扱う際には、サービスのライフサイクルを正しく理解し、適切なタイミングで確実に停止させることが、メモリリークやバッテリー消費の防止につながります。ぜひ本記事のサンプルコードを参考に、実際の開発に活用してみてください。
-
Androidでポップアップ広告を停止する方法|Chrome・アプリ・通知の設定を徹底解説
快適なはずのAndroid体験を台無しにする要因の中でも、ポップアップ広告はダントツの上位に位置しています。無関係な商品や怪しいサービスの広告が次々と表示され、近年ではその頻度も表示時間も大幅に増加しました。かつては些細なストレスにすぎなかったポップアップ広告も、今や多くのユーザーにとって深刻な悩みの種となっています。もしあなたもこの厄介な存在に悩まされているなら、そろそろ反撃の出番です。この記事では、Androidでポップアップ広告を停止する具体的な方法を詳しく解説します。 Androidでポップアップ広告を停止する方法 方法1:Chromeでポップアップ広告を無効にする ポップアップ広告
-
AndroidでWi-Fiが勝手にオンになるのを無効化する方法
Androidスマートフォンでは、手動でWi-Fiをオフにしたにもかかわらず、自動的に再接続されてしまうことがあります。これは、Googleが提供している「Wi-Fi自動オン機能」によるものです。せっかくオフにしたのにすぐにWi-Fiが復活してしまうと、不便に感じる方も多いのではないでしょうか。 この機能を好まないAndroidユーザーは少なくありません。そこで本記事では、AndroidでWi-Fiが自動的にオンになるのを無効化する方法をわかりやすく解説します。 Wi-Fiが自動的にオンになる理由 この現象の原因は、Googleの「Wi-Fi Wakeup(ウェイクアップ)」機能です。この機能