Update ProgressBar from a Service started by a BroadcastReceiver

大憨熊 提交于 2019-12-13 04:16:47

问题


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?

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?

Thanks in advance


回答1:


There are some possibilites:

  1. Your Service can send a brodcast(sendBroadcast) and your activity just need register a broacastReceiver according your implemented on your service. Something like that:

Your service:

 Intent intent=new Intent(getApplicationContext(),WebResults.class);
 intent.setAction("com.toxy.LOAD_URL");
 intent.putExtra("url",uri.toString());
 sendBroadcast(intent);

Your Activity:

 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);
 }

This link can helo you : 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.

In 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).

This link about AndroidService can be useful.



来源:https://stackoverflow.com/questions/15057565/update-progressbar-from-a-service-started-by-a-broadcastreceiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!