Domanda

Ho un metodo public void writeEntry(Activity ctx, Entry entry) che ottengono alcuni dati e devono chiamare un metodo nativo, che richiede più tempo per finire.
Quindi ho creato un Asynctask che gestisce il ProgressDialog e il metodo nativo. Funziona alla grande in un proprio Attività per testarlo, in questo Attività Ho usato un'interfaccia di callback e così via.

Nel mio caso ho il metodo sopra descritto e devo eseguire il Asynctask. L'esecuzione non può essere in quel metodo perché non ferma l'ulteriore esecuzione.
Ho bisogno del risultato dal metodo nativo prima di poter continuare con l'esecuzione.
C'è qualche possibilità di aspettare il Asynctask finché non è finito? Il metodo wait() non è un'opzione perché anche il thread dell'interfaccia utente aspetterà e quindi il senso di a ProgressDialog saranno persi.

Posso usare il metodo runOnUiThread() dai parametri indicati o è l'unica soluzione per avviare una propria Attività?

È stato utile?

Soluzione 2

La mia prima soluzione è stata quella di utilizzare i metodi di callback con un'implementazione dell'interfaccia vedere l'esempio https://stackoverflow.com/a/6396376/390177.

Dopo aver chattato un po 'nella chat Android ho sentito che esiste una soluzione più praticabile.
Puoi usare un Intenservice in combinazione con a In pendenza.
La comunicazione è realizzata con Intenzione'S.
Se vuoi usare un file ProgressDialog, hai bisogno di un proprio Attività per questo, che si registra ad esempio a Broadcastreciever e il Intenservice lo invia lo stato effettivo per trasmissione.

Ma iniziamo ora.
Per prima cosa creiamo il Attività, che contiene il ProgressDialog e un registrato Broadcastreceiver. Il Broadcastreceiver Ascolta i messaggi sull'aggiornamento e sulla finitura della finestra di dialogo.

Per il Attività Abbiamo bisogno del layout ...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="#80000000">
</LinearLayout>

... e il codice correlato:

public class ProgressActivity extends Activity {
    /**
     * ProgressDialog which is shown
     */
    private ProgressDialog progessDialog_g;

    /**
     * Instance of the BroadcastReceiver
     */
    private BroadcastReceiver receiver_g;

    /**
     * Identifier for the different settings of the ProgressDialog
     */
    public static final String PROGRESS_DIALOG_BOOL_HORIZONTAL_BAR = "pbar_horizontal_bar";
    public static final String PROGRESS_DIALOG_BOOL_CANCELABLE = "pbar_horizontal_cancelable";
    public static final String PROGRESS_DIALOG_STR_MESSAGE = "pbar_message";
    public static final String PROGRESS_DIALOG_INT_MAX = "pbar_max_bar";
    public static final String PROGRESS_DIALOG_INT_VALUE = "pbar_value";
    protected static final int PROGRESS_DIALOG_INT_MAX_VALUE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        setContentView(R.layout.progress);

        progessDialog_g = new ProgressDialog(this);

        // Reads and sets the settings for the ProgressDialog
        Intent i = getIntent();
        progessDialog_g.setCancelable(i.getBooleanExtra(
                PROGRESS_DIALOG_BOOL_CANCELABLE, false));
        if (i.getBooleanExtra(
                PROGRESS_DIALOG_BOOL_HORIZONTAL_BAR, false)) {
            progessDialog_g.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        } else {
            progessDialog_g.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }
        progessDialog_g
                .setMessage(i
                        .getStringExtra(PROGRESS_DIALOG_STR_MESSAGE));
        progessDialog_g.setMax(i.getIntExtra(
                PROGRESS_DIALOG_INT_MAX, 100));

        // Create the IntentFilter for the different broadcast messages
        IntentFilter iFilter =
                new IntentFilter(
                        ExampleProgressService.PROGRESS_DIALOG_BROADCAST_INIT);
        iFilter.addAction(ExampleProgressService.PROGRESS_DIALOG_BROADCAST_UPDATE);
        iFilter.addAction(ExampleProgressService.PROGRESS_DIALOG_BROADCAST_FINISH);

