user265889 user265889 - 2 months ago 16
Android Question

Android Thread Issues

I'm having some problems running a thread in my android application, It should show a dialog asking the user something and if the user clicks yes, a loading dialog should appear while it's doing something in the background, I created a thread but when I click the yes button, the UI still locks up until the process is done.

Code:
Dialog:

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

builder.setMessage("LOGO.bin Was Not Found, Would You Like To Extract It?")
.setTitle("LOGO Not Found!");

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {

getAndExtract();


}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
System.exit(0);
}
});


AlertDialog dialog = builder.create();
dialog.show();


getAndExtract:

public void getAndExtract()
{

new Thread(new Runnable() {
@Override
public void run() {
try {
showLoad("Grabbing Logo...");

getLogo();
Thread.sleep(2000);
progressDialog.cancel();

showLoad("Extracting Images...");
extractImages();
Thread.sleep(2000);
progressDialog.cancel();
}catch (InterruptedException iE)
{
iE.printStackTrace();
}
}
}).run();




}


showLoad:

progressDialog.setMessage(msg);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();


basics of extractImages:

Command cmd = new Command(0, "LogoInjector -i " + getFilesDir() + "/LOGO.bin -d -g " + getFilesDir() + "/");

RootTools.getShell(true).add(cmd);


basics of getLogo:

Command cmd = new Command(0, "dd if=/dev/block/mmcblk0p" + partitionIndex + " of=" + getFilesDir() + "/LOGO.bin");

RootTools.getShell(true).add(cmd);


I also tried putting showLoad in runOnUiThread but there was no change... if I remove progressDialog.cancel(); it does show the loading dialog but after the extract is already complete. I press Yes and it just hangs until getLogo() and extractImages() both completed

Can anyone help me find out why this isn't working?

Thanks!

Answer

Try using AsyncTask:

    final AsyncTask<Void,Void,Void> asyncTask = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {

            // do whatever you need to do in background

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute( aVoid);

            // do after finished 
        }
    };
    asyncTask.execute();

Hope that helps =]