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:eu.faircode.adblocker.ActivityMain.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));
    Util.logExtras(getIntent());/*w w  w. j  a va 2  s .c  o m*/

    if (Build.VERSION.SDK_INT < MIN_SDK) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.android);
        return;
    }

    Util.setTheme(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    swEnabled = (SwitchCompat) findViewById(R.id.swEnabled);
    running = true;

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean enabled = prefs.getBoolean("enabled", false);
    boolean initialized = prefs.getBoolean("initialized", false);

    // Upgrade
    Receiver.upgrade(initialized, this);

    if (!getIntent().hasExtra(EXTRA_APPROVE)) {
        if (enabled)
            ServiceSinkhole.start("UI", this);
        else
            ServiceSinkhole.stop("UI", this);
    }

    // Action bar
    final View actionView = getLayoutInflater().inflate(R.layout.actionmain, null, false);
    ivIcon = (ImageView) actionView.findViewById(R.id.ivIcon);
    ivQueue = (ImageView) actionView.findViewById(R.id.ivQueue);

    ivMetered = (ImageView) actionView.findViewById(R.id.ivMetered);

    // Icon
    ivIcon.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            menu_about();
            return true;
        }
    });

    // Title
    getSupportActionBar().setTitle(null);

    // Netguard is busy
    ivQueue.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            int location[] = new int[2];
            actionView.getLocationOnScreen(location);
            Toast toast = Toast.makeText(ActivityMain.this, R.string.msg_queue, Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP | Gravity.START, location[0] + ivQueue.getLeft(),
                    Math.round(location[1] + ivQueue.getBottom() - toast.getView().getPaddingTop()));
            toast.show();
            return true;
        }
    });

    // On/off switch
    swEnabled.setChecked(enabled);
    swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Log.i(TAG, "Switch=" + isChecked);
            prefs.edit().putBoolean("enabled", isChecked).apply();

            if (isChecked) {
                try {
                    final Intent prepare = VpnService.prepare(ActivityMain.this);
                    if (prepare == null) {
                        Log.i(TAG, "Prepare done");
                        onActivityResult(REQUEST_VPN, RESULT_OK, null);
                    } else {
                        // Show dialog
                        LayoutInflater inflater = LayoutInflater.from(ActivityMain.this);
                        View view = inflater.inflate(R.layout.vpn, null, false);
                        dialogVpn = new AlertDialog.Builder(ActivityMain.this).setView(view)
                                .setCancelable(false)
                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (running) {
                                            Log.i(TAG, "Start intent=" + prepare);
                                            try {
                                                startActivityForResult(prepare, REQUEST_VPN);
                                            } catch (Throwable ex) {
                                                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                                                Util.sendCrashReport(ex, ActivityMain.this);
                                                onActivityResult(REQUEST_VPN, RESULT_CANCELED, null);
                                                prefs.edit().putBoolean("enabled", false).apply();
                                            }
                                        }
                                    }
                                }).setOnDismissListener(new DialogInterface.OnDismissListener() {
                                    @Override
                                    public void onDismiss(DialogInterface dialogInterface) {
                                        dialogVpn = null;
                                    }
                                }).create();
                        dialogVpn.show();
                    }
                } catch (Throwable ex) {
                    // Prepare failed
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    Util.sendCrashReport(ex, ActivityMain.this);
                    prefs.edit().putBoolean("enabled", false).apply();
                }

            } else
                ServiceSinkhole.stop("switch off", ActivityMain.this);
        }
    });
    if (enabled)
        checkDoze();

    // Network is metered
    ivMetered.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            int location[] = new int[2];
            actionView.getLocationOnScreen(location);
            Toast toast = Toast.makeText(ActivityMain.this, R.string.msg_metered, Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP | Gravity.START, location[0] + ivMetered.getLeft(),
                    Math.round(location[1] + ivMetered.getBottom() - toast.getView().getPaddingTop()));
            toast.show();
            return true;
        }
    });

    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(actionView);

    // Disabled warning
    TextView tvDisabled = (TextView) findViewById(R.id.tvDisabled);
    tvDisabled.setVisibility(enabled ? View.GONE : View.VISIBLE);

    // Application list
    //        RecyclerView rvApplication = (RecyclerView) findViewById(R.id.rvApplication);
    //        rvApplication.setHasFixedSize(true);
    //        rvApplication.setLayoutManager(new LinearLayoutManager(this));
    //        adapter = new AdapterRule(this);
    //        rvApplication.setAdapter(adapter);

    // Swipe to refresh
    TypedValue tv = new TypedValue();
    getTheme().resolveAttribute(R.attr.colorPrimary, tv, true);
    //        swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh);
    //        swipeRefresh.setColorSchemeColors(Color.WHITE, Color.WHITE, Color.WHITE);
    //        swipeRefresh.setProgressBackgroundColorSchemeColor(tv.data);
    //        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    //            @Override
    //            public void onRefresh() {
    //                Rule.clearCache(ActivityMain.this);
    //                ServiceSinkhole.reload("pull", ActivityMain.this);
    //                updateApplicationList(null);
    //            }
    //        });

    // Listen for preference changes
    prefs.registerOnSharedPreferenceChangeListener(this);

    // Listen for rule set changes
    IntentFilter ifr = new IntentFilter(ACTION_RULES_CHANGED);
    LocalBroadcastManager.getInstance(this).registerReceiver(onRulesChanged, ifr);

    // Listen for queue changes
    IntentFilter ifq = new IntentFilter(ACTION_QUEUE_CHANGED);
    LocalBroadcastManager.getInstance(this).registerReceiver(onQueueChanged, ifq);

    // Listen for added/removed applications
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
    intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    intentFilter.addDataScheme("package");
    registerReceiver(packageChangedReceiver, intentFilter);

    // First use
    if (!initialized) {
        // Create view
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.first, null, false);
        TextView tvFirst = (TextView) view.findViewById(R.id.tvFirst);
        tvFirst.setMovementMethod(LinkMovementMethod.getInstance());

        // Show dialog
        dialogFirst = new AlertDialog.Builder(this).setView(view).setCancelable(false)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (running)
                            prefs.edit().putBoolean("initialized", true).apply();
                    }
                }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (running)
                            finish();
                    }
                }).setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        dialogFirst = null;
                    }
                }).create();
        dialogFirst.show();
    }

    // Fill application list
    updateApplicationList(getIntent().getStringExtra(EXTRA_SEARCH));

    // Update IAB SKUs
    try {
        iab = new IAB(new IAB.Delegate() {
            @Override
            public void onReady(IAB iab) {
                try {
                    iab.updatePurchases();

                    if (!IAB.isPurchased(ActivityPro.SKU_LOG, ActivityMain.this))
                        prefs.edit().putBoolean("log", false).apply();
                    if (!IAB.isPurchased(ActivityPro.SKU_THEME, ActivityMain.this)) {
                        if (!"teal".equals(prefs.getString("theme", "teal")))
                            prefs.edit().putString("theme", "teal").apply();
                    }
                    if (!IAB.isPurchased(ActivityPro.SKU_SPEED, ActivityMain.this))
                        prefs.edit().putBoolean("show_stats", false).apply();
                } catch (Throwable ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                } finally {
                    iab.unbind();
                }
            }
        }, this);
        iab.bind();
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    checkExtras(getIntent());
}

