我有一个活动,可以创建一个意图,并在putExtra()中添加一些额外内容,并调用startService(intent)以启动服务.
I have an activity that creates an intent, puts some extras with putExtra() and calls the startService(intent) to start a service.
此服务根据附加功能计算一些内容,然后我想将结果发送回活动.
This service calculates some stuff based on the extras and then I want to send the result back to the activity.
我可以通过哪种方式做到这一点?
In which way can I do this?
我试图在我的服务上创建一个意图,并使用sendBroadcast()对其进行广播.我在活动上有一个broadcastReceiver,但是我不确定我是否正确注册了它.我很困惑!
I tried to create an intent on my service and broadcast it using sendBroadcast(). I have a broadcastReceiver on the activity but Im not sure if I register it correctly. Im confused!
还有其他方法吗?诸如StartActivityForResult之类的东西,但用于服务(诸如StartServiceForResult之类的东西)?
Is there any other way to do so? Something like StartActivityForResult but for services (something like StartServiceForResult or something)?
推荐答案您尝试使用的方法很好!如果没有代码,将很难说出您可能做错了什么.
The method you are attempting to use is good! Without code though it will be hard to say what you might be doing incorrectly.
在您的服务中,您将广播这样的意图...
In your service you would broadcast an intent like this...
/** * Send broadcast to the activity letting it know the service is active * * @param pActivate */ private final void sendServiceActiveBroadcast( final boolean pActivate ) { final Intent _intent = new Intent(); _intent.setAction( "com.yourtld.android.SERVICE_BROADCAST" ); _intent.addCategory( "com.yourtld.android.CATEGORY" ); _intent.putExtra( "isactive", pActivate ); this.sendBroadcast( _intent ); }然后在您的活动中,您可能会遇到类似...
then in your activity you could have something like...
创建操作字符串:
private static final String SERVICE_BROADCAST_ACTION = "com.yourtld.android.SERVICE_BROADCAST";在您的onResume()方法中,您应该...
In your onResume() method you would have...
final IntentFilter serviceActiveFilter = new IntentFilter( SERVICE_BROADCAST_ACTION ); serviceActiveFilter.addCategory( "com.yourtld.android.CATEGORY" ); this.serviceReceiver = new BroadcastReceiver() { @Override public void onReceive( final Context context, final Intent intent ) { if( intent != null ) { if( intent.getBooleanExtra( "isactive", false ) ) { // The service is active } else { // False... } } } }; this.registerReceiver( this.serviceReceiver, serviceActiveFilter );希望有帮助
更多推荐
将数据从服务发送回我的活动
发布评论