Example usage for android.os AsyncTask AsyncTask

List of usage examples for android.os AsyncTask AsyncTask

Introduction

In this page you can find the example usage for android.os AsyncTask AsyncTask.

Prototype

public AsyncTask() 

Source Link

Document

Creates a new asynchronous task.

Usage

From source file:net.kayateia.lifestream.UploadService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(LOG_TAG, "UploadService kicked");

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");

    // See CaptureService for comments on this wake lock arrangement.
    boolean needsRelease = true;
    try {/*www.ja va 2 s  . co m*/
        // If we don't release it within the timeout somehow, release it anyway.
        // This may interrupt a long backlog upload or something, but this
        // is really about as long as we can reasonably expect to take.
        Log.v(LOG_TAG, "Acquire wakelock");
        if (wl != null)
            wl.acquire(WAKELOCK_TIMEOUT);
        if (!Network.IsActive(this)) {
            Log.i(LOG_TAG, "No network active, giving up");
            return START_NOT_STICKY;
        }

        // Do the check in a thread.
        new AsyncTask<UploadService, Void, Void>() {
            @Override
            protected Void doInBackground(UploadService... svc) {
                svc[0].checkUploads();
                return null;
            }

            @Override
            protected void onPostExecute(Void foo) {
                Log.v(LOG_TAG, "Release wakelock by worker");
                if (wl != null && wl.isHeld())
                    wl.release();
            }
        }.execute(this);
        needsRelease = false;
    } finally {
        if (needsRelease) {
            Log.v(LOG_TAG, "Release wakelock by default");
            if (wl != null && wl.isHeld())
                wl.release();
        }
    }

    // There's no need to worry about this.. we'll get re-kicked by the alarm.
    return START_NOT_STICKY;
}

From source file:com.deployd.Deployd.java

public static void signup(String username, String displayName, String password,
        final SignupEventHandler signedUp) {
    AsyncTask<JSONObject, JSONObject, JSONObject> query = new AsyncTask<JSONObject, JSONObject, JSONObject>() {

        @Override//from www  .jav a  2s  .c om
        protected JSONObject doInBackground(JSONObject... arg0) {
            // TODO Auto-generated method stub

            try {
                JSONObject result = Deployd.post(arg0[0], "/users/signup");
                return result;
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (result == null) {
                signedUp.failed();
                return;
            }
            DeploydObject jres = new DeploydObject(result);

            signedUp.signupComplete(jres);
        }

    };
    try {
        JSONObject pass = new JSONObject();
        pass.put("username", username);
        pass.put("password", password);
        pass.put("displayName", password);
        query.execute(pass);
    } catch (Exception e) {

    }
}

From source file:ca.rmen.android.networkmonitor.app.about.AboutActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    case R.id.action_send_logs:
        new AsyncTask<Void, Void, Boolean>() {

            @Override/*from w ww  .j ava 2 s.  c  om*/
            protected Boolean doInBackground(Void... params) {
                if (!Log.prepareLogFile()) {
                    return false;
                }
                // Bring up the chooser to share the file.
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                //sendIntent.setData(Uri.fromParts("mailto", getString(R.string.send_logs_to), null));
                sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.support_send_debug_logs_subject));
                String messageBody = getString(R.string.support_send_debug_logs_body);
                File f = new File(getExternalFilesDir(null), Log.FILE);
                sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + f.getAbsolutePath()));
                sendIntent.setType("message/rfc822");
                sendIntent.putExtra(Intent.EXTRA_TEXT, messageBody);
                sendIntent.putExtra(Intent.EXTRA_EMAIL,
                        new String[] { getString(R.string.support_send_debug_logs_to) });
                startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.action_share)));
                return true;
            }

            @Override
            protected void onPostExecute(Boolean result) {
                if (!result)
                    Toast.makeText(AboutActivity.this, R.string.support_error, Toast.LENGTH_LONG).show();
            }

        }.execute();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:net.kayateia.lifestream.StreamService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.v(LOG_TAG, "Kicked");

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");

    // See CaptureService for comments on this wake lock arrangement.
    boolean needsRelease = true;
    try {//from w  ww  .j  a  va  2 s.  co  m
        // If we don't release it within the timeout somehow, release it anyway.
        // This may interrupt a long backlog download or something, but this
        // is really about as long as we can reasonably expect to take.
        Log.v(LOG_TAG, "Acquire wakelock");
        if (wl != null)
            wl.acquire(WAKELOCK_TIMEOUT);

        if (!Network.IsActive(this)) {
            Log.i(LOG_TAG, "No network active, giving up");
            return START_NOT_STICKY;
        }

        // Do the check in a thread.
        new AsyncTask<StreamService, Void, Void>() {
            @Override
            protected Void doInBackground(StreamService... svc) {
                svc[0].checkNewImages();
                return null;
            }

            @Override
            protected void onPostExecute(Void foo) {
                Log.v(LOG_TAG, "Release wakelock by worker");
                if (wl != null && wl.isHeld())
                    wl.release();
            }
        }.execute(this);
        needsRelease = false;
    } finally {
        if (needsRelease) {
            Log.v(LOG_TAG, "Release wakelock by default");
            if (wl != null && wl.isHeld())
                wl.release();
        }
    }

    // There's no need to worry about this.. we'll get re-kicked by the alarm.
    return START_NOT_STICKY;
}

