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:org.deviceconnect.android.uiapp.fragment.profile.ExtraProfileFragment.java

/**
 * ??./*from  w  w w. j a v a2 s .com*/
 * @param view ?
 */
protected void onClickSend(final View view) {
    // 
    final CharSequence inter = ((TextView) getView().findViewById(R.id.fragment_extra_interface)).getText();
    // 
    final CharSequence attr = ((TextView) getView().findViewById(R.id.fragment_extra_attribute)).getText();
    // 
    final String accessToken = getAccessToken();
    // 
    final CharSequence query = ((TextView) getView().findViewById(R.id.fragment_extra_query)).getText();

    final URIBuilder builder = new URIBuilder();
    builder.setProfile(mProfile);
    if (inter != null && inter.length() > 0) {
        builder.setInterface(inter.toString());
    }
    if (attr != null && attr.length() > 0) {
        builder.setAttribute(attr.toString());
    }
    builder.addParameter(DConnectMessage.EXTRA_DEVICE_ID, getSmartDevice().getId());
    if (accessToken != null) {
        builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, accessToken);
    }
    if (query != null) {
        String path = query.toString();
        if (path.length() > 0) {
            String[] keyvalues = path.split("&");
            for (int i = 0; i < keyvalues.length; i++) {
                String[] kv = keyvalues[i].split("=");
                if (kv.length == 1) {
                    builder.addParameter(kv[0], "");
                } else if (kv.length == 2) {
                    builder.addParameter(kv[0], kv[1]);
                }
            }
        }
    }

    HttpRequest request = null;
    try {
        Spinner spinner = (Spinner) getView().findViewById(R.id.spinner);
        String method = (String) spinner.getSelectedItem();
        if (method.equals("GET")) {
            request = new HttpGet(builder.build());
        } else if (method.equals("POST")) {
            request = new HttpPost(builder.build());
        } else if (method.equals("PUT")) {
            request = new HttpPut(builder.build());
        } else if (method.equals("DELETE")) {
            request = new HttpDelete(builder.build());
        }
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView tv = (TextView) getView().findViewById(R.id.fragment_extra_request);
                try {
                    String uri = builder.build().toASCIIString();
                    tv.setText(uri);
                } catch (URISyntaxException e) {
                    tv.setText("");
                }
            }
        });
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    (new AsyncTask<HttpRequest, Void, DConnectMessage>() {
        public DConnectMessage doInBackground(final HttpRequest... args) {
            if (args == null || args.length <= 0) {
                return new DConnectResponseMessage(DConnectMessage.RESULT_ERROR);
            }

            DConnectMessage message = new DConnectResponseMessage(DConnectMessage.RESULT_ERROR);
            try {
                HttpRequest request = args[0];
                HttpResponse response = getDConnectClient().execute(getDefaultHost(), request);
                message = (new HttpMessageFactory()).newDConnectMessage(response);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return message;
        }

        @Override
        protected void onPostExecute(final DConnectMessage result) {

            if (getActivity().isFinishing()) {
                return;
            }

            if (result == null) {
                return;
            }
            View view = getView();
            if (view != null) {
                TextView tv = (TextView) view.findViewById(R.id.fragment_extra_response);
                tv.setText(result.toString());
            }
        }
    }).execute(request);
}

From source file:com.userhook.view.UHMessageView.java

