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.tt.jobtracker.MainActivity.java

private void registerInBackground() {
    new AsyncTask<Void, Void, String>() {
        @Override//from ww w  .  j a v a 2s .  c  o  m
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(Shared.GCM_SENDER_ID);
                msg = "Device registered, registration ID=" + regid;
                Shared.LoggedInUser.GcmRegID = regid;
                //sendRegistrationIdToBackend(regid, Shared.LoggedInUser.ID);

                storeRegistrationId(context, regid, Shared.LoggedInUser.ID);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {

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

From source file:mobile.tiis.appv2.LoginActivity.java

private void sendRegistrationIdToBackend() {
    final Context context = this;
    mRegisterTask = new AsyncTask<Void, Void, Void>() {
        @Override//from  w w w. ja  v  a  2s .c  om
        protected Void doInBackground(Void... params) {
            /**
             * Register on our server
             * On server creates a new user
             */
            ServerUtilities.register(context, regId);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            mRegisterTask = null;
            Log.d(TAG, "The appv2 has been registered on ADR Hakiki dawa Server");
        }
    };
    mRegisterTask.execute();
}

From source file:com.google.android.apps.santatracker.doodles.shared.HistoryManager.java

/**
 * Loads the history object from file.  Then merges with any changes that might have occured while
 * we waited for it to load./*from w  w  w .ja v a  2 s  .  c om*/
 */
private void load() {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                File file = new File(context.getFilesDir(), FILENAME);
                int length = (int) file.length();
                if (length <= 0) {
                    history = new JSONObject();
                    return null;
                }

                byte[] bytes = new byte[length];
                FileInputStream inputStream = new FileInputStream(file);
                inputStream.read(bytes);
                inputStream.close();

                history = new JSONObject(new String(bytes, "UTF-8"));
                Log.i(TAG, "Loaded: " + history);
            } catch (JSONException e) {
                Log.w(TAG, "Couldn't create JSON for: " + FILENAME);
            } catch (UnsupportedEncodingException e) {
                Log.d(TAG, "Couldn't decode: " + FILENAME);
            } catch (IOException e) {
                Log.w(TAG, "Couldn't read history: " + FILENAME);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if (listener != null) {
                listener.onFinishedLoading();
            }
        }
    }.execute();
}

From source file:br.com.arlsoft.pushclient.PushClientModule.java

@Kroll.method
public void unregisterPush() {
    new AsyncTask<Void, Void, String>() {
        @Override/*from w w  w .  j av a  2  s. c om*/
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                gcm.unregister();
                registrationId = "";
                TiApplication appContext = TiApplication.getInstance();
                appContext.getAppProperties().removeProperty(PROPERTY_REG_ID);
            } catch (IOException ex) {
                msg = ex.getMessage();
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            if (!msg.isEmpty()) {
                sendError(ERROR_UNREGISTER, msg);
            }
        }
    }.execute(null, null, null);
}

From source file:com.github.jimcoven.nodeauth.GoogleLoginManager.java

/**
* JSON WEB TOKEN - for identification. This is sufficient for server login purposes
*///  ww  w  . j  a  v a 2  s  .co m
public void requestIdentityToken() {
    if (mGoogleApiClient.isConnected() && configuration != null && configuration.WEB_CLIENT_ID != null) {

        final String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
        final String scope = configuration.getIdentityTokenScope();

        AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                try {
                    return GoogleAuthUtil.getToken(mContext, email, scope);
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage());
                }
                return null;
            }

            @Override
            protected void onPostExecute(String token) {
                mConnectionListener.onIdentityToken(token != null, token);
            }
        };
        task.execute();
    }
}

From source file:net.kourlas.voipms_sms.Notifications.java

/**
 * Enable SMS notifications by configuring the VoIP.ms URL callback, registering for GCM and making the appropriate
 * changes to the application preferences.
 *
 * @param activity The source activity./* ww  w . java  2  s. c o  m*/
 */
