timber.log.Timber Java Examples

The following examples show how to use timber.log.Timber. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: updateComicDatabase.java    From Easy_xkcd with Apache License 2.0 6 votes vote down vote up
void createNoMediaFile() {
    if (!prefHelper.nomediaCreated()) {
        File sdCard = prefHelper.getOfflinePath();
        File dir = new File(sdCard.getAbsolutePath() + "/easy xkcd/");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File nomedia = new File(dir, ".nomedia");
        try {
            boolean created = nomedia.createNewFile();
            Timber.d("created .nomedia in external storage: %s", created);
            prefHelper.setNomediaCreated();
        } catch (IOException e) {
            Timber.e(e);
        }
    }
}
 
Example #2
Source File: DebugView.java    From u2020 with Apache License 2.0 6 votes vote down vote up
/**
 * Populates a {@code Spinner} with the values of an {@code enum} and binds it to the value set
 * in
 * the mock service.
 */
private <T extends Enum<T>> void configureResponseSpinner(Spinner spinner,
    final Class<T> responseClass) {
  final EnumAdapter<T> adapter = new EnumAdapter<>(getContext(), responseClass);
  spinner.setEnabled(isMockMode);
  spinner.setAdapter(adapter);
  spinner.setSelection(mockResponseSupplier.get(responseClass).ordinal());

  RxAdapterView.itemSelections(spinner)
      .map(adapter::getItem)
      .filter(item -> item != mockResponseSupplier.get(responseClass))
      .subscribe(selected -> {
        Timber.d("Setting %s to %s", responseClass.getSimpleName(), selected);
        mockResponseSupplier.set(selected);
      });
}
 
Example #3
Source File: WearListenerService.java    From wear-notify-for-reddit with Apache License 2.0 6 votes vote down vote up
private void getComments(String permalink) {
    mRedditService.comments(permalink, "best")
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(comments -> {
                if (comments == null) {
                    mAnalytics.sendEvent(Logger.LOG_EVENT_GET_COMMENTS,
                            Logger.LOG_EVENT_FAILURE);
                    sendToPath(mGoogleApiClient, Constants.PATH_GET_COMMENTS_RESULT_FAILED);
                } else {
                    sendComments(comments);
                    mAnalytics.sendEvent(Logger.LOG_EVENT_GET_COMMENTS,
                            Logger.LOG_EVENT_SUCCESS);
                }
            }, throwable -> {
                Timber.e(throwable, "Failed to get comments");
                mAnalytics.sendEvent(Logger.LOG_EVENT_GET_COMMENTS, Logger.LOG_EVENT_FAILURE);
                sendToPath(mGoogleApiClient, Constants.PATH_GET_COMMENTS_RESULT_FAILED);
            });
}
 
Example #4
Source File: DefaultMiscActions.java    From under-the-hood with Apache License 2.0 6 votes vote down vote up
/**
 * Kills all associated processes
 */
public static void killProcessesAround(Activity activity) {
    try {
        ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
        String myProcessPrefix = activity.getApplicationInfo().processName;
        String myProcessName = activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0).processName;
        for (ActivityManager.RunningAppProcessInfo proc : am.getRunningAppProcesses()) {
            if (proc.processName.startsWith(myProcessPrefix) && !proc.processName.equals(myProcessName)) {
                android.os.Process.killProcess(proc.pid);
            }
        }
    } catch (Exception e) {
        Timber.e(e, "could not kill process");
    } finally {
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
 
Example #5
Source File: BluetoothCentral.java    From blessed-android with MIT License 6 votes vote down vote up
/**
 * Make the pairing popup appear in the foreground by doing a 1 sec discovery.
 * <p>
 * If the pairing popup is shown within 60 seconds, it will be shown in the foreground.
 */
public void startPairingPopupHack() {
    // Check if we are on a Samsung device because those don't need the hack
    String manufacturer = Build.MANUFACTURER;
    if (!manufacturer.equals("samsung")) {
        bluetoothAdapter.startDiscovery();

        callBackHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Timber.d("popup hack completed");
                bluetoothAdapter.cancelDiscovery();
            }
        }, 1000);
    }
}
 
