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:jp.mau.twappremover.MainActivity.java

private void loginTask() {
    final PopupView dialog = new PopupView(MainActivity.this);

    final AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
        @Override//w  ww .ja  v  a2  s.  c om
        protected void onPreExecute() {
            dialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            _client.getConnectionManager().shutdown();
            _client = new DefaultHttpClient();
            HttpParams hparams = _client.getParams();
            HttpConnectionParams.setConnectionTimeout(hparams, 60 * 1000);
            HttpConnectionParams.setSoTimeout(hparams, 60 * 1000);
            _client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

            getTopPage();
            // got session id and auth-token
            // login
            if (login()) {
                getApps();
            } else {
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            dialog.dismiss();
            if (!result) {
                // 
                final PopupView dialog = new PopupView(MainActivity.this);
                dialog.setDialog()
                        .setLabels(getString(R.string.activity_main_dlgtitle_loginfail),
                                getString(R.string.activity_main_dlgmsg_loginfail))
                        .setCancelable(true).setPositiveBtn(getString(R.string.activity_main_dlgbtn_loginfail),
                                new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                })
                        .show();
            }
        }

    };

    dialog.setDialog().setLabels(getString(R.string.activity_main_dlgtitle_loading),
            getString(R.string.activity_main_dlgmsg_loading));

    task.execute();
}

