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:com.burntout.burntout.DemoActivity.java

/**
 * Registers the application with GCM servers asynchronously.
 * <p>//from   w w  w  . j  ava  2s .  co  m
 * Stores the registration ID and the app versionCode in the application's
 * shared preferences.
 */
private void registerInBackground() {
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                msg = "Device registered, registration ID=" + regid;

                // You should send the registration ID to your server over HTTP, so it
                // can use GCM/HTTP or CCS to send messages to your app.
                sendRegistrationIdToBackend();

                // For this demo: we don't need to send it because the device will send
                // upstream messages to a server that echo back the message using the
                // 'from' address in the message.

                // Persist the regID - no need to register again.
                storeRegistrationId(context, regid);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
                // If there is an error, don't just keep trying to register.
                // Require the user to click a button again, or perform
                // exponential back-off.
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            mDisplay.append(msg + "\n");
        }
    }.execute(null, null, null);
}

From source file:ca.ualberta.cmput301.t03.user.FriendsListFragment.java

/**
 * Creates a new AlertDialog which can be
 * used to add friends./*from  ww w . j  av a  2s . co m*/
 * <p>
 * The alertDialog contains a single EditText
 * where the user can enter the username to be
 * added.
 *
 * @return the configured AlertDialog
 */
private AlertDialog createAddFriendDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    View dialogContent = View.inflate(getContext(), R.layout.content_add_friend_dialog, null);
    final EditText e = (EditText) dialogContent.findViewById(R.id.addFriendEditText);

    builder.setView(dialogContent); //todo replace with layout
    builder.setCancelable(false);
    builder.setNegativeButton("Cancel", null);
    builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            final String usr = e.getText().toString().trim();

            AsyncTask t = new AsyncTask() {
                @Override
                protected Object doInBackground(Object[] params) {

                    if (usr.equals(""))
                        return null;
                    try {
                        mController.addFriend(usr);
                    } catch (IOException e1) {
                        Snackbar.make(getView(), "There was a problem with the network", Snackbar.LENGTH_SHORT);
                    } catch (UserNotFoundException e2) {
                        Snackbar.make(getView(), String.format("User %s does not exist", usr),
                                Snackbar.LENGTH_SHORT).show();
                    } catch (UserAlreadyAddedException e1) {
                        Snackbar.make(getView(), String.format("User %s is already added!", usr),
                                Snackbar.LENGTH_SHORT).show();
                    } catch (ServiceNotAvailableException e1) {
                        Snackbar.make(getView(), "You must be online to add friends!", Snackbar.LENGTH_SHORT)
                                .show();
                    }
                    return null;
                }
            };
            t.execute();
        }
    });
    builder.setTitle("Add a Friend");
    AlertDialog d = builder.create();
    return d;
}

From source file:ca.ualberta.cmput301.t03.user.ViewProfileFragment.java

/**
 * {@inheritDoc}/*from   www  .  j  a v  a 2s.  co  m*/
 */
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    usernameView = (TextView) getView().findViewById(R.id.viewProfileUsername);
    emailView = (TextView) getView().findViewById(R.id.viewProfileEmail);
    phoneView = (TextView) getView().findViewById(R.id.viewProfilePhone);
    cityView = (TextView) getView().findViewById(R.id.viewProfileCity);
    browseInventoryButton = (Button) getView().findViewById(R.id.inventoryButton);

    AsyncTask<Void, Integer, UserProfile> t = new AsyncTask<Void, Integer, UserProfile>() {
        @Override
        protected UserProfile doInBackground(Void[] params) {
            //TODO is there a better way to do this?
            if (!PrimaryUser.getInstance().equals(mUserToView)) {
                mUserToView = new User(mUserToView.getUsername(), getContext());
            } else {
                mUserToView = PrimaryUser.getInstance();
            }

            try {
                model = mUserToView.getProfile();
            } catch (IOException e) {
                //TODO this is garbage.
                e.printStackTrace();
            } catch (ServiceNotAvailableException e) {
                throw new RuntimeException("App is offline.", e);
            }
            return model;
        }

        @Override
        protected void onPostExecute(UserProfile userProfile) {
            populateFields();
        }
    };
    t.execute();

}