Example #6
Source File: VoiceActivity.java    From africastalking-android with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_voice_dialpad);

    ButterKnife.bind(this);
    callBtn.setEnabled(false);

    try {
        Timber.i("Setting up pjsip....");
        AfricasTalking.initializeVoiceService(this, mRegListener, new Callback<VoiceService>() {
            @Override
            public void onSuccess(VoiceService service) {
                mService = service;
            }

            @Override
            public void onFailure(Throwable throwable) {
                Timber.e(throwable.getMessage());
            }
        });
    } catch (Exception ex) {
        Timber.e(ex.getMessage());
    }

}
 
Example #7
Source File: DebounceSearchEmitterFragment.java    From RxJava-Android-Samples with Apache License 2.0 6 votes vote down vote up
private DisposableObserver<TextViewTextChangeEvent> _getSearchObserver() {
  return new DisposableObserver<TextViewTextChangeEvent>() {
    @Override
    public void onComplete() {
      Timber.d("--------- onComplete");
    }

    @Override
    public void onError(Throwable e) {
      Timber.e(e, "--------- Woops on error!");
      _log("Dang error. check your logs");
    }

    @Override
    public void onNext(TextViewTextChangeEvent onTextChangeEvent) {
      _log(format("Searching for %s", onTextChangeEvent.text().toString()));
    }
  };
}
 
Example #8
Source File: AlexaCommandManagerImpl.java    From mirror with Apache License 2.0 6 votes vote down vote up
@Override
public void doAuthentication() {
    mAlexaManager.logIn(new AuthorizationCallback() {
        @Override
        public void onCancel() {
        }

        @Override
        public void onSuccess() {
            mEnabled = true;
        }

        @Override
        public void onError(Exception e) {
            mEnabled = false;
            Timber.e(e, "Error trying to login to amazon");
        }
    });
}
 
Example #9
Source File: RandomContentController.java    From CodePolitan with Apache License 2.0 6 votes vote down vote up
public void loadRandomTag()
{
    presenter.showLoading();
    CodePolitanApi.pluck()
            .getApi()
            .getTags(BenihUtils.randInt(1, 5))
            .compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.IO))
            .flatMap(tagListResponse -> Observable.just(tagListResponse.getResult()))
            .map(tags -> tags.get(BenihUtils.randInt(0, tags.size() - 1)))
            .subscribe(tag -> {
                this.tag = tag;
                if (presenter != null)
                {
                    presenter.showRandomTag(tag);
                    presenter.dismissLoading();
                }
            }, throwable -> {
                if (presenter != null)
                {
                    Timber.d(throwable.getMessage());
                    presenter.showError(new Throwable(ErrorEvent.LOAD_RANDOM_TAG));
                    presenter.dismissLoading();
                }
            });
}
 
Example #10
Source File: BluetoothPeripheral.java    From blessed-android with MIT License 6 votes vote down vote up
/**
 * Request a different connection priority.
 * <p>
 * Use the standard parameters for Android: CONNECTION_PRIORITY_BALANCED, CONNECTION_PRIORITY_HIGH, or CONNECTION_PRIORITY_LOW_POWER. There is no callback for this function.
 *
 * @param priority the requested connection priority
 * @return true if request was enqueued, false if not
 */
public boolean requestConnectionPriority(final int priority) {

    // Enqueue the request connection priority command and complete is immediately as there is no callback for it
    boolean result = commandQueue.add(new Runnable() {
        @Override
        public void run() {
            if (isConnected()) {
                if (!bluetoothGatt.requestConnectionPriority(priority)) {
                    Timber.e("could not set connection priority");
                } else {
                    Timber.d("requesting connection priority %d", priority);
                }
                completedCommand();
            }
        }
    });

    if (result) {
        nextCommand();
    } else {
        Timber.e("could not enqueue request connection priority command");
    }
    return result;
}
 
Example #11
Source File: PitchPresenter.java    From Android-Guitar-Tuner with Apache License 2.0 6 votes vote down vote up
public void startPlayingNote(final double noteFrequency) {
    pitchPlayerDisposable = pitchPlayer.startPlaying(noteFrequency)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(() -> {
            }, error -> {
                Timber.e(error, "Error Starting Pitch Playback.");

                boolean showAction = retryCount < RETRY_COUNT_MAX;
                int description = showAction ? R.string.pitch_player_error_playing_note_description_with_action
                        : R.string.pitch_player_error_playing_note_description_without_action;

                view.onErrorPlayingNote(
                        description,
                        showAction,
                        R.string.pitch_player_error_playing_note_action,
                        R.color.snack_bar_action_color
                );
            });
}
 