protected void loadMessage(Map<String, Object> params) {

    if (meta.getDisplayType().equals(UHMessageMeta.TYPE_IMAGE)) {

        if (meta.getButton1() != null && meta.getButton1().getImage() != null
                && meta.getButton1().getImage().getUrl() != null) {

            AsyncTask task = new AsyncTask<Object, Void, Drawable>() {

                @Override/*from  ww w.  ja  v  a  2  s.c o m*/
                protected Drawable doInBackground(Object... params) {
                    Drawable drawable = null;

                    try {

                        URL url = new URL((String) params[0]);

                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        InputStream is = conn.getInputStream();

                        drawable = Drawable.createFromStream(is, "src");

                        int height = drawable.getIntrinsicHeight();
                        int width = drawable.getIntrinsicWidth();

                        drawable.setBounds(0, 0, width, height);

                    } catch (Exception e) {
                        Log.e(UserHook.TAG, "error download message image", e);
                    }

                    return drawable;
                }

                @Override
                protected void onPostExecute(Drawable result) {

                    if (result != null) {

                        // size image to fit inside the view
                        int screenHeight = getResources().getDisplayMetrics().heightPixels;
                        int screenWidth = getResources().getDisplayMetrics().widthPixels;

                        int heightGutter = 40;
                        int widthGutter = 40;

                        int screenSpaceHeight = screenHeight - heightGutter * 2;
                        int screenSpaceWidth = screenWidth - widthGutter * 2;

                        float height = result.getIntrinsicHeight();
                        float width = result.getIntrinsicWidth();
                        float aspect = height / width;

                        if (height > screenSpaceHeight) {
                            height = screenHeight;
                            width = height / aspect;
                        }

                        if (width > screenSpaceWidth) {
                            width = screenSpaceWidth;
                            height = width * aspect;
                        }

                        ImageView imageView = new ImageView(getContext());
                        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                        imageView.setImageDrawable(result);

                        LayoutParams layoutParams = new LayoutParams((int) width, (int) height);
                        layoutParams.addRule(CENTER_IN_PARENT);
                        addView(imageView, layoutParams);

                        // add click handler to image
                        imageView.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (meta.getButton1() != null) {
                                    clickedButton(meta.getButton1());
                                }
                            }
                        });

                        contentLoaded = true;

                        if (showAfterLoad) {
                            showDialog();
                        }

                    }
                }
            };

            task.execute(meta.getButton1().getImage().getUrl());

        }

    } else if (UHMessageTemplate.getInstance().hasTemplate(meta.getDisplayType())) {

        String html = UHMessageTemplate.getInstance().renderTemplate(meta);

        loadWebViewContent(html);

        if (showAfterLoad) {
            showDialog();
        }

    } else {

        UHPostAsyncTask asyncTask = new UHPostAsyncTask(params, new UHAsyncTask.UHAsyncTaskListener() {
            @Override
            public void onSuccess(String result) {

                if (result != null) {

                    loadWebViewContent(result);

                }

                if (showAfterLoad) {
                    showDialog();
                }
            }
        });

        asyncTask.execute(UserHook.UH_HOST_URL + UH_MESSAGE_PATH);

    }

}

From source file:com.parse.f8.model.Favorites.java

/**
 * Saves the current set of favorites to a SharedPreferences file. This
 * method returns quickly, while the saving runs asynchronously.
 *//* ww w  .j  a  va2 s  .  co m*/
private void saveLocally(final Context context) {
    final JSONObject json = toJSON();

    new AsyncTask<Void, Void, Exception>() {
        @Override
        protected Exception doInBackground(Void... unused) {
            try {
                String jsonString = json.toString();
                SharedPreferences prefs = context.getSharedPreferences("favorites.json", Context.MODE_PRIVATE);
                prefs.edit().putString("json", jsonString).commit();
            } catch (Exception e) {
                return e;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Exception error) {
            if (error != null) {
                Toast toast = Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG);
                toast.show();
            }
        }
    }.execute();
}

From source file:jp.ne.sakura.kkkon.java.net.inetaddress.testapp.android.NetworkConnectionCheckerTestApp.java

