Example usage for android.util Log getStackTraceString

List of usage examples for android.util Log getStackTraceString

Introduction

In this page you can find the example usage for android.util Log getStackTraceString.

Prototype

public static String getStackTraceString(Throwable tr) 

Source Link

Document

Handy function to get a loggable stack trace from a Throwable

Usage

From source file:com.capstonecontrol.AccountsActivity.java

/**
 * Retrieves the authorization cookie associated with the given token. This
 * method should only be used when running against a production appengine
 * backend (as opposed to a dev mode server).
 *///from  w w w  .  jav a 2s. co m
private String getAuthCookie(String authToken) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        // Get SACSID cookie
        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
        String uri = Setup.PROD_URL + "/_ah/login?continue=http://localhost/&auth=" + authToken;
        HttpGet method = new HttpGet(uri);

        HttpResponse res = httpClient.execute(method);
        StatusLine statusLine = res.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        Header[] headers = res.getHeaders("Set-Cookie");
        if (statusCode != 302 || headers.length == 0) {
            return null;
        }

        for (Cookie cookie : httpClient.getCookieStore().getCookies()) {
            if (AUTH_COOKIE_NAME.equals(cookie.getName())) {
                return AUTH_COOKIE_NAME + "=" + cookie.getValue();
            }
        }
    } catch (IOException e) {
        Log.w(TAG, "Got IOException " + e);
        Log.w(TAG, Log.getStackTraceString(e));
    } finally {
        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    }

    return null;
}

From source file:io.teak.sdk.Session.java