Example #12
Source File: MainActivity.java    From openshop.io-android with MIT License 6 votes vote down vote up
/**
     * Method clear fragment backStack (back history). On bottom of stack will remain Fragment added by {@link #addInitialFragment()}.
     */
    private void clearBackStack() {
        Timber.d("Clearing backStack");
        FragmentManager manager = getSupportFragmentManager();
        if (manager.getBackStackEntryCount() > 0) {
            if (BuildConfig.DEBUG) {
                for (int i = 0; i < manager.getBackStackEntryCount(); i++) {
                    Timber.d("BackStack content_%d= id: %d, name: %s", i, manager.getBackStackEntryAt(i).getId(), manager.getBackStackEntryAt(i).getName());
                }
            }
            FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
            manager.popBackStackImmediate(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
        Timber.d("backStack cleared.");
//        TODO maybe implement own fragment backStack handling to prevent banner fragment recreation during clearing.
//        http://stackoverflow.com/questions/12529499/problems-with-android-fragment-back-stack
    }
 
Example #13
Source File: SplashActivity.java    From openshop.io-android with MIT License 6 votes vote down vote up
/**
 * Load available shops from server.
 */
private void requestShops() {
    if (layoutIntroScreen.getVisibility() != View.VISIBLE)
        progressDialog.show();
    GsonRequest<ShopResponse> getShopsRequest = new GsonRequest<>(Request.Method.GET, EndPoints.SHOPS, null, ShopResponse.class,
            new Response.Listener<ShopResponse>() {
                @Override
                public void onResponse(@NonNull ShopResponse response) {
                    Timber.d("Get shops response: %s", response.toString());
                    setSpinShops(response.getShopList());
                    if (progressDialog != null) progressDialog.cancel();
                    animateContentVisible();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (progressDialog != null) progressDialog.cancel();
            MsgUtils.logAndShowErrorMessage(activity, error);
            finish();
        }
    });
    getShopsRequest.setRetryPolicy(MyApplication.getDefaultRetryPolice());
    getShopsRequest.setShouldCache(false);
    MyApplication.getInstance().addToRequestQueue(getShopsRequest, CONST.SPLASH_REQUESTS_TAG);
}
 
Example #14
Source File: EventDiskCache.java    From matomo-sdk-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@NonNull
public synchronized List<Event> uncache() {
    List<Event> events = new ArrayList<>();
    if (!isCachingEnabled()) return events;

    long startTime = System.currentTimeMillis();
    while (!mEventContainer.isEmpty()) {
        File head = mEventContainer.poll();
        if (head != null) {
            events.addAll(readEventFile(head));
            if (!head.delete()) Timber.tag(TAG).e("Failed to delete cache container %s", head.getPath());
        }
    }

    checkCacheLimits();

    long stopTime = System.currentTimeMillis();
    Timber.tag(TAG).d("Uncaching of %d events took %dms", events.size(), (stopTime - startTime));
    return events;
}
 
Example #15
Source File: ScaleMeasurement.java    From openScale with GNU General Public License v3.0 6 votes vote down vote up
public void add(final ScaleMeasurement summand) {
    try {
        Field[] fields = getClass().getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            Object value = field.get(this);

            if (value != null && Float.class.isAssignableFrom(value.getClass())) {
                field.set(this, (float)value + (float)field.get(summand));
            }
            field.setAccessible(false);
        }

        count++;
    } catch (IllegalAccessException e) {
        Timber.e(e);
    }
}
 
Example #16
Source File: KeyStoreHelper.java    From xmrwallet with Apache License 2.0 6 votes vote down vote up
private static PrivateKey getPrivateKey(String alias) {
    try {
        KeyStore ks = KeyStore
                .getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
        ks.load(null);
        //KeyStore.Entry entry = ks.getEntry(alias, null);
        PrivateKey privateKey = (PrivateKey) ks.getKey(alias, null);

        if (privateKey == null) {
            Timber.w("No key found under alias: %s", alias);
            return null;
        }

        return privateKey;
    } catch (IOException | NoSuchAlgorithmException | CertificateException
            | UnrecoverableEntryException | KeyStoreException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #17
Source File: PermissionUtil.java    From AndroidBase with Apache License 2.0 6 votes vote down vote up
/**
 * 请求外部存储的权限
 */
public static void externalStorage(final RequestPermission requestPermission, RxPermissions rxPermissions, final IView view, RxErrorHandler errorHandler) {
    //先确保是否已经申请过摄像头,和写入外部存储的权限
    boolean isPermissionsGranted =
            rxPermissions
                    .isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (isPermissionsGranted) {//已经申请过,直接执行操作
        requestPermission.onRequestPermissionSuccess();
    } else {//没有申请过,则申请
        rxPermissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .compose(RxUtils.<Boolean>bindToLifecycle(view))
                .subscribe(new ErrorHandleSubscriber<Boolean>(errorHandler) {
                    @Override
                    public void onNext(Boolean granted) {
                        if (granted) {
                            Timber.tag(TAG).d("request WRITE_EXTERNAL_STORAGE and CAMERA success");
                            requestPermission.onRequestPermissionSuccess();
                        } else {
                            view.showMessage("request permissons failure");
                        }
                    }
                });
    }
}
 
Example #18
Source File: MyDuka.java    From LNMOnlineAndroidSample with Apache License 2.0 5 votes vote down vote up
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);

    if (BuildConfig.DEBUG) {
        Timber.plant(new Timber.DebugTree());
    }
}
 
Example #19
Source File: PreferenceHelper.java    From IslamicLibraryAndroid with GNU General Public License v3.0 5 votes vote down vote up
public static void updateLastViewdChangeLog(Context context) {
    try {
        getPreferencesEditor(context)
                .putInt(PREF_KEY_LATEST_SHOWN_CHANGE_LOG, getVersionCode(context))
                .commit();
    } catch (PackageManager.NameNotFoundException e) {
        Timber.e(e);
    }
}
 
Example #20
Source File: AutoCheckInService.java    From ribot-app-android with Apache License 2.0 5 votes vote down vote up
@Subscribe
public void onBeaconsSyncCompleted(BusEvent.BeaconsSyncCompleted event) {
    Timber.i("Beacons sync completed, refreshing monitoring regions...");
    // Connect will trigger a call to startMonitoringRegisteredBeaconUuids() that will
    // start monitoring any new beacon saved after the sync.
    mBeaconManager.connect(this);
}
 
Example #21
Source File: ScannerFragment.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
@Override
public void onResume() {
    super.onResume();
    Timber.d("onResume");
    mScannerView.setResultHandler(this);
    mScannerView.startCamera();
}
 
Example #22
Source File: AirMap.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Enables logging for debugging purposes. Currently cannot be disabled once enabled. This should not need to be
 * called if you are using Timber yourself and have already planted a DebugTree
 */
public static void enableLogging() {
    // Don't want to double log
    if (!timberContainsDebugTree()) {
        Timber.plant(new AirMapTree());
    }
}
 
Example #23
Source File: BleManager.java    From thunderboard-android with Apache License 2.0 5 votes vote down vote up
private void configureMotionCalibrate(boolean enabled) {
    boolean submitted = BleUtils.setCharacteristicIndications(
            gatt,
            ThunderBoardUuids.UUID_SERVICE_ACCELERATION_ORIENTATION,
            ThunderBoardUuids.UUID_CHARACTERISTIC_CALIBRATE,
            ThunderBoardUuids.UUID_DESCRIPTOR_CLIENT_CHARACTERISTIC_CONFIGURATION, enabled);
    Timber.d("%s acceleration indication submitted: %s", enabled, submitted);
}
 
Example #24
Source File: ServicePlayerController.java    From Jockey with Apache License 2.0 5 votes vote down vote up
@Override
public void changeSong(int newPosition) {
    execute(() -> {
        try {
            mBinding.changeSong(newPosition);
        } catch (RemoteException exception) {
            Timber.e(exception, "Failed to change song");
        }
        invalidateAll();
    });
}
 
Example #25
Source File: MemoryServiceWriter.java    From Android-Developer-Toolbelt with Apache License 2.0 5 votes vote down vote up
private MethodSpec createOnBind() {
    CodeBlock code = CodeBlock.builder()
            .addStatement("$T.d(\"onBind: \" + intent)", Timber.class)
            .addStatement("return mMessenger.getBinder()")
            .build();

    return MethodSpec.methodBuilder("onBind")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .addParameter(ClassName.get(Intent.class), "intent")
            .returns(ClassName.get(IBinder.class))
            .addCode(code)
            .build();
}
 
Example #26
Source File: MapDataController.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
protected Func1<AirMapPolygon, Observable<List<AirMapJurisdiction>>> getJurisdictions() {
    return polygon -> Observable.create((Observable.OnSubscribe<List<AirMapJurisdiction>>) subscriber -> {
        // query map for jurisdictions
        List<Feature> features = map.getMap().queryRenderedFeatures(new RectF(0,
                0, map.getMeasuredWidth(), map.getMeasuredHeight()), "jurisdictions");

        if (features.isEmpty()) {
            Timber.d("Features are empty");
            hasJurisdictions = false;
            subscriber.onError(new Throwable("Features are empty"));
        }

        List<AirMapJurisdiction> jurisdictions = new ArrayList<>();
        for (Feature feature : features) {
            try {
                JsonObject propertiesJSON = feature.properties();
                JSONObject jurisdictionJSON = new JSONObject(propertiesJSON.get("jurisdiction").getAsString());

                jurisdictions.add(new AirMapJurisdiction(jurisdictionJSON));
            } catch (JSONException e) {
                Timber.e(e, "Unable to get jurisdiction json");
            }
        }
        subscriber.onNext(jurisdictions);
        subscriber.onCompleted();
    })
    .retryWhen(new RetryWithDelay(4, 400), AndroidSchedulers.mainThread())
    .onErrorReturn(throwable -> {
        Timber.v("Ran out of attempts to query jurisdictions");
        return null;
    });
}
 
Example #27
Source File: AccountAuthenticator.java    From Pioneer with Apache License 2.0 5 votes vote down vote up
@Override
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException {
    Timber.d("[addAccount] - accountType: %s, authTokenType: %s", accountType, authTokenType);
    Bundle result = new Bundle();
    result.putParcelable(KEY_INTENT, createActivityIntent(response, authTokenType));
    return result;
}
 
Example #28
Source File: Ledger.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
synchronized private byte[] exchangeRaw(byte[] apdu) {
    if (transport == null)
        throw new IllegalStateException("No transport (probably closed previously)");
    Timber.d("exchangeRaw %02x", apdu[1]);
    Instruction ins = Instruction.fromByte(apdu[1]);
    if (listener != null) listener.onInstructionSend(ins, apdu);
    sniffOut(ins, apdu);
    byte[] data = transport.exchange(apdu);
    if (listener != null) listener.onInstructionReceive(ins, data);
    sniffIn(data);
    return data;
}
 
Example #29
Source File: FileResourcesUtil.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static boolean writeToFile(@NonNull String content, @Nullable String secretToEncode) {
    // Get the directory for the user's public pictures directory.
    final File path = new File(Environment.getExternalStorageDirectory(), "DHIS2");

    // Make sure the path directory exists.
    if (!path.exists()) {
        // Make it, if it doesn't exit
        path.mkdirs();
    }

    final File file = new File(path, "dhisDataBuckUp.txt");
    if (file.exists())
        file.delete();

    // Save your stream, don't forget to flush() it before closing it.

    try {
        boolean fileCreated = file.createNewFile();
        try (FileOutputStream fOut = new FileOutputStream(file)) {
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
            myOutWriter.append(content);

            myOutWriter.close();

            fOut.flush();
        }
        return fileCreated;
    } catch (IOException e) {
        Timber.e("File write failed: %s", e.toString());
        return false;
    }
}
 
Example #30
Source File: JsonUtils.java    From openshop.io-android with MIT License 5 votes vote down vote up
/**
 * @param order create json from Order object
 * @return return converted order JSON
 * @throws JSONException throw exception
 */
public static JSONObject createOrderJson(Order order) throws JSONException {
    JSONObject jo = new JSONObject();

    jo.put(TAG_SHIPPING_TYPE, order.getShippingType());
    if (order.getPaymentType() == -1) {
        jo.put(TAG_PAYMENT_TYPE, null);
    } else {
        jo.put(TAG_PAYMENT_TYPE, order.getPaymentType());
    }

    jo.put(TAG_NAME, order.getName());
    jo.put(TAG_STREET, order.getStreet());
    jo.put(TAG_HOUSE_NUMBER, order.getHouseNumber());
    jo.put(TAG_CITY, order.getCity());
    jo.put(TAG_ZIP, order.getZip());
    jo.put(TAG_EMAIL, order.getEmail());
    jo.put(TAG_PHONE, order.getPhone());

    if (order.getNote() != null) {
        jo.put(TAG_NOTE, order.getNote());
    }

    if (order.getRegion() != null) {
        jo.put(TAG_REGION, order.getRegion().getId());
    }

    Timber.d("JSONParser postOrder: %s", jo.toString());
    return jo;
}