public void enableNotifications(final Activity activity) {
    if (preferences.getEmail().equals("") || preferences.getPassword().equals("")
            || preferences.getDid().equals("")) {
        Utils.showInfoDialog(activity,
                applicationContext.getString(R.string.notifications_callback_username_password_did));
        return;
    }

    final ProgressDialog progressDialog = new ProgressDialog(activity);
    progressDialog.setMessage(activity.getString(R.string.notifications_callback_progress));
    progressDialog.setCancelable(false);
    progressDialog.show();

    new AsyncTask<Boolean, Void, Boolean>() {
        @Override
        protected Boolean doInBackground(Boolean... params) {
            try {
                String url = "https://www.voip.ms/api/v1/rest.php?" + "api_username="
                        + URLEncoder.encode(preferences.getEmail(), "UTF-8") + "&" + "api_password="
                        + URLEncoder.encode(preferences.getPassword(), "UTF-8") + "&" + "method=setSMS" + "&"
                        + "did=" + URLEncoder.encode(preferences.getDid(), "UTF-8") + "&" + "enable=1" + "&"
                        + "url_callback_enable=1" + "&" + "url_callback=" + URLEncoder
                                .encode("http://voipmssms-kourlas.rhcloud.com/sms_callback?did={TO}", "UTF-8")
                        + "&" + "url_callback_retry=0";

                JSONObject result = Utils.getJson(url);
                String status = result.optString("status");
                return !(status == null || !status.equals("success"));
            } catch (Exception ex) {
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean success) {
            progressDialog.hide();

            DialogInterface.OnClickListener gcmOnClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    gcm.registerForGcm(activity, true, true);
                }
            };

            if (!success) {
                Utils.showAlertDialog(activity, null,
                        applicationContext.getString(R.string.notifications_callback_fail),
                        applicationContext.getString(R.string.ok), gcmOnClickListener, null, null);
            } else {
                Utils.showAlertDialog(activity, null,
                        applicationContext.getString(R.string.notifications_callback_success),
                        applicationContext.getString(R.string.ok), gcmOnClickListener, null, null);
            }
        }
    }.execute();
}

From source file:fr.mdk.kisspush.KISSPush.java

/**
 * Registers the application with GCM servers asynchronously.
 * <p>//from  w w  w.  j  a v a  2  s  . c om
 * Stores the registration ID and the app versionCode in the application's
 * shared preferences.
 */
private void registerInBackground() {
    final KISSPush self = this;
    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;
                self.onRegIdAvailable(regid);
                storeRegistrationId(context, regid);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
                // If there is an error, don't just keep trying to register.
                // Require the useor other views support the
                // swipe-to-dismissr to click a button again, or perform
                // exponential back-off.
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
        }
    }.execute(null, null, null);
}

From source file:com.xirvik.transdroid.preferences.PreferencesXirvikServer.java