private void startHeartbeat() {
    final Session _this = this;

    this.heartbeatService = Executors.newSingleThreadScheduledExecutor();
    this.heartbeatService.scheduleAtFixedRate(new Runnable() {
        public void run() {
            if (Teak.isDebug) {
                Log.v(LOG_TAG, "Sending heartbeat for user: " + userId);
            }//from w  ww.j  av a 2 s.  c  o m

            HttpsURLConnection connection = null;
            try {
                String queryString = "game_id=" + URLEncoder.encode(_this.appConfiguration.appId, "UTF-8")
                        + "&api_key=" + URLEncoder.encode(_this.userId, "UTF-8") + "&sdk_version="
                        + URLEncoder.encode(Teak.SDKVersion, "UTF-8") + "&sdk_platform="
                        + URLEncoder.encode(_this.deviceConfiguration.platformString, "UTF-8") + "&app_version="
                        + URLEncoder.encode(String.valueOf(_this.appConfiguration.appVersion), "UTF-8")
                        + (_this.countryCode == null ? ""
                                : "&country_code="
                                        + URLEncoder.encode(String.valueOf(_this.countryCode), "UTF-8"))
                        + "&buster=" + URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
                URL url = new URL("https://iroko.gocarrot.com/ping?" + queryString);
                connection = (HttpsURLConnection) url.openConnection();
                connection.setRequestProperty("Accept-Charset", "UTF-8");
                connection.setUseCaches(false);

                int responseCode = connection.getResponseCode();
                if (Teak.isDebug) {
                    Log.v(LOG_TAG, "Heartbeat response code: " + responseCode);
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }
    }, 0, 1, TimeUnit.MINUTES); // TODO: If RemoteConfiguration specifies a different rate, use that
}

From source file:io.teak.sdk.TeakNotification.java

/**
 * Schedules a push notification for some time in the future.
 *
 * @param creativeId     The identifier of the notification in the Teak dashboard (will create if not found).
 * @param defaultMessage The default message to send, may be over-ridden in the dashboard.
 * @param delayInSeconds The delay in seconds from now to send the notification.
 * @return The identifier of the scheduled notification (see {@link TeakNotification#cancelNotification(String)} or null.
 *//*  www.  j  a  va 2s  .  c o  m*/
@SuppressWarnings("unused")
public static FutureTask<String> scheduleNotification(final String creativeId, final String defaultMessage,
        final long delayInSeconds) {
    if (!Teak.isEnabled()) {
        Log.e(LOG_TAG, "Teak is disabled, ignoring scheduleNotification().");
        return null;
    }

    if (creativeId == null || creativeId.isEmpty()) {
        Log.e(LOG_TAG, "creativeId cannot be null or empty");
        return null;
    }

    if (defaultMessage == null || defaultMessage.isEmpty()) {
        Log.e(LOG_TAG, "defaultMessage cannot be null or empty");
        return null;
    }

    final ArrayBlockingQueue<String> q = new ArrayBlockingQueue<>(1);
    final FutureTask<String> ret = new FutureTask<>(new Callable<String>() {
        public String call() {
            try {
                return q.take();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
            }
            return null;
        }
    });

    Session.whenUserIdIsReadyRun(new Session.SessionRunnable() {
        @Override
        public void run(Session session) {
            HashMap<String, Object> payload = new HashMap<>();
            payload.put("identifier", creativeId);
            payload.put("message", defaultMessage);
            payload.put("offset", delayInSeconds);

            new Request("/me/local_notify.json", payload, session) {
                @Override
                protected void done(int responseCode, String responseBody) {
                    try {
                        JSONObject response = new JSONObject(responseBody);
                        if (response.getString("status").equals("ok")) {
                            q.offer(response.getJSONObject("event").getString("id"));
                        } else {
                            q.offer("");
                        }
                    } catch (Exception ignored) {
                        q.offer("");
                    }

                    ret.run();
                }
            }.run();
        }
    });
    return ret;
}

From source file:org.alfresco.mobile.android.application.providers.storage.StorageAccessDocumentsProvider.java

@Override
public Cursor queryDocument(String documentId, String[] projection) throws FileNotFoundException {
    // Log.d(TAG, "Query Document : " + documentId);
    final DocumentFolderCursor docsCursor = new DocumentFolderCursor(resolveDocumentProjection(projection));
    Uri uri = DocumentsContract.buildDocumentUri(mAuthority, documentId);

    try {//from  www .  j a v a 2 s.c om
        EncodedQueryUri cUri = new EncodedQueryUri(documentId);
        // checkSession(cUri);

        if (cUri.id != null) {
            if (nodesIndex.containsKey(cUri.id)) {
                addNodeRow(docsCursor, nodesIndex.get(cUri.id));
            } else if (pathIndex.containsKey(cUri.id)) {
                addNodeRow(docsCursor, pathIndex.get(cUri.id));
            } else if (siteIndex.containsKey(cUri.id)) {
                addSiteRow(docsCursor, siteIndex.get(cUri.id));
            } else if (IMPORT_FOLDER_LIST.contains(cUri.id)) {
                addRootMenuRow(docsCursor, Integer.parseInt(cUri.id));
            }
        } else {
            // Log.d(TAG, "Default Row " + documentId);
            DocumentFolderCursor.RowBuilder row = docsCursor.newRow();
            row.add(Document.COLUMN_DOCUMENT_ID,
                    EncodedQueryUri.encodeItem(PREFIX_ACCOUNT, cUri.accountId, cUri.id));
            row.add(Document.COLUMN_DISPLAY_NAME, cUri.id);
            row.add(Document.COLUMN_SIZE, null);
            row.add(Document.COLUMN_LAST_MODIFIED, null);
            row.add(Document.COLUMN_MIME_TYPE, Document.MIME_TYPE_DIR);
            row.add(Document.COLUMN_ICON, null);
        }
    } catch (Exception e) {
        docsCursor.setErrorInformation("Error : " + e.getMessage());
        docsCursor.setNotificationUri(getContext().getContentResolver(), uri);
        getContext().getContentResolver().notifyChange(uri, null);
        Log.d(TAG, Log.getStackTraceString(e));
    }

    return docsCursor;
}

From source file:eu.operando.operandoapp.filters.response.ResponseFiltersActivity.java

protected void importExternalFilters(final String importUrl) {
    //String timestap = SimpleDateFormat.getDateTimeInstance().format(new Date().getTime());
    final File tmp = new File(getFilesDir(), "respfilters_" + System.currentTimeMillis());
    try {//from  ww  w .j a v a 2s . com
        new DownloadTask(ResponseFiltersActivity.this, new URL(importUrl), tmp, new DownloadTask.Listener() {
            @Override
            public void onCompleted() {
                Toast.makeText(ResponseFiltersActivity.this, R.string.msg_downloaded, Toast.LENGTH_LONG).show();

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

                    ProgressDialog dialog;

                    @Override
                    protected void onPreExecute() {
                        dialog = ProgressDialog.show(ResponseFiltersActivity.this, null,
                                "Parsing downloaded file...");
                        dialog.setCancelable(false);
                    }

                    @Override
                    protected Integer doInBackground(Void... params) {
                        int count = 0;
                        BufferedReader br = null;
                        try {
                            br = new BufferedReader(new FileReader(tmp));
                            String line;
                            while ((line = br.readLine()) != null) {
                                int hash = line.indexOf('#');
                                if (hash >= 0)
                                    line = line.substring(0, hash);
                                line = line.trim();

                                if (line.length() > 0) {
                                    ResponseFilter responseFilter = new ResponseFilter();
                                    responseFilter.setContent(line);
                                    responseFilter.setSource(importUrl);
                                    db.createResponseFilter(responseFilter);
                                    count++;
                                }
                            }
                            Log.i(TAG, count + " entries read");
                        } catch (IOException ex) {
                            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                        } finally {
                            if (br != null)
                                try {
                                    br.close();
                                } catch (IOException exex) {
                                    Log.e(TAG, exex.toString() + "\n" + Log.getStackTraceString(exex));
                                }
                        }

                        return count;
                    }

                    @Override
                    protected void onPostExecute(Integer count) {
                        dialog.dismiss();
                        if (count > 0) {
                            updateFiltersList();
                            externalResponseFiltersAdapter.notifyDataSetChanged();
                        }
                    }
                }.execute();

                //recyclerView.scrollToPosition(userFilters.size() - 1);
                //ServiceSinkhole.reload("hosts file download", ActivitySettings.this);
            }

            @Override
            public void onCancelled() {
                if (tmp.exists())
                    tmp.delete();
            }

            @Override
            public void onException(Throwable ex) {
                if (tmp.exists())
                    tmp.delete();

                ex.printStackTrace();
                Toast.makeText(ResponseFiltersActivity.this, ex.getMessage(), Toast.LENGTH_LONG).show();
            }
        }).execute();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Toast.makeText(ResponseFiltersActivity.this, ex.toString(), Toast.LENGTH_LONG).show();
    }
}

From source file:io.bunnyblue.noticedog.app.overlay.ui.OverlayNotificationBarView.java

private Drawable getActionIcon(String appId, int resourceId) {
    try {/*from   ww w.j av a 2 s.c o  m*/
        return this.context.getPackageManager()
                .getResourcesForApplication(this.appManager.getAppById(appId).getAppPackageName())
                .getDrawable(resourceId);
    } catch (NameNotFoundException nnfe) {
        Log.d(TAG, "Caught PackageManager.NameNotFoundException when loading resource: "
                + Log.getStackTraceString(nnfe));
        return null;
    } catch (Exception e) {
        Log.d(TAG, "Caught exception when loading resource: " + Log.getStackTraceString(e));
        return null;
    }
}

From source file:com.ibm.caas.JSONParser.java

/**
 * Parse the properties of the resulting items list, if they exist.
 * @param json the header JSON object which contains the list properties.
 * @return a {@link CAASContentItemsList} object containing the parsed list properties.
 *//*from  w  w  w .ja  va2 s. com*/
private CAASContentItemsList parseListProperties(JSONObject json) {
    CAASContentItemsList result = new CAASContentItemsList();
    Log.w(LOG_TAG, "in parseListProperties()");
    try {
        boolean hasProps = json.has("listProperties");
        //Log.w(LOG_TAG, "in parseListProperties() hasProps=" + hasProps);
        if (json.has("listProperties")) {
            JSONObject listProps = json.getJSONObject("listProperties");
            if (listProps.has("id")) {
                result.setOid(listProps.getString("id"));
                //Log.w(LOG_TAG, "in parseListProperties() id=" + result.getOid());
            }
            if (listProps.has("lastmodifieddate")) {
                String s = listProps.getString("lastmodifieddate");
                result.setLastModifiedDate((Date) Converter.DATE.convert(s));
                //Log.w(LOG_TAG, "in parseListProperties() lastModified=" + result.getLastModifiedDate());
            }
            if (listProps.has("pageSize")) {
                result.setPageSize(listProps.getInt("pageSize"));
                Log.w(LOG_TAG, "in parseListProperties() pageSize=" + result.getPageSize());
            }
            if (listProps.has("pageNumber")) {
                result.setPageNumber(listProps.getInt("pageNumber"));
                Log.w(LOG_TAG, "in parseListProperties() pageNumber=" + result.getPageNumber());
            }
            if (listProps.has("hasNext")) {
                result.setHasNextPage(listProps.getBoolean("hasNext"));
                Log.w(LOG_TAG, "in parseListProperties() hasNext=" + result.hasNextPage());
            }
        }
    } catch (Exception ignore) {
        // this doesn't prevent us from parsing the items
        Log.w(LOG_TAG, "exception in parseListProperties') : " + Log.getStackTraceString(ignore));
    }
    return result;
}

From source file:com.packetsender.android.PacketListenerService.java

@Override
protected void onHandleIntent(Intent intent) {

    dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0));

    listenportTCP = dataStore.getTCPPort();
    listenportUDP = dataStore.getUDPPort();
    Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP));

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startNotification();//ww  w.  j a  v a 2 s  . c o m

    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
    ByteBuffer response = null;
    try {
        response = encoder.encode(CharBuffer.wrap("response"));
    } catch (CharacterCodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {

        SocketAddress localportTCP = new InetSocketAddress(listenportTCP);
        SocketAddress localportUDP = new InetSocketAddress(listenportUDP);

        tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localportTCP);

        udpserver = DatagramChannel.open();
        udpserver.socket().bind(localportUDP);

        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        Selector selector = Selector.open();

        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
        receiveBuffer.clear();

        shutdownListener = new Runnable() {
            public void run() {

                if (false) {

                    try {
                        tcpserver.close();
                    } catch (IOException e) {
                    }
                    try {
                        udpserver.close();
                    } catch (IOException e) {
                    }
                    stopSelf();
                } else {
                    mHandler.postDelayed(shutdownListener, 2000);

                }

            }
        };

        sendListener = new Runnable() {
            public void run() {

                //Packet fetchedPacket = mDbHelper.needSendPacket();
                Packet[] fetchedPackets = dataStore.fetchAllServicePackets();

                if (fetchedPackets.length > 0) {
                    dataStore.clearServicePackets();
                    Log.d("service",
                            DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets"));

                    for (int i = 0; i < fetchedPackets.length; i++) {
                        Packet fetchedPacket = fetchedPackets[i];
                        Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString()));

                    }

                    new SendPacketsTask().execute(fetchedPackets);
                }

                mHandler.postDelayed(sendListener, 2000);

            }
        };

        //start shutdown listener
        mHandler.postDelayed(shutdownListener, 2000);

        //start send listener
        mHandler.postDelayed(sendListener, 5000);

        while (true) {
            try { // Handle per-connection problems below
                  // Wait for a client to connect
                Log.d("service", DataStorage.FILE_LINE("waiting for connection"));
                selector.select();
                Log.d("service", DataStorage.FILE_LINE("client connection"));

                Set keys = selector.selectedKeys();

                for (Iterator i = keys.iterator(); i.hasNext();) {

                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    Channel c = (Channel) key.channel();

                    if (key.isAcceptable() && c == tcpserver) {

                        SocketChannel client = tcpserver.accept();

                        if (client != null) {

                            Socket tcpSocket = client.socket();
                            packetCounter++;

                            DataInputStream in = new DataInputStream(tcpSocket.getInputStream());

                            byte[] buffer = new byte[1024];
                            int received = in.read(buffer);
                            byte[] bufferConvert = new byte[received];
                            System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "TCP";
                            storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = tcpSocket.getPort();
                            storepacket.port = tcpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            Log.i("service", DataStorage.FILE_LINE("Got TCP"));
                            //dataStore.SavePacket(storepacket);

                            /*
                            Intent tcpIntent = new Intent();
                            tcpIntent.setAction(ResponseReceiver.ACTION_RESP);
                            tcpIntent.addCategory(Intent.CATEGORY_DEFAULT);
                            tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name);
                            sendBroadcast(tcpIntent);
                            */

                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "TCP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = tcpSocket.getInetAddress().getHostAddress();
                                storepacket.fromPort = tcpSocket.getLocalPort();
                                storepacket.port = tcpSocket.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                                client.write(response); // send response
                            }

                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {

                        DatagramSocket udpSocket;
                        DatagramPacket udpPacket;

                        byte[] buffer = new byte[2048];
                        // Create a packet to receive data into the buffer
                        udpPacket = new DatagramPacket(buffer, buffer.length);

                        udpSocket = udpserver.socket();

                        receiveBuffer.clear();

                        InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer);

                        if (clientAddress != null) {

                            String fromAddress = clientAddress.getAddress().getHostAddress();

                            packetCounter++;

                            int received = receiveBuffer.position();
                            byte[] bufferConvert = new byte[received];

                            System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "UDP";
                            storepacket.fromIP = clientAddress.getAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = clientAddress.getPort();
                            storepacket.port = udpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            //dataStore.SavePacket(storepacket);
                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "UDP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = clientAddress.getAddress().getHostAddress();
                                storepacket.fromPort = udpSocket.getLocalPort();
                                storepacket.port = clientAddress.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                //dataStore.SavePacket(storepacket);
                                udpserver.send(response, clientAddress);
                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            }
                        }
                    }
                }
            } catch (java.io.IOException e) {
                Log.i("service", DataStorage.FILE_LINE("IOException "));
            } catch (Exception e) {
                Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e)));
            }
        }
    } catch (BindException e) {

        //mDbHelper.putServiceError("Error binding to port");
        dataStore.putToast("Port already in use.");
        Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e)));

    } catch (Exception e) {
        //mDbHelper.putServiceError("Fatal Error starting service");
        Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e)));
    }

    stopNotification();

}

