问题
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:
- 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