通过从其他应用程序点击按钮(通过触发待处理的Intent)触发以下服务。 onStartCommand()使用send()方法创建消息和调度。理想情况下,我希望每次单击按钮时都会调用onStartCommand,因为挂起的意图用于在buttonClick上触发服务。
但onstartCommand()只被调用一次,这是第一次点击按钮。后续按钮单击不会触发onStartCommand()。
有趣的是,如果我评论这条线 replyTo.send(MSG); 每次单击来自其他应用程序的按钮时,都会调用onStartCommand。
因此,从服务中使用Android IPC Messenger调度消息可能会导致问题。我确认消息已成功到达目标应用程序。我是否遗漏了一些关于消息的细节,比如阻止发送呼叫?
我从onStartCommand()返回'START_STICKY',这也可能就是原因。
欢迎任何有关正在发生的事情的见解。
// MyService.java
@Override
public void onCreate() {
// create RemoteViews -> rView
Intent intent = new Intent(getBaseContext(), MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(getBaseContext(), 0, intent, 0);
rView.setOnClickPendingIntent(buttonId, pendingIntent);
//On click of the above button, this MyService will be started usingthe given pendingintent
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("debug","Service onStartCommand");
Message msg = Message.obtain(null, UPDATE_REMOTE_VIEW, rView);
try {
replyTo.send(msg);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return START_STICKY;
}
奖励明细:按钮上的pendingIntent(来自其他应用)使用setOnclickPendingIntent()(RemoteViews类)设置。
答案 0 :(得分:1)
我在类似案例中所做的是实施onStartCommand
,如下所示:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//
// ... HERE support for intent sent by setOnClickPendingIntent ...
//
return super.onStartCommand(intent, flags, startId);
}
它似乎有效。多次调用onStartCommand
(与我RemoteViews
点击的次数一样多。)
答案 1 :(得分:0)
来自文档:
客户端也可以使用Context.bindService()来获取持久性 连接到服务。如果是这样,这同样会创造服务 尚未运行(在执行此操作时调用onCreate()),但没有 调用onStartCommand()。客户端将收到IBinder对象 服务从其onBind(Intent)方法返回,允许 然后客户端回拨服务。该服务将保留 只要建立连接就运行(无论是否连接 客户保留对服务的IBinder的参考。通常是 IBinder返回的是一个已写入的复杂接口 AIDL。
所以,可能是因为使用了bindService