From source file:eu.operando.operandoapp.OperandoProxyStatus.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    MainUtil.initializeMainContext(getApplicationContext());
    Settings settings = mainContext.getSettings();
    settings.initializeDefaultValues();/*  w  w w .j  a v  a2s  . c  o  m*/
    setCurrentThemeStyle(settings.getThemeStyle());
    setTheme(getCurrentThemeStyle().themeAppCompatStyle());
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    settings.registerOnSharedPreferenceChangeListener(this);

    webView = (WebView) findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);

    //region Floating Action Button

    fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (MainUtil.isServiceRunning(mainContext.getContext(), ProxyService.class)
                    && !MainUtil.isProxyPaused(mainContext)) {
                //Update Preferences to BypassProxy
                MainUtil.setProxyPaused(mainContext, true);
                fab.setImageResource(android.R.drawable.ic_media_play);
                //Toast.makeText(mainContext.getContext(), "-- bypass (disable) proxy --", Toast.LENGTH_SHORT).show();
            } else if (MainUtil.isServiceRunning(mainContext.getContext(), ProxyService.class)
                    && MainUtil.isProxyPaused(mainContext)) {

                MainUtil.setProxyPaused(mainContext, false);
                fab.setImageResource(android.R.drawable.ic_media_pause);
                //Toast.makeText(mainContext.getContext(), "-- re-enable proxy --", Toast.LENGTH_SHORT).show();
            } else if (!mainContext.getAuthority()
                    .aliasFile(BouncyCastleSslEngineSource.KEY_STORE_FILE_EXTENSION).exists()) {
                try {
                    installCert();
                } catch (RootCertificateException | GeneralSecurityException | OperatorCreationException
                        | IOException ex) {
                    Logger.error(this, ex.getMessage(), ex.getCause());
                }
            }
        }
    });

    //endregion

    //region TabHost

    final TabHost tabHost = (TabHost) findViewById(R.id.tabHost2);
    tabHost.setup();

    TabHost.TabSpec tabSpec = tabHost.newTabSpec("wifi_ap");
    tabSpec.setContent(R.id.WifiAndAccessPointsScrollView);
    tabSpec.setIndicator("", getResources().getDrawable(R.drawable.ic_home));
    tabHost.addTab(tabSpec);

    tabSpec = tabHost.newTabSpec("response_domain_filters");
    tabSpec.setContent(R.id.ResponseAndDomainFiltersScrollView);
    tabSpec.setIndicator("", getResources().getDrawable(R.drawable.ic_filter));
    tabHost.addTab(tabSpec);

    tabSpec = tabHost.newTabSpec("pending_notifications");
    tabSpec.setContent(R.id.PendingNotificationsScrollView);
    tabSpec.setIndicator("", getResources().getDrawable(R.drawable.ic_pending_notification));
    tabHost.addTab(tabSpec);

    tabSpec = tabHost.newTabSpec("logs");
    tabSpec.setContent(R.id.LogsScrollView);
    tabSpec.setIndicator("", getResources().getDrawable(R.drawable.ic_report));
    tabHost.addTab(tabSpec);

    tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            switch (tabId) {
            case "pending_notifications":
                //region Load Tab3
                ((TableLayout) ((LinearLayout) ((ScrollView) findViewById(R.id.PendingNotificationsScrollView))
                        .getChildAt(0)).getChildAt(1)).removeAllViews();
                LoadPendingNotificationsTab();
                //endregion
                break;
            case "logs":
                //region Load Tab 4
                //because it is a heavy task it is being loaded asynchronously
                ((TableLayout) ((LinearLayout) ((ScrollView) findViewById(R.id.LogsScrollView)).getChildAt(0))
                        .getChildAt(1)).removeAllViews();
                new AsyncTask() {
                    private ProgressDialog mProgress;
                    private List<String[]> apps;

                    @Override
                    protected void onPreExecute() {
                        super.onPreExecute();
                        mProgress = new ProgressDialog(MainActivity.this);
                        mProgress.setCancelable(false);
                        mProgress.setCanceledOnTouchOutside(false);
                        mProgress.setTitle("Fetching Application Data Logs");
                        mProgress.show();
                    }

                    @Override
                    protected Object doInBackground(Object[] params) {
                        apps = new ArrayList();
                        for (String[] app : getInstalledApps(false)) {
                            apps.add(new String[] { app[0], GetDataForApp(Integer.parseInt(app[1])) });
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Object o) {
                        super.onPostExecute(o);
                        mProgress.dismiss();
                        for (String[] app : apps) {
                            if (app[0].contains(".")) {
                                continue;
                            }
                            TextView tv = new TextView(MainActivity.this);
                            tv.setTextSize(18);
                            tv.setText(app[0] + " || " + app[1]);
                            ((TableLayout) ((LinearLayout) ((ScrollView) findViewById(R.id.LogsScrollView))
                                    .getChildAt(0)).getChildAt(1)).addView(tv);

                            View separator = new View(MainActivity.this);
                            separator.setBackgroundColor(Color.BLACK);
                            separator.setLayoutParams(
                                    new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 5));
                            ((TableLayout) ((LinearLayout) ((ScrollView) findViewById(R.id.LogsScrollView))
                                    .getChildAt(0)).getChildAt(1)).addView(separator);
                        }
                    }
                }.execute();
                //endregion
                break;
            }
        }
    });

    //endregion

    //region Buttons

    WiFiAPButton = (Button) findViewById(R.id.WiFiAPButton);
    WiFiAPButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(mainContext.getContext(), AccessPointsActivity.class);
            startActivity(i);
        }
    });

    responseFiltersButton = (Button) findViewById(R.id.responseFiltersButton);
    responseFiltersButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(mainContext.getContext(), ResponseFiltersActivity.class);
            startActivity(i);
        }
    });

    domainFiltersButton = (Button) findViewById(R.id.domainFiltersButton);
    domainFiltersButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(mainContext.getContext(), DomainFiltersActivity.class);
            startActivity(i);
        }
    });

    domainManagerButton = (Button) findViewById(R.id.domainManagerButton);
    domainManagerButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(mainContext.getContext(), DomainManagerActivity.class);
            startActivity(i);
        }
    });

    permissionsPerDomainButton = (Button) findViewById(R.id.permissionsPerDomainButton);
    permissionsPerDomainButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(mainContext.getContext(), PermissionsPerDomainActivity.class);
            startActivity(i);
        }
    });

    trustedAccessPointsButton = (Button) findViewById(R.id.trustedAccessPointsButton);
    trustedAccessPointsButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(mainContext.getContext(), TrustedAccessPointsActivity.class);
            startActivity(i);
        }
    });

    updateButton = (Button) findViewById(R.id.updateButton);
    updateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // mark first time has not runned and update like it's initial .
            final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("firstTime", true);
            editor.commit();
            DownloadInitialSettings();
        }
    });

    statisticsButton = (Button) findViewById(R.id.statisticsButton);
    statisticsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(mainContext.getContext(), StatisticsActivity.class);
            startActivity(i);
        }
    });

    //endregion

    //region Action Bar
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        setTitle(R.string.app_name);
    }

    //endregion

    //region Send Cached Settings
    //send cached settings if exist...
    BufferedReader br = null;
    try {
        File file = new File(MainContext.INSTANCE.getContext().getFilesDir(), "resend.inf");
        StringBuilder content = new StringBuilder();
        br = new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null) {
            content.append(line);
        }
        if (content.toString().equals("1")) {
            File f = new File(file.getCanonicalPath());
            f.delete();
            new DatabaseHelper(MainActivity.this)
                    .sendSettingsToServer(new RequestFilterUtil(MainActivity.this).getIMEI());
        }
    } catch (Exception ex) {
        ex.getMessage();
    } finally {
        try {
            br.close();
        } catch (Exception ex) {
            ex.getMessage();
        }
    }
    //endregion

    initializeProxyService();
}