From source file:org.starfishrespect.myconsumption.android.ui.CreateAccountActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_account);

    editTextUsername = (EditText) findViewById(R.id.editTextUsername);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    editTextPassword2 = (EditText) findViewById(R.id.editTextPassword2);
    buttonCreateAccount = (Button) findViewById(R.id.buttonCreateAccount);
    buttonCreateAccount.setOnClickListener(new View.OnClickListener() {
        @Override/*from  w  ww.  jav a2s.  c  om*/
        public void onClick(View v) {
            if (!MiscFunctions.isOnline(CreateAccountActivity.this)) {
                MiscFunctions.makeOfflineDialog(CreateAccountActivity.this).show();
                return;
            }
            if (editTextUsername.getText().toString().equals("")
                    || editTextPassword.getText().toString().equals("")
                    || editTextPassword2.getText().toString().equals("")) {
                Toast.makeText(CreateAccountActivity.this,
                        getString(R.string.dialog_message_error_must_fill_all_fields), Toast.LENGTH_LONG)
                        .show();
                return;
            }

            if (!editTextPassword.getText().toString().equals(editTextPassword2.getText().toString())) {
                Toast.makeText(CreateAccountActivity.this, R.string.dialog_message_error_password_must_match,
                        Toast.LENGTH_LONG).show();
                return;
            }

            new AsyncTask<Void, Void, Integer>() {

                @Override
                protected Integer doInBackground(Void... params) {
                    return createAccount();
                }

                @Override
                protected void onPostExecute(Integer result) {
                    if (result == 0) {
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(CreateAccountActivity.this);
                        builder.setTitle(R.string.dialog_title_error);
                        builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        switch (result) {
                        case SimpleResponseDTO.STATUS_ALREADY_EXISTS:
                            builder.setMessage(R.string.dialog_message_error_user_already_exists);
                            break;
                        default:
                            builder.setMessage("An error has occurred. You might want to "
                                    + "check your internet connection or contact the application provider.");
                            break;

                        }
                        builder.show();
                    }
                }
            }.execute();
        }
    });
}

From source file:at.bitfire.davdroid.mirakel.syncadapter.DavSyncAdapter.java

@Override
public void close() {
    Log.d(TAG, "Closing httpClient");

    // may be called from a GUI thread, so we need an AsyncTask
    new AsyncTask<Void, Void, Void>() {
        @Override/*from   w  w  w.jav a2 s. c  o  m*/
        protected Void doInBackground(Void... params) {
            try {
                httpClientLock.writeLock().lock();
                if (httpClient != null) {
                    httpClient.close();
                    httpClient = null;
                }
                httpClientLock.writeLock().unlock();
            } catch (IOException e) {
                Log.w(TAG, "Couldn't close HTTP client", e);
            }
            return null;
        }
    }.execute();
}

From source file:com.limewoodmedia.nsdroid.NationInfo.java

public void setName(final String name) {
    if (this.name != name) {
        this.name = name;
        if (name != null) {
            saveString("nation_name", name);
        }//from w w w. j a v  a2 s.c o  m
        new AsyncTask<String, Void, Void>() {
            @Override
            protected Void doInBackground(String... params) {
                // Log out
                API.getInstance(context).logout();
                if (name != null) {
                    // Add to database
                    if (params[0] != null) {
                        NationsDatabase.getInstance(context).addNation(params[0]);
                    }
                }
                return null;
            }
        }.execute(name);
    }
}

