Reputation: 6723
I want to create a service, that downloads content from web and I want to show progress dialog while it is executing. I know how to use progress dialog with asynctask and volley, but here I have no idea, now can I be notified on UI thread about service ending when using service.
How can I accomplish this ?
Code is following
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClickStart(View v) {
startService(new Intent(this, MyService.class));
}
public void onClickStop(View v) {
stopService(new Intent(this, MyService.class));
}
}
public class MyService extends Service {
public void onCreate() {
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(LOG_TAG, "onStartCommand");
someTask();
return super.onStartCommand(intent, flags, startId);
}
public void onDestroy() {
super.onDestroy();
}
public IBinder onBind(Intent intent) {
return null;
}
void someTask() {
new Thread(new Runnable() {
public void run() {
for (int i = 1; i<=5; i++) {
Log.d(LOG_TAG, "i = " + i);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stopSelf();
}
}).start();
}
Upvotes: 2
Views: 3844
Reputation: 1366
create broadcast messages when you want to show or hide progress bar from your service:
Intent i = new Intent("yourPackage.SHOW_Progress");
sendBroadcast(i);
then create broadcast receiver and handle received messages:
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
MainActivity mainActivity = ((MyApplication) context.getApplicationContext()).mainActivity;
mainActivity.showProgress();
}
}
and inside your mainActivity create method for show or hide progress bar
Upvotes: 2
Reputation: 1080
There are different ways to communicate between a Service and an Activity.
You could send a Broadcast from the Service and process it in the Activity with a BroadcastReceiver.
Or you could as well bind the Service and send any command back when the service has finished doing its task.
Upvotes: 1