private void updateScgiMountFolder() {
    if (typeValue != null && XirvikServerType.fromCode(typeValue) == XirvikServerType.SharedRtorrent) {
        new AsyncTask<Void, Void, String>() {
            @Override//  w  w w  . j  a v  a2  s . co  m
            protected String doInBackground(Void... params) {
                try {
                    // Get, from the server, the RPC SCGI mount address
                    DefaultHttpClient httpclient = HttpHelper.createStandardHttpClient(true, userValue,
                            passValue, true, null, HttpHelper.DEFAULT_CONNECTION_TIMEOUT, serverValue, 443);
                    String url = "https://" + serverValue + ":443/browsers_addons/transdroid_autoconf.txt";
                    HttpResponse request = httpclient.execute(new HttpGet(url));
                    InputStream stream = request.getEntity().getContent();
                    String folderVal = HttpHelper.ConvertStreamToString(stream).trim();
                    if (folderVal.startsWith("<?xml")) {
                        folderVal = null;
                    }
                    stream.close();
                    return folderVal;
                } catch (DaemonException e) {
                } catch (ClientProtocolException e) {
                } catch (IOException e) {
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                storeScgiMountFolder(result);
            }
        }.execute();
    } else {
        // No need to retrieve this value
        storeScgiMountFolder(XirvikSettings.RTORRENT_FOLDER);
    }
}

From source file:com.teinproductions.tein.papyrosprogress.UpdateCheckReceiver.java

private void checkBlog() {
    // The amount of blog posts that were found when last checked
    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
    final int cachePostAmount = pref.getInt(Constants.CACHED_BLOG_AMOUNT, -1);

    // Load the GitHub API page containing information about the amount of blog posts
    new AsyncTask<Void, Void, Integer>() {
        @Override// ww w  .j a  va2 s.  c  om
        protected Integer doInBackground(Void... params) {
            try {
                MilestoneLoader.Result file = IOUtils.loadPage(Constants.PAPYROS_BLOG_API_URL);
                if (file.getError() != MilestoneLoader.Result.NO_ERROR)
                    return null;
                return new JSONArray(file.getStrData()).length();
            } catch (Exception e) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(Integer newPostAmount) {
            try {
                // If there was a cachePostAmount present in storage, compare it to the new amount
                if (cachePostAmount != -1 && newPostAmount > cachePostAmount) {
                    // A blog post has been added
                    issueBlogNotification(UpdateCheckReceiver.this.context);
                }

                pref.edit().putInt(Constants.CACHED_BLOG_AMOUNT, newPostAmount).apply();
            } catch (Exception ignored) {
            }
        }
    }.execute();
}

From source file:android_network.hetnet.vpn_service.AdapterLog.java

@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
    // Get values
    final long id = cursor.getLong(colID);
    long time = cursor.getLong(colTime);
    int version = (cursor.isNull(colVersion) ? -1 : cursor.getInt(colVersion));
    int protocol = (cursor.isNull(colProtocol) ? -1 : cursor.getInt(colProtocol));
    String flags = cursor.getString(colFlags);
    String saddr = cursor.getString(colSAddr);
    int sport = (cursor.isNull(colSPort) ? -1 : cursor.getInt(colSPort));
    String daddr = cursor.getString(colDAddr);
    int dport = (cursor.isNull(colDPort) ? -1 : cursor.getInt(colDPort));
    String dname = (cursor.isNull(colDName) ? null : cursor.getString(colDName));
    int uid = (cursor.isNull(colUid) ? -1 : cursor.getInt(colUid));
    String data = cursor.getString(colData);
    int allowed = (cursor.isNull(colAllowed) ? -1 : cursor.getInt(colAllowed));
    int connection = (cursor.isNull(colConnection) ? -1 : cursor.getInt(colConnection));
    int interactive = (cursor.isNull(colInteractive) ? -1 : cursor.getInt(colInteractive));

    // Get views/*from w  w  w.  j av  a  2 s  . c o  m*/
    TextView tvTime = (TextView) view.findViewById(R.id.tvTime);
    TextView tvProtocol = (TextView) view.findViewById(R.id.tvProtocol);
    TextView tvFlags = (TextView) view.findViewById(R.id.tvFlags);
    TextView tvSAddr = (TextView) view.findViewById(R.id.tvSAddr);
    TextView tvSPort = (TextView) view.findViewById(R.id.tvSPort);
    final TextView tvDaddr = (TextView) view.findViewById(R.id.tvDAddr);
    TextView tvDPort = (TextView) view.findViewById(R.id.tvDPort);
    final TextView tvOrganization = (TextView) view.findViewById(R.id.tvOrganization);
    ImageView ivIcon = (ImageView) view.findViewById(R.id.ivIcon);
    TextView tvUid = (TextView) view.findViewById(R.id.tvUid);
    TextView tvData = (TextView) view.findViewById(R.id.tvData);
    ImageView ivConnection = (ImageView) view.findViewById(R.id.ivConnection);
    ImageView ivInteractive = (ImageView) view.findViewById(R.id.ivInteractive);

    // Show time
    tvTime.setText(new SimpleDateFormat("HH:mm:ss").format(time));

    // Show connection type
    if (connection <= 0)
        ivConnection.setImageResource(allowed > 0 ? R.drawable.host_allowed : R.drawable.host_blocked);
    else {
        if (allowed > 0)
            ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_on : R.drawable.other_on);
        else
            ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_off : R.drawable.other_off);
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(ivConnection.getDrawable());
        DrawableCompat.setTint(wrap, allowed > 0 ? colorOn : colorOff);
    }

    // Show if screen on
    if (interactive <= 0)
        ivInteractive.setImageDrawable(null);
    else {
        ivInteractive.setImageResource(R.drawable.screen_on);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            Drawable wrap = DrawableCompat.wrap(ivInteractive.getDrawable());
            DrawableCompat.setTint(wrap, colorOn);
        }
    }

    // Show protocol name
    tvProtocol.setText(Util.getProtocolName(protocol, version, false));

    // SHow TCP flags
    tvFlags.setText(flags);
    tvFlags.setVisibility(TextUtils.isEmpty(flags) ? View.GONE : View.VISIBLE);

    // Show source and destination port
    if (protocol == 6 || protocol == 17) {
        tvSPort.setText(sport < 0 ? "" : getKnownPort(sport));
        tvDPort.setText(dport < 0 ? "" : getKnownPort(dport));
    } else {
        tvSPort.setText(sport < 0 ? "" : Integer.toString(sport));
        tvDPort.setText(dport < 0 ? "" : Integer.toString(dport));
    }

    // Application icon
    ApplicationInfo info = null;
    PackageManager pm = context.getPackageManager();
    String[] pkg = pm.getPackagesForUid(uid);
    if (pkg != null && pkg.length > 0)
        try {
            info = pm.getApplicationInfo(pkg[0], 0);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    if (info == null)
        ivIcon.setImageDrawable(null);
    else if (info.icon == 0)
        Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(ivIcon);
    else {
        Uri uri = Uri.parse("android.resource://" + info.packageName + "/" + info.icon);
        Picasso.with(context).load(uri).resize(iconSize, iconSize).into(ivIcon);
    }

    // https://android.googlesource.com/platform/system/core/+/master/include/private/android_filesystem_config.h
    uid = uid % 100000; // strip off user ID
    if (uid == -1)
        tvUid.setText("");
    else if (uid == 0)
        tvUid.setText(context.getString(R.string.title_root));
    else if (uid == 9999)
        tvUid.setText("-"); // nobody
    else
        tvUid.setText(Integer.toString(uid));

    // Show source address
    tvSAddr.setText(getKnownAddress(saddr));

    // Show destination address
    if (resolve && !isKnownAddress(daddr))
        if (dname == null) {
            tvDaddr.setText(daddr);
            new AsyncTask<String, Object, String>() {
                @Override
                protected void onPreExecute() {
                    ViewCompat.setHasTransientState(tvDaddr, true);
                }

                @Override
                protected String doInBackground(String... args) {
                    try {
                        return InetAddress.getByName(args[0]).getHostName();
                    } catch (UnknownHostException ignored) {
                        return args[0];
                    }
                }

                @Override
                protected void onPostExecute(String name) {
                    tvDaddr.setText(">" + name);
                    ViewCompat.setHasTransientState(tvDaddr, false);
                }
            }.execute(daddr);
        } else
            tvDaddr.setText(dname);
    else
        tvDaddr.setText(getKnownAddress(daddr));

    // Show organization
    tvOrganization.setVisibility(View.GONE);
    if (organization) {
        if (!isKnownAddress(daddr))
            new AsyncTask<String, Object, String>() {
                @Override
                protected void onPreExecute() {
                    ViewCompat.setHasTransientState(tvOrganization, true);
                }

                @Override
                protected String doInBackground(String... args) {
                    try {
                        return Util.getOrganization(args[0]);
                    } catch (Throwable ex) {
                        Log.w(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                        return null;
                    }
                }

                @Override
                protected void onPostExecute(String organization) {
                    if (organization != null) {
                        tvOrganization.setText(organization);
                        tvOrganization.setVisibility(View.VISIBLE);
                    }
                    ViewCompat.setHasTransientState(tvOrganization, false);
                }
            }.execute(daddr);
    }

    // Show extra data
    if (TextUtils.isEmpty(data)) {
        tvData.setText("");
        tvData.setVisibility(View.GONE);
    } else {
        tvData.setText(data);
        tvData.setVisibility(View.VISIBLE);
    }
}