从由BroadcastReceiver启动的服务更新ProgressBar [英] Update ProgressBar from a Service started by a BroadcastReceiver
问题描述
这是场景:我有一个BroadcastAction接收器,它监听ACTION_PHONE_STATE_CHANGED,并且当它更改时,它将启动服务.该服务通过CallLog进行查询,当查询增加时,我想在MainActivity的几个ProgressBar上显示它,但是我该怎么做呢?
This is the scenario: i have a BroadcastReceiver that listen to the ACTION_PHONE_STATE_CHANGED, and when it changes it starts a Service. This service make a query con the CallLog, and when something increases i want to show it on several ProgressBar on the MainActivity, but how can i do that?
我正在考虑创建一个Application类,该类将MainActivity和Service子类化,然后我可以拥有相应的引用,或者我错了吗?
I was thinking on creating an Application class thats subclasses the MainActivity and the Service, and then i could have the corresponding references, or am i wrong?
预先感谢
推荐答案
有一些可能性:
- 您的服务可以发送广播( sendBroadcast ),您的活动仅需根据您在服务上实现的方式注册一个broacastReceiver.像这样的东西:
- Your Service can send a brodcast(sendBroadcast) and your activity just need register a broacastReceiver according your implemented on your service. Something like that:
您的服务
Intent intent=new Intent(getApplicationContext(),WebResults.class);
intent.setAction("com.toxy.LOAD_URL");
intent.putExtra("url",uri.toString());
sendBroadcast(intent);
您的活动:
private class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
String url = arg1.getExtras().getString("url");
WebView webview =(WebView)findViewById(R.id.webView);
webview.loadUrl(url);
}
此链接可以帮助您: http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html
第二种方法是在您的服务上注册一个侦听器,并在您的服务上通知该侦听器.
The second way is register a listener on your service and notify that listener on your service.
为您服务:
void onSomethingHappened()
{
activityListener.notifyProgressBar();
}
void subscribe(YourInterface listener)
{
actibityListener = listener;
}
在您的活动中,开始服务后:
In you activity, after start you service:
service.subscribe(this);
但是,要采用更好的解决方案,您应该考虑您的服务实现(类型).
However, to take the better solution you should take into account your service implementation(type).
关于 AndroidService 的链接可能会有用.
This link about AndroidService can be useful.
这篇关于从由BroadcastReceiver启动的服务更新ProgressBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!