java Android服务将无法继续运行
我的应用已经有了一个处理通知的服务,但我需要另一个在后台持续运行的服务,用于监听来自Pebble smartwatch的传入数据
然而,出于某种原因,尽管该服务在Android清单中声明,并将随应用程序一起启动,但它会立即永久关闭
我真的不想使用前台服务,因为我觉得我不应该这么做。有很多像Facebook和Music Boss这样的服务在后台以持续的方式悄悄运行
服务正在主活动的onCreate
中启动,为什么我的服务会立即被终止
服务生。爪哇:
package net.thevgc.quotes;
import 安卓.app.NotificationManager;
import 安卓.app.PendingIntent;
import 安卓.app.Service;
import 安卓.content.Context;
import 安卓.content.Intent;
import 安卓.os.IBinder;
import 安卓.support.v4.app.NotificationCompat;
import com.getpebble.安卓.kit.PebbleKit;
import com.getpebble.安卓.kit.util.PebbleDictionary;
import java.util.UUID;
public class PebbleService extends Service {
private PebbleKit.PebbleDataReceiver appMessageReciever;
private static final int KEY_AUTHOR = 1;
private static final int KEY_QUOTE = 0;
private static final UUID WATCHAPP_UUID = UUID.fromString("18451441-8451-4418-4514-418451441845");
public void onCreate() {
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
String[] extras = (String[]) intent.getSerializableExtra("data");
final String quote = extras[0];
final String author = extras[1];
// Define AppMessage behavior
if (appMessageReciever == null) {
appMessageReciever = new PebbleKit.PebbleDataReceiver(WATCHAPP_UUID) {
@Override
public void receiveData(Context context, int transactionId, PebbleDictionary data) {
// Always ACK
PebbleKit.sendAckToPebble(context, transactionId);
// Send KEY_QUOTE to Pebble
PebbleDictionary out = new PebbleDictionary();
out.addString(KEY_QUOTE, mainActivity.quote[0]);
out.addString(KEY_AUTHOR, mainActivity.quote[1]);
PebbleKit.sendDataToPebble(getApplicationContext(), WATCHAPP_UUID, out);
}
};
// Add AppMessage capabilities
PebbleKit.registerReceivedDataHandler(this, appMessageReciever);
}
return START_STICKY;
}
public IBinder onBind(Intent intent) {
return null;
}
}
来自AndroidManifest。xml:
<service
安卓:enabled="true"
安卓:name="PebbleService" />
更新:显然,服务正在某个地方运行,因为我对代码进行了一些修改,现在我得到了一个空指针,但只有当我关闭主活动时。我很确定它正在重新启动,无法从主要活动中找到它需要的额外数据,因为这不是它启动的初衷。这意味着我仍然需要使用MainActivity mainActivity = new MainActivity();
来获取所需的字符串数据
更新2:好吧,我对造成这么多混乱感到非常抱歉。服务正在运行,但它没有显示在我的设置中>;应用程序>;运行列表,甚至在父活动下。但我知道它正在运行,因为它最终确定了它应该做什么。猜测蓝牙连接薄弱。尽管如此,我仍在抛出一个NullPointerException,当前代码试图接收intent extras。不过,我对这个问题已经有了opened a new thread
# 1 楼答案
由于您正在返回
START_NOT_STICKY
,Android将在您的Service
从onStartCommand()
返回后立即停止。如果你想让你的Service
保持活力,那么你需要从onStartCommand()
返回START_STICKY
此外,你的
Service
不会随应用程序自动启动。它需要通过调用startService()
来启动此外,正如有人在评论中指出的,不要使用
new
创建Android组件,如下所示:只有Android可以正确地实例化组件
Activity
、Service
、BroadcastReceiver
和Provider
,因为它们还需要设置Context