在我的应用程序中,我有一个服务类,它具有在执行某些操作时显示进度对话框的方法:
private void openprogresdialog() {
new AsyncTask<Integer, Integer, Boolean>()
{
ProgressDialog progressDialog;
@Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(thisActivity, "Dialog","Loading...");
}
@Override
protected Boolean doInBackground(Integer... params)
{
if (params == null)
{
return false;
}
try
{
Thread.sleep(params[0]);
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
return false;
}
return true;
}
@Override
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
AlertDialog.Builder b = new AlertDialog.Builder(thisActivity);
b.setTitle(android.R.string.dialog_alert_title);
if (result)
{
b.setMessage("Download succeeded");
}
else
{
b.setMessage("Download failed");
}
b.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int arg1)
{
dlg.dismiss();
}
});
b.create().show();
}
}.execute(2000);
new Thread()
{
@Override
public void run()
{
DialogInterface progressDialog = null;
progressDialog.dismiss();
}
}.start();
}
我希望在应用程序执行时会显示工作进度对话框,但是当我运行应用程序时出现此错误:
无法在尚未调用的线程内创建处理程序Looper.prepare()
我该如何解决?
编辑 :
public class MyService extends Service {
private static final String TAG = "MyService";
Thread readthread;
final MyService thisActivity = this;
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final ParentActivityData data = intent.getParcelableExtra("DATA");
readthread = new Thread(new Runnable() {
public void run() {
// SOME CODE TO EXECUTE //
}
openprogresdialog();
}
});
readthread.start();
Log.d(TAG, "onCreate");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
}
@Override
public void onDestroy() {
}
}