【发布时间】:2016-10-20 16:21:09
【问题描述】:
我是 Android 开发的新手,我正在尝试创建一个简单的“概念验证应用程序”,它将作为后台服务运行。我正在尝试将 IntentService 与 BroadcastReceiver 一起使用来启动该过程(目前在启动期间,有时我可能会将其切换到 Screen on / user present)。
我在 Android Studio 中创建了一个没有任何活动的新项目。然后我添加了以下 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 中输出的任何日志。
我确定我做错了什么——帮我弄清楚是什么:D。谢谢!
【问题讨论】:
-
您的应用需要有一个
Activity,您在安装后至少启动一次以使其脱离已停止状态。在此之前,您的启动接收器将不会收到广播(从 API 3.1 开始)。 -
好的,如果我添加一个活动,它只需要运行一次(不管手机是否重启等?)
-
是的,安装后基本上需要运行一次。但是,它可以恢复到 stopped 状态 - 例如,如果用户从设置中强行停止您的应用程序 - 在这种情况下,他们必须再次运行它才能让您的启动接收器工作。但是,简单地重新启动不会让它回到 stopped 状态。
标签: java android android-intent background-service