将数据从服务发送回我的活动

编程入门 行业动态 更新时间:2024-10-28 08:19:21
本文介绍了将数据从服务发送回我的活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个活动,可以创建一个意图,并在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 );

希望有帮助

更多推荐

将数据从服务发送回我的活动

本文发布于:2023-11-11 11:13:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1578270.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!