/** Called when the activity is first created. */
@Override//from   w w  w.j a v a2 s.  c  o  m
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        NetworkConnectionChecker.initialize();
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("reachable=");
    layout.addView(tv);
    this.textView = tv;

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    {
        Button btn = new Button(this);
        btn.setText("disp isReachable");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                final boolean isReachable = NetworkConnectionChecker.isReachable();
                Toast toast = Toast.makeText(context, "IsReachable=" + isReachable, Toast.LENGTH_LONG);
                toast.show();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("upload http AsyncTask");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                    @Override
                    protected Boolean doInBackground(String... paramss) {
                        Boolean result = true;
                        Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                        try {
                            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                            Log.d(TAG, "fng=" + Build.FINGERPRINT);
                            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                            HttpPost httpPost = new HttpPost(paramss[0]);
                            //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                            httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                    new Integer(5 * 1000));
                            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                    new Integer(5 * 1000));
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            // <uses-permission android:name="android.permission.INTERNET"/>
                            // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                            HttpResponse response = httpClient.execute(httpPost);
                            Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                        } catch (Exception e) {
                            Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                            result = false;
                        }
                        Log.d(TAG, "upload finish");
                        return result;
                    }

                };

                asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
                asyncTask.isCancelled();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(0.0.0.0)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            destHost = InetAddress.getByName("0.0.0.0");
                            if (null != destHost) {
                                try {
                                    if (destHost.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " reachable");
                                    } else {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " not reachable");
                                    }
                                } catch (IOException e) {

                                }
                            }
                        } catch (UnknownHostException e) {

                        }
                        Log.d(TAG, "destHost=" + destHost);
                    }
                });
                thread.start();
                try {
                    thread.join(1000);
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }
    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(www.google.com)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        Log.d(TAG, "start");
                        try {
                            InetAddress dest = InetAddress.getByName("www.google.com");
                            if (null == dest) {
                                dest = destHost;
                            }

                            if (null != dest) {
                                final String[] uris = new String[] { "http://www.google.com/",
                                        "https://www.google.com/" };
                                for (final String destURI : uris) {
                                    URI uri = null;
                                    try {
                                        uri = new URI(destURI);
                                    } catch (URISyntaxException e) {
                                        //Log.d( TAG, e.toString() );
                                    }

                                    if (null != uri) {
                                        URL url = null;
                                        try {
                                            url = uri.toURL();
                                        } catch (MalformedURLException ex) {
                                            Log.d(TAG, "got exception:" + ex.toString(), ex);
                                        }

                                        URLConnection conn = null;
                                        if (null != url) {
                                            Log.d(TAG, "openConnection before");
                                            try {
                                                conn = url.openConnection();
                                                if (null != conn) {
                                                    conn.setConnectTimeout(3 * 1000);
                                                    conn.setReadTimeout(3 * 1000);
                                                }
                                            } catch (IOException e) {
                                                //Log.d( TAG, "got Exception" + e.toString(), e );
                                            }
                                            Log.d(TAG, "openConnection after");
                                            if (conn instanceof HttpURLConnection) {
                                                HttpURLConnection httpConn = (HttpURLConnection) conn;
                                                int responceCode = -1;
                                                try {
                                                    Log.d(TAG, "getResponceCode before");
                                                    responceCode = httpConn.getResponseCode();
                                                    Log.d(TAG, "getResponceCode after");
                                                } catch (IOException ex) {
                                                    Log.d(TAG, "got exception:" + ex.toString(), ex);
                                                }
                                                Log.d(TAG, "responceCode=" + responceCode);
                                                if (0 < responceCode) {
                                                    isReachable = true;
                                                    destHost = dest;
                                                }
                                                Log.d(TAG,
                                                        " HTTP ContentLength=" + httpConn.getContentLength());
                                                httpConn.disconnect();
                                                Log.d(TAG,
                                                        " HTTP ContentLength=" + httpConn.getContentLength());
                                            }
                                        }
                                    } // if uri

                                    if (isReachable) {
                                        //break;
                                    }
                                } // for uris
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                        Log.d(TAG, "end");
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        Log.d(TAG, "start");
                        try {
                            InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                        Log.d(TAG, "end");
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp) support proxy");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            String target = null;
                            {
                                ProxySelector proxySelector = ProxySelector.getDefault();
                                Log.d(TAG, "proxySelector=" + proxySelector);
                                if (null != proxySelector) {
                                    URI uri = null;
                                    try {
                                        uri = new URI("http://www.google.com/");
                                    } catch (URISyntaxException e) {
                                        Log.d(TAG, e.toString());
                                    }
                                    List<Proxy> proxies = proxySelector.select(uri);
                                    if (null != proxies) {
                                        for (final Proxy proxy : proxies) {
                                            Log.d(TAG, " proxy=" + proxy);
                                            if (null != proxy) {
                                                if (Proxy.Type.HTTP == proxy.type()) {
                                                    final SocketAddress sa = proxy.address();
                                                    if (sa instanceof InetSocketAddress) {
                                                        final InetSocketAddress isa = (InetSocketAddress) sa;
                                                        target = isa.getHostName();
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (null == target) {
                                target = "kkkon.sakura.ne.jp";
                            }
                            InetAddress dest = InetAddress.getByName(target);
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                        {
                                            ProxySelector proxySelector = ProxySelector.getDefault();
                                            //Log.d( TAG, "proxySelector=" + proxySelector );
                                            if (null != proxySelector) {
                                                URI uri = null;
                                                try {
                                                    uri = new URI("http://www.google.com/");
                                                } catch (URISyntaxException e) {
                                                    //Log.d( TAG, e.toString() );
                                                }

                                                if (null != uri) {
                                                    List<Proxy> proxies = proxySelector.select(uri);
                                                    if (null != proxies) {
                                                        for (final Proxy proxy : proxies) {
                                                            //Log.d( TAG, " proxy=" + proxy );
                                                            if (null != proxy) {
                                                                if (Proxy.Type.HTTP == proxy.type()) {
                                                                    URL url = uri.toURL();
                                                                    URLConnection conn = null;
                                                                    if (null != url) {
                                                                        try {
                                                                            conn = url.openConnection(proxy);
                                                                            if (null != conn) {
                                                                                conn.setConnectTimeout(
                                                                                        3 * 1000);
                                                                                conn.setReadTimeout(3 * 1000);
                                                                            }
                                                                        } catch (IOException e) {
                                                                            Log.d(TAG, "got Exception"
                                                                                    + e.toString(), e);
                                                                        }
                                                                        if (conn instanceof HttpURLConnection) {
                                                                            HttpURLConnection httpConn = (HttpURLConnection) conn;
                                                                            if (0 < httpConn
                                                                                    .getResponseCode()) {
                                                                                isReachable = true;
                                                                            }
                                                                            Log.d(TAG, " HTTP ContentLength="
                                                                                    + httpConn
                                                                                            .getContentLength());
                                                                            Log.d(TAG, " HTTP res=" + httpConn
                                                                                    .getResponseCode());
                                                                            //httpConn.setInstanceFollowRedirects( false );
                                                                            //httpConn.setRequestMethod( "HEAD" );
                                                                            //conn.connect();
                                                                            httpConn.disconnect();
                                                                            Log.d(TAG, " HTTP ContentLength="
                                                                                    + httpConn
                                                                                            .getContentLength());
                                                                            Log.d(TAG, " HTTP res=" + httpConn
                                                                                    .getResponseCode());
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }
                                    destHost = dest;
                                } catch (IOException e) {
                                    Log.d(TAG, "got Excpetion " + e.toString());
                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    setContentView(layout);
}

From source file:com.is.rest.cache.CacheAwareCallback.java

@Override
public void onFailure(final int statusCode, final Header[] headers, final Throwable e,
        final String responseBody, final Result errorResponse) {
    Logger.d("onFailure: status" + statusCode + " rawResponse: " + responseBody);

    ExecutionUtils.execute(new AsyncTask<Void, Void, Result>() {
        @Override//from w ww  .  j ava  2s  . co  m
        protected Result doInBackground(Void... voids) {
            Result cachedResponse = null;
            boolean loadFromCache = false;
            switch (cacheInfo.getPolicy()) {
            case LOAD_IF_TIMEOUT:
                if (e != null && (ConnectTimeoutException.class.isAssignableFrom(e.getClass())
                        || SocketTimeoutException.class.isAssignableFrom(e.getClass()))) {
                    loadFromCache = true;
                }
                break;
            case LOAD_ON_ERROR:
                loadFromCache = true;
                break;
            default:
                break;

            }
            if (loadFromCache) {
                try {
                    cachedResponse = cacheManager.get(cacheInfo.getKey(), cacheInfo);
                } catch (IOException e1) {
                    Logger.e("cache error", e);
                } catch (ClassNotFoundException e1) {
                    Logger.e("cache error", e);
                }
            }
            return cachedResponse;
        }

        @Override
        public void onPostExecute(Result result) {
            if (result != null) {
                String errorMsg = e != null ? e.getLocalizedMessage() : "n/a";
                Logger.d("CacheAwareCallback. Loading from cache after response error: " + errorMsg
                        + " result with cached result: " + result);
                cacheInfo.setLoadedFromCache(true);
            }

            Response<Result> httpResponse = new Response<Result>(statusCode, headers, responseBody,
                    errorResponse, e, getCacheInfo());
            if (proceedWithResponse()) {
                timesProcessed++;
                onResponse(httpResponse);
            }
        }

    });
}

From source file:ca.rmen.android.networkmonitor.app.prefs.PreferenceFragmentActivity.java

@Override
public void onOkClicked(int actionId, Bundle extras) {
    Log.v(TAG, "onClicked, actionId=" + actionId + ", extras = " + extras);
    mUserInput = true;/*from  ww w .ja  v  a2  s. c  o m*/
    // Import the database in a background thread.
    if (actionId == ID_ACTION_IMPORT) {
        final Uri uri = extras.getParcelable(EXTRA_IMPORT_URI);
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {

            @Override
            protected void onPreExecute() {
                DialogFragmentFactory.showProgressDialog(PreferenceFragmentActivity.this,
                        getString(R.string.progress_dialog_message), ProgressDialog.STYLE_SPINNER,
                        PROGRESS_DIALOG_FRAGMENT_TAG);
            }

            @Override
            protected Boolean doInBackground(Void... params) {
                try {
                    Log.v(TAG, "Importing db from " + uri);
                    DBImport.importDB(PreferenceFragmentActivity.this, uri);
                    return true;
                } catch (Exception e) {
                    Log.e(TAG, "Error importing db: " + e.getMessage(), e);
                    return false;
                }
            }

            @Override
            protected void onPostExecute(Boolean result) {
                ProgressDialogFragment dialogFragment = (ProgressDialogFragment) getSupportFragmentManager()
                        .findFragmentByTag(PROGRESS_DIALOG_FRAGMENT_TAG);
                if (dialogFragment != null)
                    dialogFragment.dismissAllowingStateLoss();
                String toastText = result ? getString(R.string.import_successful, uri.getPath())
                        : getString(R.string.import_failed, uri.getPath());
                Toast.makeText(PreferenceFragmentActivity.this, toastText, Toast.LENGTH_SHORT).show();
                finish();
            }
        };
        task.execute();
    } else if (actionId == ID_ACTION_LOCATION_SETTINGS) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
        finish();
    }
}

From source file:com.google.android.gcm.demo.logic.DeviceGroupsHelper.java

/**
 * Execute the HTTP call to delete a Device Group.
 *
 * This is obtained by removing all the members of the group.
 *//*from www . j a va 2 s.  c o m*/
public void asyncDeleteGroup(final String senderId, final String apiKey, final String groupName) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            Sender sender = mSenders.getSender(senderId);
            if (sender == null) {
                return null;
            }
            DeviceGroup group = sender.groups.get(groupName);
            if (group == null) {
                return null;
            }
            Bundle members2Remove = new Bundle();
            for (String name : group.tokens.keySet()) {
                members2Remove.putString(name, group.tokens.get(name));
            }
            if (members2Remove.size() > 0) {
                removeMembers(senderId, apiKey, groupName, group.notificationKey, members2Remove);
            }
            sender.groups.remove(group.notificationKeyName);
            mSenders.updateSender(sender);
            return null;
        }
    }.execute();
}

From source file:au.id.micolous.frogjump.Util.java

public static void sendGcmMessage(String action, @Nullable Bundle message_p) {
    final long message_id = rng.nextLong();
    final Bundle message;
    if (message_p == null) {
        message = new Bundle();
    } else {//from   w  ww.  j ava2 s. c  om
        message = new Bundle(message_p);
    }

    message.putString("a", action);
    message.putString("v", Integer.toString(getVersionCode()));

    FrogjumpApplication app = FrogjumpApplication.getInstance();
    final GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(app);

    final String gcm_to = app.getString(R.string.gcm_defaultSenderId) + "@gcm.googleapis.com";
    (new AsyncTask<Void, Void, Boolean>() {
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                gcm.send(gcm_to, Long.toString(message_id), message);
                return true;
            } catch (IOException ex) {
                Log.e(TAG, "sendGcmMessage fail", ex);
                return false;
            }
        }
    }).execute();
}

From source file:com.piusvelte.sonet.core.SonetNotifications.java

@Override
public boolean onContextItemSelected(final MenuItem item) {
    if (item.getItemId() == CLEAR) {
        final ProgressDialog loadingDialog = new ProgressDialog(this);
        final AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {

            @Override//from w  w w.j  a v  a  2 s.c  om
            protected Void doInBackground(Void... arg0) {
                // clear all notifications
                ContentValues values = new ContentValues();
                values.put(Notifications.CLEARED, 1);
                SonetNotifications.this.getContentResolver().update(
                        Notifications.getContentUri(SonetNotifications.this), values, Notifications._ID + "=?",
                        new String[] { Long.toString(((AdapterContextMenuInfo) item.getMenuInfo()).id) });
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                if (loadingDialog.isShowing()) {
                    loadingDialog.dismiss();
                }
                SonetNotifications.this.finish();
            }
        };
        loadingDialog.setMessage(getString(R.string.loading));
        loadingDialog.setCancelable(true);
        loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (!asyncTask.isCancelled())
                    asyncTask.cancel(true);
            }
        });
        loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        loadingDialog.show();
        asyncTask.execute();
    }
    return super.onContextItemSelected(item);
    // clear
}