From source file:com.google.plus.wigwamnow.social.GoogleProvider.java

/**
 * Initiate server-side authorization by sending a one time code to the server.
 *//*from  w w w .j  ava2s  .c o  m*/
@Override
public void hybridAuth(final Activity activity) {
    // Check that the activity has a PlusClient
    if (!(activity instanceof PlusClientHostActivity)) {
        throw new IllegalArgumentException("Activity must host a PlusClient!");
    }

    final PlusClientHostActivity clientHost = (PlusClientHostActivity) activity;

    // Create the hybrid authorization resources
    final String clientId = activity.getResources().getString(R.string.plus_client_id);
    final String[] activities = activity.getResources().getStringArray(R.array.visible_activities);
    final String[] scopes = activity.getResources().getStringArray(R.array.plus_scopes);
    final String scopeString = "oauth2:server:client_id:" + clientId + ":api_scope:"
            + TextUtils.join(" ", scopes);

    final Bundle appActivities = new Bundle();
    appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES, TextUtils.join(" ", activities));

    AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {

        final Activity hostActivity = activity;

        @Override
        protected String doInBackground(Void... params) {
            try {
                return GoogleAuthUtil.getToken(hostActivity, clientHost.getPlusClient().getAccountName(),
                        scopeString, appActivities);
            } catch (IOException transientEx) {
                // Network or server error, try later
                Log.e(TAG, transientEx.toString(), transientEx);
                return null;
            } catch (UserRecoverableAuthException e) {
                // Recover (with e.getIntent())
                Log.e(TAG, e.toString(), e);
                Intent recover = e.getIntent();
                hostActivity.startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
            } catch (GoogleAuthException authEx) {
                // The call is not ever expected to succeed and should not be retried.
                Log.e(TAG, authEx.toString(), authEx);
                return null;
            } catch (Exception e) {
                Log.e(TAG, e.toString(), e);
                throw new RuntimeException(e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(String code) {
            Log.d(TAG, "Authorization code retrieved:" + code);
            if (code != null && !mPendingCodeSend) {
                mPendingCodeSend = true;
                initGoogleHybridFlow(code, hostActivity);
            }
        }

    };
    task.execute();

}

From source file:ca.rmen.android.networkmonitor.app.log.LogActionsActivity.java

/**
 * Run the given file export, then bring up the chooser intent to share the exported file.
 */// w  w w.j  a  v a2s . co m
private void shareFile(final FileExport fileExport) {
    Log.v(TAG, "shareFile " + fileExport);
    // Use a horizontal progress bar style if we can show progress of the export.
    String dialogMessage = getString(R.string.export_progress_preparing_export);
    int dialogStyle = fileExport != null ? ProgressDialog.STYLE_HORIZONTAL : ProgressDialog.STYLE_SPINNER;
    DialogFragmentFactory.showProgressDialog(this, dialogMessage, dialogStyle, PROGRESS_DIALOG_TAG);

    AsyncTask<Void, Void, File> asyncTask = new AsyncTask<Void, Void, File>() {

        @Override
        protected File doInBackground(Void... params) {
            File file = null;
            if (fileExport != null) {
                if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
                    return null;
                try {
                    // Export the file in the background.
                    file = fileExport.export();
                } catch (Throwable t) {
                    Log.e(TAG, "Error exporting file " + fileExport + ": " + t.getMessage(), t);
                }
                if (file == null)
                    return null;
            }

            String reportSummary = SummaryExport.getSummary(LogActionsActivity.this);
            // Bring up the chooser to share the file.
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.export_subject_send_log));

            String dateRange = SummaryExport.getDataCollectionDateRange(LogActionsActivity.this);

            String messageBody = getString(R.string.export_message_text, dateRange);
            if (file != null) {
                sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file.getAbsolutePath()));
                sendIntent.setType("message/rfc822");
                messageBody += getString(R.string.export_message_text_file_attached);
            } else {
                sendIntent.setType("text/plain");
            }
            messageBody += reportSummary;
            sendIntent.putExtra(Intent.EXTRA_TEXT, messageBody);

            startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.action_share)));
            return file;
        }

        @Override
        protected void onPostExecute(File result) {
            super.onPostExecute(result);
            DialogFragment fragment = (DialogFragment) getSupportFragmentManager()
                    .findFragmentByTag(PROGRESS_DIALOG_TAG);
            if (fragment != null)
                fragment.dismissAllowingStateLoss();
            // Show a toast if we failed to export a file.
            if (fileExport != null && result == null)
                Toast.makeText(LogActionsActivity.this, R.string.export_error_sdcard_unmounted,
                        Toast.LENGTH_LONG).show();
            finish();
        }

    };
    asyncTask.execute();
}

