AndroidのIntentServiceからインテントを共有する方法を徹底解説
IntentServiceとは?
具体例に入る前に、AndroidにおけるIntentServiceについて確認しておきましょう。IntentServiceは、バックグラウンド処理を非同期で実行するためのサービスコンポーネントです。アクティビティからstartService()を呼び出した場合でも、リクエストごとに新しいインスタンスは生成されません。また、サービスクラス内の処理が完了すれば自動的に終了し、必要に応じてstopSelf()を呼び出して明示的に停止させることも可能です。
この記事では、IntentServiceからインテントを共有(シェア)する方法を、サンプルコードとともにわかりやすく解説します。
ステップ1:新規プロジェクトの作成
まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを作成してください。
ステップ2:レイアウトファイルの作成
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を配置しています。ユーザーがこのTextViewをタップすると、Android OS標準の共有ダイアログが開く仕組みです。
ステップ3:MainActivity.javaの実装
src/MainActivity.java に以下のコードを追加します。
package com.example.andy.myapplication;
import android.content.Intent;
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;
@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));
}
});
}
}
次に、service.javaという名前のクラスファイルを作成し、以下のコードを記述します。
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 sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Tutorialspoint.com");
startActivity(Intent.createChooser(sharingIntent, "Sharing"));
if(shouldStop) {
stopSelf();
return;
}
}
}
onHandleIntent()の中でACTION_SENDインテントを作成し、createChooser()を呼び出すことで、共有先を選択するダイアログを表示できます。サービスを停止させたい場合は、サービスクラス内で以下のコードを使用します。
stopSelf();
ステップ4:マニフェストファイルの設定
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>
ここでは、WAKE_LOCK権限の宣言と、作成したサービスクラス(.service)の登録を行っています。サービスを利用する際は、マニフェストへの登録を忘れないように注意しましょう。
アプリの実行と動作確認
それでは、アプリを実行してみましょう。実際のAndroid端末をパソコンに接続していることを前提としています。Android Studioでプロジェクトのアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。接続したモバイルデバイスを選択すると、端末にアプリの初期画面が表示されます。

上記がアプリの初期画面です。TextViewをタップすると、以下のようにモバイルOS標準の共有ダイアログが表示されます。

補足:IntentServiceは非推奨
なお、IntentServiceはAPIレベル30(Android 11)以降で非推奨(Deprecated)となっています。新規開発では、WorkManagerなどの代替手段の利用が推奨されています。一方、既存コードの保守や学習目的としては依然として有用なので、プロジェクトの要件に応じて適切に使い分けてください。
-
AndroidからPCへファイルを転送する3つの方法|クラウド・Bluetooth・転送アプリを徹底解説
現代では、パソコンよりもスマートフォンを使う時間の方が圧倒的に長くなっています。そのため、写真や動画、書類などのファイルの多くは、PCではなくスマホの中に保存されているのが実情です。しかし、AndroidやiPhoneには保存できる容量に上限があり、それ以上データを増やすことができません。そこで、空き容量が豊富なPCにデータを移しておくのが賢い選択となります。 とはいえ、スマホからPCへのファイル移行は意外と手間がかかるものです。すべてのファイルやフォルダを手作業で一つずつ移していたら、膨大な時間がかかってしまいます。ご安心ください。この記事では、AndroidとPCの間でファイルを効率よ
-
Androidの画面をPCにミラーリング!USBデバッグからAirDroid・TeamViewer活用まで徹底解説
結婚式の写真やお気に入りの映画がAndroidスマホの中に入っていて、大画面で楽しみたいと思ったことはありませんか?どうすれば実現できるのでしょうか。その答えが「AndroidからPCへのスクリーンミラーリング」です。画面を共有すれば、友人や家族と一緒にお気に入りの映画を大画面で鑑賞できます。この記事では、Androidの画面をPCにミラーリングする具体的な手順を詳しく解説します。ステップ1:USBデバッグを有効にするまず、USBデバッグとは何かを理解しておきましょう。USBデバッグとは、Android端末に用意されている開発者向け機能の一つで、USB接続を通じてテスト用デバイス(PCなど)か