From source file:org.deviceconnect.android.deviceplugin.sonycamera.utils.DConnectUtil.java

/**
 * ???.// w  ww  .  j  a va 2 s  . c  om
 * 
 * @param deviceId ?ID
 * @param sessionKey ID
 * @param listener 
 */
public static void asyncRegistAccel(final String deviceId, final String sessionKey,
        final DConnectMessageHandler listener) {
    AsyncTask<Void, Void, DConnectMessage> task = new AsyncTask<Void, Void, DConnectMessage>() {
        @Override
        protected DConnectMessage doInBackground(final Void... params) {
            try {
                DConnectClient client = new HttpDConnectClient();
                HttpPut request = new HttpPut(
                        DEVICE_ORIENTATION_URI + "?deviceId=" + deviceId + "&sessionKey=" + sessionKey);
                HttpResponse response = client.execute(request);
                return (new HttpMessageFactory()).newDConnectMessage(response);
            } catch (IOException e) {
                return new DConnectResponseMessage(DConnectMessage.RESULT_ERROR);
            }
        }

        @Override
        protected void onPostExecute(final DConnectMessage message) {
            if (listener != null) {
                listener.handleMessage(message);
            }
        }
    };
    task.execute();
}

From source file:ca.ualberta.cmput301.t03.MainActivity.java

/**
 * After confirmation of Configuration holding a username, this method will setup and load
 * the application's User singleton.//from   w ww .j  a v a 2  s  .  c o  m
 */
private void afterUserSetup() {
    AsyncTask task = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] params) {
            PrimaryUser.setup(getApplicationContext());
            User mainUser = PrimaryUser.getInstance();
            TradeApp.startNotificationService();
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            finishOnCreate();
        }
    };
    task.execute();
}

From source file:net.majorkernelpanic.spydroid.ClientActivity.java

private void updateSettings() {
    final String oldVideoParameters = videoParameters, oldAudioParameters = audioParameters;
    generateURI();/* www  .j ava  2 s  . c  o  m*/
    if (oldVideoParameters == videoParameters && oldAudioParameters == audioParameters)
        return;
    stopStreaming();
    progressBar.setVisibility(View.VISIBLE);
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            HttpClient client = new DefaultHttpClient();
            //HttpGet request = new HttpGet("http://"+editTextIP.getText().toString()+":8080?set&"+uriParameters);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ignore) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void weird) {
            Log.d(TAG, "Reconnecting to server...");
            connectToServer();
        }
    }.execute();
}

From source file:com.facebook.reflection.SelectionFragment.java