From source file:com.tesobe.hello_obp.lib.OBPRestClient.java

public static boolean getAndSetAccessToken(Activity activity, String verifyCode) {
    try {/*ww  w  . j  a  v  a  2  s.  co  m*/
        provider.retrieveAccessToken(consumer, verifyCode);
        String token = consumer.getToken();
        String secret = consumer.getTokenSecret();
        if (token != null && secret != null) {
            Editor editor = activity.getSharedPreferences(PREF_FILE, Activity.MODE_PRIVATE).edit();
            editor.putString(CONSUMER_TOKEN, token);
            editor.putString(CONSUMER_SECRET, secret);
            return editor.commit();
        } else
            return false;
    } catch (OAuthMessageSignerException e) {
        Log.w(LOG_TAG, Log.getStackTraceString(e));
    } catch (OAuthNotAuthorizedException e) {
        Log.w(LOG_TAG, Log.getStackTraceString(e));
    } catch (OAuthExpectationFailedException e) {
        Log.w(LOG_TAG, Log.getStackTraceString(e));
    } catch (OAuthCommunicationException e) {
        Log.w(LOG_TAG, Log.getStackTraceString(e));
    }
    return false;
}

From source file:com.zhengde163.netguard.ActivitySettings.java

private void handleHosts(final Intent data) {
    new AsyncTask<Object, Object, Throwable>() {
        @Override//from  w  w w .j  a va  2  s.  com
        protected Throwable doInBackground(Object... objects) {
            File hosts = new File(getFilesDir(), "hosts.txt");

            FileOutputStream out = null;
            InputStream in = null;
            try {
                Log.i(TAG, "Reading URI=" + data.getData());
                in = getContentResolver().openInputStream(data.getData());
                out = new FileOutputStream(hosts);

                int len;
                long total = 0;
                byte[] buf = new byte[4096];
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                    total += len;
                }
                Log.i(TAG, "Copied bytes=" + total);

                return null;
            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                return ex;
            } finally {
                if (out != null)
                    try {
                        out.close();
                    } catch (IOException ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }
                if (in != null)
                    try {
                        in.close();
                    } catch (IOException ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }
            }
        }

        @Override
        protected void onPostExecute(Throwable ex) {
            if (running) {
                if (ex == null) {
                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(ActivitySettings.this);
                    String last = SimpleDateFormat.getDateTimeInstance().format(new Date().getTime());
                    prefs.edit().putString("hosts_last_import", last).apply();

                    if (running) {
                        getPreferenceScreen().findPreference("use_hosts").setEnabled(true);
                        Toast.makeText(ActivitySettings.this, R.string.msg_completed, Toast.LENGTH_LONG).show();
                    }

                    ServiceSinkhole.reload("hosts import", ActivitySettings.this);
                } else
                    Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
            }
        }
    }.execute();
}