From source file:com.hly.component.download.DownloadTransaction.java

public void run() {
    // TODO ?Daemon
    InputStream is = null;//from   ww  w.  ja  va 2s.  c o  m
    HttpURLConnection conn = null;
    RandomAccessFile randomFile = null;
    File tmpFile = null;
    try {
        // ?uri
        tmpFile = new File(mTempLocalUri);
        File parentFile = tmpFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        if (!tmpFile.exists()) {
            tmpFile.createNewFile();
        }
        randomFile = new RandomAccessFile(mTempLocalUri, "rw");
        long fileLength = randomFile.length();
        completeSize = fileLength;

        if (isCancel) {
            return;
        }
        String connUrl = mUri;
        // ?uri????
        // getRedirectUrl(connUrl);
        if (!T.ckIsEmpty(mRedirectUri)) {
            connUrl = mRedirectUri;
        }
        conn = getHttpConnetion(connUrl);
        conn.setRequestProperty("range", "bytes=" + fileLength + "-");
        conn.connect();

        int contentLength = conn.getContentLength();
        totalSize = completeSize + contentLength;
        if (contentLength == -1 || contentLength > 0) {
            //    
            randomFile.seek(fileLength);
            byte[] buffer = new byte[8192];
            is = conn.getInputStream();
            int length = -1;
            while ((length = is.read(buffer)) != -1) {
                if (isCancel) {
                    return;
                }
                randomFile.write(buffer, 0, length);
                completeSize += length;
                notifyProgress(length);
            }
        }
        mTransactionState.setState(TransactionState.SUCCESS);
    } catch (Throwable t) {
        Log.w(TAG, Log.getStackTraceString(t));
    } finally {
        isRunning = false;
        isCancel = false;
        try {
            if (randomFile != null) {
                randomFile.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            conn.disconnect();
        }

        if (mTransactionState.getState() != TransactionState.SUCCESS) {
            mTransactionState.setState(TransactionState.FAILED);
            Log.e(TAG, "Delivery failed.");
        } else {
            if (tmpFile == null) {
                mTransactionState.setState(TransactionState.FAILED);
            } else {
                File localFile = new File(this.mLocalUri);
                boolean flag = tmpFile.renameTo(localFile);
                if (flag) {
                    Log.d(TAG, "rename pic succ" + this.mLocalUri);
                } else {
                    mTransactionState.setState(TransactionState.FAILED);
                    Log.d(TAG, "rename pic failed" + this.mLocalUri);
                }
            }
        }
        notifyObservers();
    }
}

From source file:eu.faircode.netguard.ServiceSinkhole.java

public static void setPcap(boolean enabled, Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    int record_size = 64;
    try {//from   w  w  w  . j ava  2s .  c om
        String r = prefs.getString("pcap_record_size", null);
        if (TextUtils.isEmpty(r))
            r = "64";
        record_size = Integer.parseInt(r);
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    int file_size = 2 * 1024 * 1024;
    try {
        String f = prefs.getString("pcap_file_size", null);
        if (TextUtils.isEmpty(f))
            f = "2";
        file_size = Integer.parseInt(f) * 1024 * 1024;
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    File pcap = (enabled ? new File(context.getDir("data", MODE_PRIVATE), "netguard.pcap") : null);
    jni_pcap(pcap == null ? null : pcap.getAbsolutePath(), record_size, file_size);
}

From source file:net.olejon.mdapp.NotesEditActivity.java

private void getNote() {
    if (noteId != 0) {
        SQLiteDatabase sqLiteDatabase = new NotesSQLiteHelper(mContext).getReadableDatabase();

        String[] queryColumns = { NotesSQLiteHelper.COLUMN_TITLE, NotesSQLiteHelper.COLUMN_TEXT,
                NotesSQLiteHelper.COLUMN_PATIENT_ID, NotesSQLiteHelper.COLUMN_PATIENT_NAME,
                NotesSQLiteHelper.COLUMN_PATIENT_DOCTOR, NotesSQLiteHelper.COLUMN_PATIENT_DEPARTMENT,
                NotesSQLiteHelper.COLUMN_PATIENT_ROOM, NotesSQLiteHelper.COLUMN_PATIENT_MEDICATIONS };
        Cursor cursor = sqLiteDatabase.query(NotesSQLiteHelper.TABLE, queryColumns,
                NotesSQLiteHelper.COLUMN_ID + " = " + noteId, null, null, null, null);

        if (cursor.moveToFirst()) {
            String title = cursor.getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_TITLE));
            String text = cursor.getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_TEXT));
            String patientId = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_ID));
            String patientName = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_NAME));
            String patientDoctor = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_DOCTOR));
            String patientDepartment = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_DEPARTMENT));
            String patientRoom = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_ROOM));
            String patientMedications = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_MEDICATIONS));

            mTitleEditText.setText(title);
            mTextEditText.setText(text);
            mPatientIdEditText.setText(patientId);
            mPatientNameEditText.setText(patientName);
            mPatientDoctorEditText.setText(patientDoctor);
            mPatientDepartmentEditText.setText(patientDepartment);
            mPatientRoomEditText.setText(patientRoom);

            if (patientMedications != null && !patientMedications.equals("")) {
                try {
                    mPatientMedicationsJsonArray = new JSONArray(patientMedications);

                    getMedications();// w  w w.  j a va 2  s .  co  m
                } catch (Exception e) {
                    Log.e("NotesEditActivity", Log.getStackTraceString(e));
                }
            }
        }

        cursor.close();
        sqLiteDatabase.close();
    }
}