private void handleGraphApiAnnounce() {
    Session session = Session.getActiveSession();

    List<String> permissions = session.getPermissions();
    if (!permissions.contains(PERMISSION)) {
        pendingAnnounce = true;//from w w w .ja v  a2  s.  c  o m
        requestPublishPermissions(session);
        return;
    }

    // Show a progress dialog because sometimes the requests can take a while.
    progressDialog = ProgressDialog.show(getActivity(), "",
            getActivity().getResources().getString(R.string.progress_dialog_text), true);

    // Run this in a background thread so we can process the list of responses and extract errors.
    AsyncTask<Void, Void, List<Response>> task = new AsyncTask<Void, Void, List<Response>>() {

        @Override
        protected List<Response> doInBackground(Void... voids) {
            EatAction eatAction = createEatAction();

            RequestBatch requestBatch = new RequestBatch();

            String photoStagingUri = null;

            if (photoUri != null) {
                try {
                    Pair<File, Integer> fileAndMinDimemsion = getImageFileAndMinDimension();
                    if (fileAndMinDimemsion != null) {
                        Request photoStagingRequest = Request.newUploadStagingResourceWithImageRequest(
                                Session.getActiveSession(), fileAndMinDimemsion.first, null);
                        photoStagingRequest.setBatchEntryName("photoStaging");
                        requestBatch.add(photoStagingRequest);
                        // Facebook SDK * pro-tip *
                        // We can use the result from one request in the batch as the input to another request.
                        // In this case, the result from the staging upload is "uri", which we will use as the
                        // input into the "url" field for images on the open graph action below.
                        photoStagingUri = "{result=photoStaging:$.uri}";
                        eatAction.setImage(getImageListForAction(photoStagingUri,
                                fileAndMinDimemsion.second >= USER_GENERATED_MIN_SIZE));
                    }
                } catch (FileNotFoundException e) {
                    // NOOP - if we can't upload the image, just skip it for now
                }
            }
            MealGraphObject meal = eatAction.getMeal();
            if (meal.getCreateObject()) {
                Request createObjectRequest = Request.newPostOpenGraphObjectRequest(Session.getActiveSession(),
                        meal, null);
                createObjectRequest.setBatchEntryName("createObject");
                requestBatch.add(createObjectRequest);
                eatAction.setProperty("meal", "{result=createObject:$.id}");
            }

            Request request = Request.newPostOpenGraphActionRequest(Session.getActiveSession(), eatAction,
                    null);
            requestBatch.add(request);

            return requestBatch.executeAndWait();
        }

        @Override
        protected void onPostExecute(List<Response> responses) {
            // We only care about the last response, or the first one with an error.
            Response finalResponse = null;
            for (Response response : responses) {
                finalResponse = response;
                if (response != null && response.getError() != null) {
                    break;
                }
            }
            onPostActionResponse(finalResponse);
        }
    };

    task.execute();
}

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

