私はAndroid開発が初めてで、バックグラウンドサービスとして実行される簡単な「概念証明アプリケーション」を作成しようとしています。私はIntentServiceをBroadcastReceiverで使用してプロセスを起動しようとしています(起動時には、現在の画面に切り替えるかもしれません)。BroadcastReceiverがAndroidエミュレータで起動しないのはなぜですか?
私はAndroidスタジオ内で新しいプロジェクトを作成しました。次に、以下のJavaファイルを追加し、AndroidManifest.xmlに以下の変更を加えました。
のAndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.circlesquires.netcountable.netcountable">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">
</uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<service android:name=".SnapshotService" android:exported="true">
</service>
<receiver android:name=".ServiceStarter" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
ServiceStarter.java
package com.circlesquires.netcountable.netcountable;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* Created by camha on 6/18/2016.
*/
public class ServiceStarter extends BroadcastReceiver{
static final String ACTION = "android.intent.action.BOOT_COMPLETED";
@Override
public void onReceive(Context context, Intent intent) {
Log.i("output", "onReceive occured!");
if(intent.getAction().equals(ACTION)) {
Intent serviceIntent = new Intent(context, SnapshotService.class);
context.startService(serviceIntent);
}
}
}
SnapshotService.java
package com.circlesquires.netcountable.netcountable;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
/**
* Created by camha on 6/18/2016.
*/
public class SnapshotService extends IntentService {
public SnapshotService() {
super("SnapshotService");
}
@Override
protected void onHandleIntent(Intent workIntent) {
while(true) {
Log.i("output", "I'm running!");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
私は、 "デバッグ" ボタンをクリックしてくださいというエミュレータにアプリケーションをデプロイします。しかし、私はlogcatで出力されたログのどれも見ることはありません。
私は何か間違っていると確信しています。ありがとう!
アプリは、あなたが_stopped_状態からそれを持って来るために、インストール後に少なくとも一度起動し 'Activity'を持っている必要があります。それまでは、あなたのブートレシーバーはブロードキャストされません(API 3.1以降)。 –
さて、アクティビティを追加すると、電話を再起動しても関係なく1回実行する必要があります。 – CamHart
インストール後は基本的に1回実行する必要があります。ただし、ユーザーが設定から強制的にアプリケーションを停止した場合など、_stopped_状態に戻すことができます。その場合は、起動するReceiverが動作するために再度実行する必要があります。しかし、再起動するだけで、それを_stopped_状態に戻すことはできません。 –