From source file:net.gromgull.android.bibsonomyposter.BibsonomyPosterActivity.java

/** Called with the activity is first created. */
@Override/*from   w w w  .  j  a v  a2  s  .  c om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    load();

    Intent intent = getIntent();
    String action = intent.getAction();
    if (action.equalsIgnoreCase(Intent.ACTION_SEND)) {
        final String uri = intent.getStringExtra(Intent.EXTRA_TEXT);
        final String title = intent.getStringExtra(Intent.EXTRA_SUBJECT);

        final Context context = getApplicationContext();

        new AsyncTask<Void, Integer, Boolean>() {

            @Override
            protected Boolean doInBackground(Void... v) {
                try {
                    bookmark(uri, title);
                    return true;
                } catch (Exception e) {
                    Log.w(LOGTAG, "Could not bookmark: " + title + " / " + uri, e);
                    return false;
                }
            }

            protected void onPostExecute(Boolean result) {
                if (result) {
                    Toast toast = Toast.makeText(context, "Bookmarked " + title, Toast.LENGTH_SHORT);
                    toast.show();
                } else {
                    Toast toast = Toast.makeText(context, "Error bookmarking " + title, Toast.LENGTH_SHORT);
                    toast.show();
                }
            }

        }.execute();

        finish();
        return;
    }

    // Inflate our UI from its XML layout description.
    setContentView(R.layout.bibsonomyposter_activity);

    if (username != null)
        ((EditText) findViewById(R.id.username)).setText(username);
    if (apikey != null)
        ((EditText) findViewById(R.id.apikey)).setText(apikey);

    // Hook up button presses to the appropriate event handler.
    ((Button) findViewById(R.id.save)).setOnClickListener(mSaveListener);

}

From source file:nl.timmevandermeer.carglass.LocationActivity.java

/**
 * Load the map asynchronously and populate the ImageView when it's loaded.
 *//*www. j a va 2  s  .  com*/
private void loadMap(double latitude, double longitude, int zoom) {
    String url = makeStaticMapsUrl(52.001783, 4.368871, 10);
    new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... urls) {
            try {
                HttpResponse response = new DefaultHttpClient().execute(new HttpGet(urls[0]));
                InputStream is = response.getEntity().getContent();
                return BitmapFactory.decodeStream(is);
            } catch (Exception e) {
                Log.e(TAG, "Failed to load image", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                mMapView.setImageBitmap(bitmap);
            }
        }
    }.execute(url);
}

From source file:com.wso2.mobile.mdm.services.WSO2DeviceAdminReceiver.java

public void startUnRegistration(Context app_context) {
    final Context context = app_context;
    mRegisterTask = new AsyncTask<Void, Void, Void>() {

        @Override// ww  w. j  a v  a  2 s  .co m
        protected Void doInBackground(Void... params) {
            Map<String, String> paramss = new HashMap<String, String>();
            paramss.put("regid", regId);
            //ServerUtilities.sendToServer(context, "/UNRegister", paramss);
            unregState = ServerUtilities.unregister(regId, context);
            return null;
        }

        //ProgressDialog progressDialog;
        //declare other objects as per your need
        @Override
        protected void onPreExecute() {
            //progressDialog= ProgressDialog.show(context, "Unregistering Device","Please wait", true);

            //do initialization of required objects objects here                
        };

        @Override
        protected void onPostExecute(Void result) {
            try {
                SharedPreferences mainPref = context.getSharedPreferences(
                        context.getResources().getString(R.string.shared_pref_package), Context.MODE_PRIVATE);
                Editor editor = mainPref.edit();
                editor.putString(context.getResources().getString(R.string.shared_pref_policy), "");
                editor.putString(context.getResources().getString(R.string.shared_pref_isagreed), "0");
                editor.putString(context.getResources().getString(R.string.shared_pref_regId), "");
                editor.putString(context.getResources().getString(R.string.shared_pref_registered), "0");
                editor.putString(context.getResources().getString(R.string.shared_pref_ip), "");
                editor.putString(context.getResources().getString(R.string.shared_pref_sender_id), "");
                editor.putString(context.getResources().getString(R.string.shared_pref_eula), "");

                editor.commit();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mRegisterTask = null;
            //progressDialog.dismiss();
        }

    };
    mRegisterTask.execute(null, null, null);

}