@Override
public void onRefresh() {
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override/*from  w ww . jav  a2  s.c  o  m*/
        protected Void doInBackground(Void... params) {
            try {
                PrimaryUser.getInstance().refresh();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServiceNotAvailableException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    };
    task.execute();
}

From source file:ca.ualberta.cmput301.t03.inventory.UserInventoryFragment.java

@Override
public void onRefresh() {
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override/*ww w.j  a  v  a  2  s. c  o  m*/
        protected Void doInBackground(Void... params) {
            try {
                PrimaryUser.getInstance().refresh();
                model = user.getInventory();

            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServiceNotAvailableException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            model.setFilters(filters);
            adapter.notifyUpdated(model);
            mSwipeRefreshLayout.setRefreshing(false);
        }
    };
    task.execute();
}

From source file:org.anhonesteffort.flock.SubscriptionGoogleFragment.java

private void handleRequestPurchaseIntent(final String productType, final String productSku) {
    if (asyncTask != null)
        return;//from ww w .jav a  2s . c  om

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

        @Override
        protected void onPreExecute() {
            Log.d(TAG, "handleRequestPurchaseIntent");
            subscriptionActivity.setProgressBarIndeterminateVisibility(true);
            subscriptionActivity.setProgressBarVisibility(true);
        }

        @Override
        protected Bundle doInBackground(Void... params) {
            Bundle result = new Bundle();

            if (subscriptionActivity.billingService == null) {
                Log.e(TAG, "billing service is null");
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR);
                return result;
            }

            String developerPayload = Base64
                    .encodeBytes(subscriptionActivity.davAccount.getUserId().toUpperCase().getBytes());

            try {

                Bundle intentBundle = subscriptionActivity.billingService.getBuyIntent(3,
                        SubscriptionGoogleFragment.class.getPackage().getName(), productSku, productType,
                        developerPayload);

                if (intentBundle.getParcelable("BUY_INTENT") != null) {
                    result.putParcelable("BUY_INTENT", intentBundle.getParcelable("BUY_INTENT"));
                    result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_SUCCESS);

                    return result;
                }
                Log.e(TAG, "buy intent is null");

            } catch (RemoteException e) {
                Log.e(TAG, "caught remote exception while getting buy intent", e);
            }

            result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR);

            return result;
        }

        @Override
        protected void onPostExecute(Bundle result) {
            asyncTask = null;
            subscriptionActivity.setProgressBarIndeterminateVisibility(false);
            subscriptionActivity.setProgressBarVisibility(false);

            if (result.getInt(ErrorToaster.KEY_STATUS_CODE) == ErrorToaster.CODE_SUCCESS)
                handleStartPurchaseIntent((PendingIntent) result.getParcelable("BUY_INTENT"));
            else
                ErrorToaster.handleDisplayToastBundledError(subscriptionActivity, result);
        }
    }.execute();
}

From source file:com.herokuapp.pushdemoandroid.DemoActivity.java

private void sendPostRequest() {
    pDialog.setMessage("Registering ...");
    showDialog();//ww  w .j  a v  a  2 s  .c  o  m
    final Context context = this;
    mRegisterTask = new AsyncTask<Void, Void, HttpResponse>() {

        @Override
        protected HttpResponse doInBackground(Void... params) {
            // Register to server
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(CommonUtilities.SERVER_URL_REGISTER);
            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
            nameValuePair.add(new BasicNameValuePair(CommonUtilities.PROPERTY_REG_USERNAME, username));
            nameValuePair.add(new BasicNameValuePair(CommonUtilities.PROPERTY_REG_PASSWORD, password));
            nameValuePair.add(new BasicNameValuePair(CommonUtilities.PROPERTY_REG_GCMID, regid));
            nameValuePair.add(new BasicNameValuePair(CommonUtilities.PROPERTY_REG_ROLE, "ROLE_USER"));
            nameValuePair.add(new BasicNameValuePair(CommonUtilities.PROPERTY_REG_EMAIL, email));

            //Encoding POST data
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            try {
                HttpResponse response = httpClient.execute(httpPost);
                // write response to log
                Log.d("Http Post Response:", response.toString());
                return response;
            } catch (ClientProtocolException e) {
                // Log exception
                e.printStackTrace();
            } catch (IOException e) {
                // Log exception
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(HttpResponse result) {
            hideDialog();
            if (result == null)
                return;
            String jsonBody = "";
            boolean error = false;
            String errorMessage = "";
            String name = "";
            String mail = "";
            try {
                jsonBody = EntityUtils.toString(result.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (!jsonBody.isEmpty()) {
                try {
                    JSONObject data = new JSONObject(jsonBody);
                    error = data.getBoolean("error");
                    if (error)
                        errorMessage = data.getString("error_message");
                    JSONObject user = data.getJSONObject("user");
                    name = user.getString("name");
                    mail = user.getString("email");
                    String createdAt = user.getString("created_at");
                    String uid = user.getString("uid");

                    // Inserting row in users table
                    db.addUser(name, mail, uid, createdAt);

                    Log.i(CommonUtilities.TAG,
                            "JSONObject user= " + user + " name =" + name + "email = " + mail);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (!error) {
                    mRegisterTask = null;
                    Intent i = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(i);
                    finish();
                } else {
                    alert.showAlertDialog(DemoActivity.this, "An error has occurred", errorMessage, false);
                }
            }

        }

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