-1

以下服务通过点击某个其他应用程序(通过触发挂起的Intent)的按钮触发。 onStartCommand()使用send()方法创建一个Messages和dispatches。理想情况下,我期望每次点击按钮时调用onStartCommand,因为挂起的意图用于在buttonClick上触发服务。即使在多次启动服务时,onStartCommand()也只会被调用一次

但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

你在用'Message msg'做什么? – pskink

+0

@pskink没什么特别的,从为MyService到MyApp的味精告诉MyApp的基础上为MyService –

+0

进行计算,以更新的一些看法不是“没什么特别的”,因为'如果我评论的线replyTo.send(MSG);每次点击来自其他应用程序的按钮时,onStartCommand都会被调用。“# – pskink

回答

0

从文档:

客户还可以使用Context.bindService()来获得持久 连接到服务。如果 尚未运行(同时调用onCreate()),但是不调用onStartCommand(),则同样会创建该服务。客户端将收到服务从其onBind(Intent)方法返回的IBinder对象,允许 客户端将呼叫回拨给该服务。该服务将继续 只要建立连接(在 客户机是否保留对服务的的IBinder参考)上运行。 IBinder通常返回的是一个复杂的界面,已经写入 aidl。

所以,这可能是因为使用的bindService

+0

没有让你,你能详细说明吗?并且添加msg.send()时,onStartCommand回调会中断。无法理解那部分。感谢您的回复:) –

+0

将您的代码发布到初始化/启动服务的位置 –

+0

添加了更多代码,因此服务在按钮单击时使用onCreate()中提供的挂起的意图开始。小小的纠结... –

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)。

相关问题