        // Creates the BroadcastReceiver
        receiver_g = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent){
                Log.d(DefaultPreferences.DEBUG_PREFIX + "ProgressActivity",
                        intent.getAction());

                if (ExampleProgressService.PROGRESS_DIALOG_BROADCAST_INIT
                        .equals(intent.getAction())) {
                    // Sets the ProgressDialog style
                    if (intent
                            .getBooleanExtra(
                                    PROGRESS_DIALOG_BOOL_HORIZONTAL_BAR,
                                    false)) {
                        progessDialog_g
                                .setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    } else {
                        progessDialog_g
                                .setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    }

                    // Shows the ProgressDialog    
                    progessDialog_g.show();
                } else if (ExampleProgressService.PROGRESS_DIALOG_BROADCAST_UPDATE
                        .equals(intent.getAction())) {
                    // Updates the ProgressDialog
                    int value =
                            intent.getIntExtra(
                                    PROGRESS_DIALOG_INT_VALUE,
                                    -1);
                    if (value != -1) {
                        progessDialog_g.setProgress(value);
                    }
                } else if (ExampleProgressService.PROGRESS_DIALOG_BROADCAST_FINISH
                        .equals(intent.getAction())) {
                    // Finishs the ProgressDialog
                    progessDialog_g.cancel();
                    finish();
                }
            }
        };

        // Registers the BroadcastReceiver
        registerReceiver(receiver_g, iFilter);
    }

    @Override
    protected void onDestroy(){
        unregisterReceiver(receiver_g);
        super.onDestroy();
    }
}

Ora vogliamo usare il Attività, quindi iniziamo chiamandolo:

final Intent i = new Intent(parentActivity, <packages>.ProgressActivity);
i.putExtra(ProgressActivity.PROGRESS_DIALOG_BOOL_CANCELABLE, cancelable_g);
i.putExtra(ProgressActivity.PROGRESS_DIALOG_BOOL_HORIZONTAL_BAR, showProgress_g);
i.putExtra(ProgressActivity.PROGRESS_DIALOG_STR_MESSAGE, message_g);
i.putExtra(ProgressActivity.PROGRESS_DIALOG_INT_MAX, ProgressActivity.PROGRESS_DIALOG_INT_MAX_VALUE);

parentActivity.startActivity(i);

Quindi abbiamo una progrettività in esecuzione, che attende diverse trasmissioni. Ma prima abbiamo bisogno del Intenservice, che invia le trasmissioni.
Quindi andiamo:

public class ExampleProgressService extends IntentService {
    /**
     * PendingIntent for callback.
     */
    protected PendingIntent pi_g = null;

    private static final String DEBUG_TAG = "ExampleProgressService";

    /**
     * Message identifier for ProgressDialog init
     */
    public static final String PROGRESS_DIALOG_BROADCAST_INIT = "Dialog.Progress.Init";
    /**
     * Message identifier for ProgressDialog finish
     */
    public static final String PROGRESS_DIALOG_BROADCAST_FINISH = "Dialog.Progress.Finish";
    /**
     * Message identifier for ProgressDialog update
     */
    public static final String PROGRESS_DIALOG_BROADCAST_UPDATE = "Dialog.Progress.Update";

    /**
     * Identifier of the result for intent content
     */
    public static final String PROGRESS_DATA_RESULT = "Result";
    /**
     * Identifier of the result error for intent content
     */
    public static final String PROGRESS_DATA_RESULT_ERROR_MESSAGE = "Result.Error.Message";
    /**
     * Identifier of the result error exception for intent content
     */
    public static final String PROGRESS_DATA_RESULT_ERROR_EXCEPTION = "Result.Error.Exception";
    /**
     * Identifier of the result status for intent content
     */
    public static final String PROGRESS_DATA_RESULT_STATUS_BOOL = "Result.Status.boolean";

    /**
     * Identifier of the pending intent for intent content
     */
    public static final String PROGRESS_DATA_PENDING_RESULT = "PendingResult";

    public ExampleProgressService() {
        super("ExampleProgressService");
    }

    /**
     * Send the finish message.
     */
    private void closeProgressActivity() {
        Intent intent = new Intent(PROGRESS_DIALOG_BROADCAST_FINISH);

        sendBroadcast(intent);
    }