From source file:org.pixmob.freemobile.netstat.SyncServiceTesting.java

private void run(Intent intent, final SQLiteDatabase db) throws Exception {
    final long now = dateAtMidnight(System.currentTimeMillis());

    Log.i(TAG, "Initializing statistics before uploading");

    final LongSparseArray<DailyStat> stats = new LongSparseArray<>(15);
    final Set<Long> uploadedStats = new HashSet<>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor pendingUploadsCursor = null;
    try {// w w  w  .  j a  va2s  .c  om
        pendingUploadsCursor = db.query("daily_stat_testing",
                new String[] { "stat_timestamp", "orange", "free_mobile", "free_mobile_3g", "free_mobile_4g",
                        "free_mobile_femtocell", "sync" },
                "stat_timestamp>=? AND stat_timestamp<?",
                new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
        while (pendingUploadsCursor.moveToNext()) {
            final long d = pendingUploadsCursor.getLong(0);
            final int sync = pendingUploadsCursor.getInt(6);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = pendingUploadsCursor.getInt(1);
                s.freeMobile = pendingUploadsCursor.getInt(2);
                s.freeMobile3G = pendingUploadsCursor.getInt(3);
                s.freeMobile4G = pendingUploadsCursor.getInt(4);
                s.freeMobileFemtocell = pendingUploadsCursor.getInt(5);
                stats.put(d, s);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    } finally {
        try {
            if (pendingUploadsCursor != null)
                pendingUploadsCursor.close();
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

    // Compute missing uploads.
    final ContentValues cv = new ContentValues();
    db.beginTransaction();
    try {
        for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) {
            if (stats.get(d) == null && !uploadedStats.contains(d)) {
                final DailyStat s = computeDailyStat(d);
                cv.put("stat_timestamp", d);
                cv.put("orange", s.orange);
                cv.put("free_mobile", s.freeMobile);
                cv.put("free_mobile_3g", s.freeMobile3G);
                cv.put("free_mobile_4g", s.freeMobile4G);
                cv.put("free_mobile_femtocell", s.freeMobileFemtocell);
                cv.put("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat_testing", null, cv);
                stats.put(d, s);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    // Delete old statistics.
    if (DEBUG) {
        Log.d(TAG, "Cleaning up upload database");
    }
    db.delete("daily_stat_testing", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) });

    // Check if there are any statistics to upload.
    final int statsLen = stats.size();
    if (statsLen == 0) {
        Log.i(TAG, "Nothing to upload");
        return;
    }

    // Check if the remote server is up.
    final HttpClient client = createHttpClient();
    try {
        client.head(createServerUrl(null)).execute();
    } catch (HttpClientException e) {
        Log.w(TAG, "Remote server is not available: cannot upload statistics", e);
        return;
    }

    // Upload statistics.
    Log.i(TAG, "Uploading statistics");
    final JSONObject json = new JSONObject();
    final String deviceId = getDeviceId();
    final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false);
    for (int i = 0; i < statsLen; ++i) {
        final long d = stats.keyAt(i);
        final DailyStat s = stats.get(d);

        try {
            json.put("timeOnOrange", s.orange);
            json.put("timeOnFreeMobile", s.freeMobile);
            json.put("timeOnFreeMobile3g", s.freeMobile3G);
            json.put("timeOnFreeMobile4g", s.freeMobile4G);
            json.put("timeOnFreeMobileFemtocell", s.freeMobileFemtocell);
        } catch (JSONException e) {
            final IOException ioe = new IOException("Failed to prepare statistics upload");
            ioe.initCause(e);
            throw ioe;
        }

        final String url = createServerUrl(
                "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d));
        if (DEBUG) {
            Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url);
        }

        final byte[] rawJson = json.toString().getBytes("UTF-8");
        try {
            client.post(url).content(rawJson, "application/json")
                    .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND)
                    .to(new HttpResponseHandler() {
                        @Override
                        public void onResponse(HttpResponse response) throws Exception {
                            final int sc = response.getStatusCode();
                            if (HttpURLConnection.HTTP_NOT_FOUND == sc) {
                                // Check if the device has just been
                                // registered.
                                if (deviceWasRegistered) {
                                    throw new IOException("Failed to upload statistics");
                                } else {
                                    // Got 404: the device does not exist.
                                    // We need to register this device.
                                    registerDevice(deviceId);

                                    // Restart this service.
                                    startService(new Intent(getApplicationContext(), SyncServiceTesting.class)
                                            .putExtra(EXTRA_DEVICE_REG, true));
                                }
                            } else if (HttpURLConnection.HTTP_OK == sc) {
                                // Update upload database.
                                cv.clear();
                                cv.put("sync", SYNC_UPLOADED);
                                db.update("daily_stat_testing", cv, "stat_timestamp=?",
                                        new String[] { String.valueOf(d) });

                                if (DEBUG) {
                                    Log.d(TAG, "Upload done for " + DateUtils.formatDate(d));
                                }
                            }
                        }
                    }).execute();
        } catch (HttpClientException e) {
            final IOException ioe = new IOException("Failed to send request with statistics");
            ioe.initCause(e);
            throw ioe;
        }
    }
}

From source file:org.proninyaroslav.libretorrent.fragments.DetailTorrentFragment.java

@Override
public void onDestroy() {
    super.onDestroy();

    if (bound) {/* ww w.  j  av a 2s. c o  m*/
        try {
            ipc.sendClientDisconnect(serviceCallback, clientCallback);

        } catch (RemoteException e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
        getActivity().unbindService(connection);

        bound = false;
    }
}

From source file:com.dm.material.dashboard.candybar.helpers.IconsHelper.java

public static void selectIcon(@NonNull Context context, int action, Icon icon) {
    if (action == IntentHelper.ICON_PICKER) {
        Intent intent = new Intent();
        Bitmap bitmap = ImageLoader.getInstance().loadImageSync("drawable://" + icon.getRes(),
                ImageConfig.getRawImageOptions().build());

        intent.putExtra("icon", bitmap);
        ((AppCompatActivity) context).setResult(bitmap != null ? Activity.RESULT_OK : Activity.RESULT_CANCELED,
                intent);/*w  w  w . j  a v  a 2  s.co m*/
        ((AppCompatActivity) context).finish();
    } else if (action == IntentHelper.IMAGE_PICKER) {
        Intent intent = new Intent();
        Bitmap bitmap = ImageLoader.getInstance().loadImageSync("drawable://" + icon.getRes(),
                ImageConfig.getRawImageOptions().build());
        if (bitmap != null) {
            File file = new File(context.getCacheDir(), icon.getTitle() + ".png");
            FileOutputStream outStream;
            try {
                outStream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                outStream.flush();
                outStream.close();

                Uri uri = FileHelper.getUriFromFile(context, context.getPackageName(), file);
                if (uri == null)
                    uri = Uri.fromFile(file);
                intent.putExtra(Intent.EXTRA_STREAM, uri);
                intent.setData(uri);
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } catch (Exception | OutOfMemoryError e) {
                LogUtil.e(Log.getStackTraceString(e));
            }
            intent.putExtra("return-data", false);
        }
        ((AppCompatActivity) context).setResult(bitmap != null ? Activity.RESULT_OK : Activity.RESULT_CANCELED,
                intent);
        ((AppCompatActivity) context).finish();
    } else {
        IconPreviewFragment.showIconPreview(((AppCompatActivity) context).getSupportFragmentManager(),
                icon.getTitle(), icon.getRes());
    }
}

From source file:eu.faircode.netguard.SinkholeService.java

private void startDebug(final ParcelFileDescriptor pfd) {
    if (!debug)/*w w  w.ja  v a 2  s.co m*/
        return;

    thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                FileInputStream in = new FileInputStream(pfd.getFileDescriptor());
                FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor());

                ByteBuffer buffer = ByteBuffer.allocate(32767);
                buffer.order(ByteOrder.BIG_ENDIAN);

                Log.i(TAG, "Start receiving");
                while (!Thread.currentThread().isInterrupted() && pfd.getFileDescriptor() != null
                        && pfd.getFileDescriptor().valid())
                    try {
                        buffer.clear();
                        int length = in.read(buffer.array());
                        if (length > 0) {
                            buffer.limit(length);
                            Packet pkt = new Packet(buffer);

                            if (pkt.IPv4.protocol == Packet.IPv4Header.TCP && pkt.TCP.SYN) {
                                int uid = pkt.getUid4();
                                if (uid < 0)
                                    Log.w(TAG, "uid not found");

                                String[] pkg = getPackageManager().getPackagesForUid(uid);
                                if (pkg == null)
                                    pkg = new String[] { uid == 0 ? "root" : "unknown" };

                                Log.i(TAG, "Connect " + pkt.IPv4.destinationAddress + ":"
                                        + pkt.TCP.destinationPort + " uid=" + uid + " pkg=" + pkg[0]);

                                // Send RST
                                pkt.swapAddresses();
                                pkt.TCP.clearFlags();
                                pkt.TCP.RST = true;
                                long ack = pkt.TCP.acknowledgementNumber;
                                pkt.TCP.acknowledgementNumber = (pkt.TCP.sequenceNumber + 1) & 0xFFFFFFFFL;
                                pkt.TCP.sequenceNumber = (ack + 1) & 0xFFFFFFFFL;
                                pkt.send(out);
                            }
                        }
                    } catch (Throwable ex) {
                        Log.e(TAG, ex.toString());
                    }
                Log.i(TAG, "End receiving");
            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        }
    });
    thread.start();
}