From source file:ch.christofbuechi.testgcm.MainActivity.java

/**
 * Registers the application with GCM servers asynchronously.
 * <p>//w  w w .  j  a  v  a  2 s.  co  m
 * Stores the registration ID and the app versionCode in the application's
 * shared preferences.
 */
private void registerInBackground() {
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                msg = "Device registered, registration ID=" + regid;

                // You should send the registration ID to your server over HTTP, so it
                // can use GCM/HTTP or CCS to send messages to your app.

                // For this demo: we don't need to send it because the device will send
                // upstream messages to a server that echo back the message using the
                // 'from' address in the message.

                // Persist the regID - no need to register again.
                storeRegistrationId(context, regid);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
                // If there is an error, don't just keep trying to register.
                // Require the user to click a button again, or perform
                // exponential back-off.
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            mDisplay.append(msg + "\n");
        }
    }.execute(null, null, null);
}

From source file:microsoft.aspnet.signalr.client.test.integration.android.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_settings:
        startActivity(new Intent(this, SignalRPreferenceActivity.class));
        return true;

    case R.id.menu_run_tests:
        if (ApplicationContext.getServerUrl().trim().equals("")) {
            startActivity(new Intent(this, SignalRPreferenceActivity.class));
        } else {/*  w w w  .  j av  a2  s.c  o  m*/
            runTests();
        }
        return true;

    case R.id.menu_check_all:
        changeCheckAllTests(true);
        return true;

    case R.id.menu_uncheck_all:
        changeCheckAllTests(false);
        return true;

    case R.id.menu_reset:
        refreshTestGroupsAndLog();
        return true;

    case R.id.menu_view_log:
        AlertDialog.Builder logDialogBuilder = new AlertDialog.Builder(this);
        logDialogBuilder.setTitle("Log");

        final WebView webView = new WebView(this);

        String logContent = TextUtils.htmlEncode(mLog.toString()).replace("\n", "<br />");
        String logHtml = "<html><body><pre>" + logContent + "</pre></body></html>";
        webView.loadData(logHtml, "text/html", "utf-8");

        logDialogBuilder.setPositiveButton("Copy", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                clipboardManager.setText(mLog.toString());
            }
        });

        final String postContent = mLog.toString();

        logDialogBuilder.setNeutralButton("Post data", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        try {
                            String url = ApplicationContext.getLogPostURL();
                            if (url != null && url.trim() != "") {
                                url = url + "?platform=android";
                                HttpPost post = new HttpPost();
                                post.setEntity(new StringEntity(postContent, "utf-8"));

                                post.setURI(new URI(url));

                                new DefaultHttpClient().execute(post);
                            }
                        } catch (Exception e) {
                            // Wasn't able to post the data. Do nothing
                        }

                        return null;
                    }
                }.execute();
            }
        });

        logDialogBuilder.setView(webView);

        logDialogBuilder.create().show();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.google.plus.wigwamnow.social.FacebookProvider.java

/**
 * Create a rental action for the {@link Wigwam} on the Open Graph.
 *//*from w w  w  . j ava  2  s.  com*/