    /**
     * Do some magic with the intent content
     */
    private void extractVariablesFromIntentAndPrepare(Intent intent)
            throws Exception {
        pi_g = (PendingIntent) intent
                .getParcelableExtra(PROGRESS_DATA_PENDING_RESULT);

        if (pi_g == null) {
            throw new Exception("There is no pending intent!");
    }

    /**
     * Sends an error message.
     */
    private void failed(Exception e, String message) {
        Intent i = new Intent();
        i.putExtra(PROGRESS_DATA_RESULT_ERROR_EXCEPTION, e);
        i.putExtra(PROGRESS_DATA_RESULT_ERROR_MESSAGE, message);

        send(i, false);
    }

    /**
     * Sends the init message.
     */
    private void initProgressActivity() {
        Intent intent = new Intent(PROGRESS_DIALOG_BROADCAST_INIT);

        intent.putExtra(PROGRESS_DIALOG_BOOL_HORIZONTAL_BAR,
                multipart_g);

        sendBroadcast(intent);
    }

    /**
     * (non-Javadoc)
     * 
     * @see android.app.IntentService#onHandleIntent(android.content.Intent)
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        extractVariablesFromIntentAndPrepare(intent);

        initProgressActivity();

        // do your calculation here and implements following code
        Intent intent = new Intent(PROGRESS_DIALOG_BROADCAST_UPDATE);

        intent.putExtra(PROGRESS_DIALOG_INT_VALUE, progressValue);

        sendBroadcast(intent);

        // If you finished, use one of the two methods to send the result or an error
        success(result);
        failed(exception, optionalMessage);
    }

    /**
     * Sends the data to the calling Activity
     */
    private void send(Intent resultData, boolean status) {
        resultData.putExtra(PROGRESS_DATA_RESULT_STATUS_BOOL, status);

        closeProgressActivity();

        try {
            pi_g.send(this, Activity.RESULT_OK, resultData);
        } catch (PendingIntent.CanceledException e) {
            Log.e(DEBUG_TAG,
                    "There is something wrong with the pending intent", e);
        }
    }

    /**
     * Sends the result message.
     */
    private void success(String result) {
        Intent i = new Intent();
        i.putExtra(PROGRESS_DATA_RESULT, result);

        send(i, true);
    }
}

Il risultato del progresso del calcolo deve essere disponibile in genitorialità, quindi creiamo il In pendenza In ciò Attività e chiama il Intenservice.

// Some identifier for the call
int requestCode = 12345;

final Intent sI = new Intent(ExampleProgressService.PROGRESS_SERVICE_ACTION);

// Callback
sI.putExtra(ExampleProgressService.PROGRESS_DATA_PENDING_RESULT, parentActivity
        .createPendingResult(requestCode, null,
                PendingIntent.FLAG_CANCEL_CURRENT));

// Service start
parentActivity.startService(sI);

Per ricevere i risultati, dobbiamo sovrascrivere il metodo onActivityResult(int requestCode, int resultCode, Intent data).

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    // Compares the requestCode with the requestCode from above
    if (requestCode == ...) {
        if (data.getBooleanExtra(ExampleProgressService.PROGRESS_DATA_RESULT_STATUS_BOOL, false)) {
            // Calculation was success
            data.getStringExtra(ExampleProgressService.PROGRESS_DATA_RESULT);
        } else
        {
            // Calculation is failed
            data.getStringExtra(ExampleProgressService.PROGRESS_DATA_RESULT_ERROR_MESSAGE);
            ((Exception) data.getSerializableExtra(ExampleProgressService.PROGRESS_DATA_RESULT_ERROR_EXCEPTION));
        }
    }
}

Questa è stata la magia, spero che ti aiuti.

Altri suggerimenti

Quindi cercherò di spiegare il più possibile

Inizia il tuo processo pesante all'interno di un asyncTask, ma qualunque codice desideri eseguire dopo il completamento di AsyncTask lo metti in un metodo pubblico separato. Ora, una volta terminato con il tuo pesante Call Call, quel metodo creato separatamente in onPostExecute().

Quindi il codice psuuedo sembrerà così,

class main extends Activity {

    class Something extends AsyncTask<String, Integer, String> {

        protected void onPreExecute() {
            // Start your progress bar...
        }

        protected String doInBackground(String... params) {
            // Do your heavy stuff...
            return null;
        }

        protected void onPostExecute(String result) {
            // close your progress dialog and than call method which has
            // code you are wishing to execute after AsyncTask.
        }
    }

}

Spero che questo possa aiutare,

Buona fortuna!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top