From source file:com.dm.material.dashboard.candybar.fragments.IconsBaseFragment.java

private void getIcons() {
    mGetIcons = new AsyncTask<Void, Void, Boolean>() {

        @Override/*from  w  w  w  . j  a  v  a2  s .  c om*/
        protected void onPreExecute() {
            super.onPreExecute();
            mProgress.setVisibility(View.VISIBLE);
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            while (!isCancelled()) {
                try {
                    Thread.sleep(1);
                    if (CandyBarMainActivity.sSections == null) {
                        CandyBarMainActivity.sSections = IconsHelper.getIconsList(getActivity());
                        CandyBarMainActivity.sIconsCount = 0;

                        for (int i = 0; i < CandyBarMainActivity.sSections.size(); i++) {
                            List<Icon> icons = CandyBarMainActivity.sSections.get(i).getIcons();
                            CandyBarMainActivity.sIconsCount += icons.size();

                            if (getActivity().getResources().getBoolean(R.bool.show_icon_name)) {
                                for (Icon icon : icons) {
                                    boolean replacer = getActivity().getResources()
                                            .getBoolean(R.bool.enable_icon_name_replacer);
                                    String name = IconsHelper.replaceName(getActivity(), replacer,
                                            icon.getTitle());
                                    icon.setTitle(name);
                                }
                            }

                            if (getActivity().getResources().getBoolean(R.bool.enable_icons_sort)) {
                                Collections.sort(icons, new AlphanumComparator() {
                                    @Override
                                    public int compare(Object o1, Object o2) {
                                        String s1 = ((Icon) o1).getTitle();
                                        String s2 = ((Icon) o2).getTitle();
                                        return super.compare(s1, s2);
                                    }
                                });

                                CandyBarMainActivity.sSections.get(i).setIcons(icons);
                            }
                        }
                    }
                    return true;
                } catch (Exception e) {
                    LogUtil.e(Log.getStackTraceString(e));
                    return false;
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            mProgress.setVisibility(View.GONE);
            if (aBoolean) {
                setHasOptionsMenu(true);
                PagerIconsAdapter adapter = new PagerIconsAdapter(getChildFragmentManager(),
                        CandyBarMainActivity.sSections);
                mPager.setAdapter(adapter);

                updateTabTypeface();
            } else {
                Toast.makeText(getActivity(), R.string.icons_load_failed, Toast.LENGTH_LONG).show();
            }

            mGetIcons = null;
        }
    }.execute();
}

From source file:info.papdt.blacklight.support.Utility.java

public static View findActionSpinner(Activity activity) {
    ActionBar action = activity.getActionBar();

    // Get ActionBarImpl class for ActionView object
    // Then get spinner from ActionView
    try {//  www  .j a v  a 2  s. c  o m
        Class<?> clazz = Class.forName("com.android.internal.app.ActionBarImpl");
        Field f = clazz.getDeclaredField("mActionView");
        f.setAccessible(true);
        Object actionView = f.get(action);
        clazz = Class.forName("com.android.internal.widget.ActionBarView");
        f = clazz.getDeclaredField("mSpinner");
        f.setAccessible(true);
        return (View) f.get(actionView);
    } catch (Exception e) {
        if (DEBUG) {
            Log.e(TAG, "Failed to find spinner");
            Log.e(TAG, Log.getStackTraceString(e));
        }

        return null;
    }
}