@Override
public boolean rent(Wigwam wigwam, Activity activity) {
    // Write an OpenGraph action to Facebook
    Session session = Session.getActiveSession();

    if (session == null || !session.isOpened()) {
        return false;
    }

    if (!hasPublishPermissions()) {
        // Get user's permission to post OG Actions
        requestPublishPermissions(session, activity);
        return false;
    }

    String postingString = activity.getResources().getString(R.string.posting);
    showProgressDialog(postingString, activity);

    final Wigwam toShare = wigwam;
    final Activity hostActivity = activity;
    AsyncTask<Void, Void, Response> task = new AsyncTask<Void, Void, Response>() {

        @Override
        protected Response doInBackground(Void... params) {
            RentAction rentAction = GraphObject.Factory.create(RentAction.class);
            WigwamGraphObject wigwamObject = GraphObject.Factory.create(WigwamGraphObject.class);
            // Set wigwam URL
            String host = hostActivity.getResources().getString(R.string.external_host);
            String wigwamUrl = host + "/wigwams/" + toShare.getId().toString();
            wigwamObject.setUrl(wigwamUrl);
            // Add wigwam
            rentAction.setWigwam(wigwamObject);
            // Post to OpenGraph
            Request request = new Request(Session.getActiveSession(), RENT_ACTION_PATH, null, HttpMethod.POST);
            request.setGraphObject(rentAction);
            return request.executeAndWait();
        }

        @Override
        protected void onPostExecute(Response response) {
            onPostActionResponse(response, hostActivity);
        }

    };
    task.execute();

    return true;
}

From source file:com.dtz.plugins.azurehubnotification.AzureHubNotification.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected void registerForAzureNotificationHub(final String handle, final CallbackContext callbackContext) {

    final String senderId = AzureConfig.getSenderId(this.cordova.getActivity());
    NotificationsManager.handleNotifications(this.cordova.getActivity(), senderId, NotificationHandler.class);
    gcm = GoogleCloudMessaging.getInstance(this.cordova.getActivity());
    String connectionString = AzureConfig.getEndPoint(this.cordova.getActivity());
    String notificationHubPath = AzureConfig.getNotificationHubPath(this.cordova.getActivity());

    Log.i(TAG, "Configuration data  :senderId : " + senderId + " ,  notificationHubPath :" + notificationHubPath
            + " ,  connectionString : " + connectionString);

    hub = new NotificationHub(notificationHubPath, connectionString, this.cordova.getActivity());
    new AsyncTask() {
        @Override/*from   w ww. j ava2s  . co m*/
        protected Object doInBackground(Object... params) {
            try {
                regid = getRegistrationId(AzureHubNotification.this.cordova.getActivity());
                if (regid.isEmpty()) {
                    hub.unregister();
                    gcm.unregister();
                    regid = gcm.register(senderId);
                    hub.register(regid, handle);
                    Log.i(TAG, "Register for GCM and Azure hub using REG_ID : " + regid);
                } else {
                    Log.i(TAG, "Device is already registered for GCM and Azure hub using REG_ID : " + regid);
                }
                storeRegistrationId(AzureHubNotification.this.cordova.getActivity(), regid);
            } catch (Exception e) {
                Log.e(TAG, "Error in Registering Handle : " + e.getMessage());
                return e;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            Log.i(TAG, "Handle Registered");
            super.onPostExecute(result);
            sendNotificationCallback(callbackContext, "Handle Registered with Server", PluginResult.Status.OK);
        }
    }.execute(null, null, null);
}

From source file:com.genesys.gms.demo.DemoActivity.java

/**
 * Registers the application with GCM servers asynchronously.
 * <p>/*from   ww  w . j  a v a2s. co  m*/
 * Stores the registration ID and the app versionCode in the application's
 * shared preferences.
 */
private void registerInBackground() {
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                msg = "Device registered, registration ID=" + regid;

                // You should send the registration ID to your server over HTTP, so it
                // can use GCM/HTTP or CCS to send messages to your app.
                sendRegistrationIdToBackend(regid);

                // For this demo: we don't need to send it because the device will send
                // upstream messages to a server that echo back the message using the
                // 'from' address in the message.

                // Persist the regID - no need to register again.
                storeRegistrationId(context, regid);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
                // If there is an error, don't just keep trying to register.
                // Require the user to click a button again, or perform
                // exponential back-off.
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            mDisplay.append(msg + "\n");
        }
    }.execute(null, null, null);
}