我想创建一个服务,该服务从Web下载内容,并且要在执行过程中显示进度对话框。我知道如何在asynctask和volley中使用进度对话框,但是在这里我不知道,现在可以在使用服务时在UI线程上收到有关服务结束的通知。
我怎样才能做到这一点?
代码如下
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();
}
要在服务中显示或隐藏进度栏时创建广播消息:
Intent i = new Intent("yourPackage.SHOW_Progress");
sendBroadcast(i);
然后创建广播接收器并处理收到的消息:
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
MainActivity mainActivity = ((MyApplication) context.getApplicationContext()).mainActivity;
mainActivity.showProgress();
}
}
并在您的mainActivity创建方法中显示或隐藏进度条
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句