コード例 #1
0
  @Override
  public void doAfter(JSONArray jsonArray) {
    flProxy.setVisibility(View.GONE);

    if (jsonArray != null) {
      try {
        Gson gson = new Gson();
        Response response = gson.fromJson(jsonArray.getJSONObject(0).toString(), Response.class);

        android.support.design.widget.Snackbar.make(
                findViewById(R.id.cl_container),
                response.getMessage(),
                android.support.design.widget.Snackbar.LENGTH_LONG)
            .show();

        if (response.getStatus()) {
          etSubject.setText("");
          etMessage.setText("");
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
    } else {
      android.support.design.widget.Snackbar.make(
              findViewById(R.id.cl_container),
              "Falhou, tente novamente.",
              android.support.design.widget.Snackbar.LENGTH_LONG)
          .show();
    }
  }
コード例 #2
0
 @Override
 public void handleMessage(Message msg) {
   super.handleMessage(msg);
   switch (msg.what) {
     case StringUtils.START_GET_BILL_COMMENT_SUCCESSFULLY:
       // App.dismissDialog();
       commentList = BillCommentUtils.getBillCommentList(StringUtils.FRAGMENT_BILL_COMMENT);
       commentAdapter.refresh(commentList);
       srlComment.setRefreshing(false);
       isRefreshing = false;
       break;
     case StringUtils.START_GET_BILL_COMMENT_FAILED:
       Snackbar.make(rvComment, R.string.please_check_your_network, Snackbar.LENGTH_SHORT)
           .show();
       srlComment.setRefreshing(false);
       isRefreshing = false;
       break;
     case StringUtils.START_POST_BILL_COMMENT_SUCCESSFULLY:
       BillCommentUtils.clearList(StringUtils.FRAGMENT_BILL_COMMENT);
       BillCommentUtils.startGetBillCommentTransaction(
           StringUtils.FRAGMENT_BILL_COMMENT, handler, bill.getObjectId());
       App.dismissDialog();
       break;
     case StringUtils.START_POST_BILL_COMMENT_FAILED:
       App.dismissDialog();
       Snackbar.make(rvComment, R.string.please_check_your_network, Snackbar.LENGTH_SHORT)
           .show();
       break;
   }
 }
コード例 #3
0
ファイル: LoginActivity.java プロジェクト: mmccoy37/GTMovies
 @Override
 protected void onPostExecute(final Boolean success) {
   mAuthTask = null;
   // Check if no view has focus:
   if (success) {
     verified = true;
     if (getParent() == null) {
       setResult(1);
     } else {
       getParent().setResult(1);
     }
     Snackbar.make(
             findViewById(R.id.login_root),
             "'" + CurrentState.getUser().getUsername() + "' signed in.",
             Snackbar.LENGTH_LONG)
         .show();
     // We are done. Go back to MainActivity, after a set delay.
     TimerTask task =
         new TimerTask() {
           @Override
           public void run() {
             //                        NavUtils.navigateUpFromSameTask(LoginActivity.this);
             finish();
           }
         };
     Timer t = new Timer();
     t.schedule(task, 1000);
   } else {
     if (null != attempts.get(email) && attempts.get(email) >= 2) {
       Snackbar.make(rootView, "ACCOUNT '" + email + "' LOCKED!", Snackbar.LENGTH_SHORT).show();
       IOActions.getUserByUsername(email).setPermission(0);
     }
     if (IOActions.getUserByUsername(email) != null) {
       if (attempts.get(email) != null) {
         attempts.put(email, attempts.get(email) + 1);
         Snackbar.make(
                 rootView,
                 (3 - attempts.get(email)) + " attempts remaining for " + email,
                 Snackbar.LENGTH_SHORT)
             .show();
       } else {
         attempts.put(email, 1);
         Snackbar.make(rootView, "2 attempts remaining for " + email, Snackbar.LENGTH_SHORT)
             .show();
         Log.i("GTMovies", error);
       }
     }
     Log.i("GTMovies", error);
     if (error.equals("duplicate")) {
       mEmailView.setError("User already exists");
       mEmailView.requestFocus();
     } else if (error.equals("nulluser")) {
       mEmailView.setError("User not found");
       mEmailView.requestFocus();
     } else {
       mPasswordView.setError(getString(R.string.error_incorrect_password));
       mPasswordView.requestFocus();
     }
   }
 }
コード例 #4
0
  @Override
  public void onRequestPermissionsResult(
      int requestCode, String[] permissions, int[] grantResults) {
    /**
     * // BEGIN_INCLUDE(onRequestPermissionsResult) if (requestCode ==
     * PERMISSION_REQUEST_NETWORK_STATE) { // Request for network state permission. if
     * (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
     *
     * <p>Snackbar.make(mLayout, "Permission Access Network State was granted. Get status.",
     * Snackbar.LENGTH_SHORT) .show(); if (getNetworkStatus(mainContext) == true)
     * startGetScheduleActivity(); } else { // Permission request was denied. Snackbar.make(mLayout,
     * "Permission Access Network State was denied.", Snackbar.LENGTH_SHORT) .show(); } } //
     * END_INCLUDE(onRequestPermissionsResult)
     */
    if (requestCode == PERMISSION_REQUEST_INTERNET) {
      // Request for network state  permission.
      if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        Snackbar.make(
                mLayout, "Permission Internet was granted. Get status.", Snackbar.LENGTH_SHORT)
            .show();
        if (getNetworkStatus(mainContext) == true) startGetScheduleActivity();
      } else {
        // Permission request was denied.
        Snackbar.make(mLayout, "Permission Internet was denied.", Snackbar.LENGTH_SHORT).show();
      }
    }
    // END_INCLUDE(onRequestPermissionsResult)

  }
コード例 #5
0
ファイル: RecentFragment.java プロジェクト: bkromhout/Minerva
  /**
   * Called when one of the cards is swiped away. Removes the associated book from the recents list.
   *
   * @param uniqueId The unique ID of the item so that the correct {@link RBook} can be retrieved.
   */
  @Override
  public void handleSwiped(long uniqueId) {
    // Remove from recents.
    realm.executeTransactionAsync(
        bgRealm ->
            bgRealm.where(RBook.class).equalTo("uniqueId", uniqueId).findFirst().isInRecents =
                false);

    // Show snackbar with "Undo" button.
    Snackbar undoSnackbar = Snackbar.make(coordinator, R.string.book_removed, Snackbar.LENGTH_LONG);
    undoSnackbar.setAction(
        R.string.undo,
        view -> {
          // Put back in recents if undo button is clicked.
          try (Realm realm = Realm.getDefaultInstance()) {
            realm.executeTransactionAsync(
                bgRealm ->
                    bgRealm
                            .where(RBook.class)
                            .equalTo("uniqueId", uniqueId)
                            .findFirst()
                            .isInRecents =
                        true);
          }
        });
    undoSnackbar.show();
  }
コード例 #6
0
 @Override
 public void showSnackbar(String message) {
   CoordinatorLayout coordinator =
       (CoordinatorLayout) getActivity().findViewById(R.id.coordinator);
   Snackbar snackbar = Snackbar.make(coordinator, message, Snackbar.LENGTH_LONG);
   snackbar.show();
 }
コード例 #7
0
ファイル: ProfileActivity.java プロジェクト: Sivashankar06/KK
    @Override
    protected void onPostExecute(String response) {
      super.onPostExecute(response);
      Log.d(TAG, "Response : " + response);
      if (response != null) {

        try {
          JSONObject jsonObject = new JSONObject(response);
          boolean isSuccess = jsonObject.getBoolean(Keys.KEY_SUCCESS);

          if (isSuccess) {

            Log.d(TAG, "Profile information Updated");
            Snackbar.make(profileImgView, "Profile information Updated", Snackbar.LENGTH_LONG)
                .setAction("Action", null)
                .show();

          } else {
            Snackbar.make(profileImgView, "Profile information not Updated", Snackbar.LENGTH_LONG)
                .setAction("Action", null)
                .show();
            Log.d(TAG, "Profile information not Updated");
          }
        } catch (JSONException e) {
          e.printStackTrace();
        }
      } else {
        Log.d(TAG, "Update response is NULL");
      }
    }
コード例 #8
0
  /* Shows notification for a running sleep timer */
  private void showSleepTimerNotification(long remainingTime) {

    // set snackbar message
    String message;
    if (remainingTime > 0) {
      message = mSleepTimerNotificationMessage + getReadableTime(remainingTime);
    } else {
      message = mSleepTimerNotificationMessage;
    }

    // show snackbar
    mSleepTimerNotification = Snackbar.make(mRootView, message, Snackbar.LENGTH_INDEFINITE);
    mSleepTimerNotification.setAction(
        R.string.dialog_generic_button_cancel,
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            // stop sleep timer service
            mSleepTimerService.startActionStop(mActivity);
            mSleepTimerRunning = false;
            saveAppState(mActivity);
            // notify user
            Toast.makeText(
                    mActivity,
                    mActivity.getString(R.string.toastmessage_timer_cancelled),
                    Toast.LENGTH_SHORT)
                .show();
            LogHelper.v(LOG_TAG, "Sleep timer cancelled.");
          }
        });
    mSleepTimerNotification.show();
  }
コード例 #9
0
 public void GotoScheduleListActivityIfNetworkAvailable(final Context context) {
   // permission     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
   /**
    * if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) ==
    * PackageManager.PERMISSION_GRANTED) { // Permission is already available, start network state
    * preview Snackbar.make(mLayout, "Access Network State avaiable. Getting status",
    * Snackbar.LENGTH_SHORT).show(); if (getNetworkStatus(mainContext) == true) {
    * Snackbar.make(mLayout, "Network is available", Snackbar.LENGTH_SHORT).show();
    * startGetScheduleActivity(); } else { Snackbar.make(mLayout, "Network is not available",
    * Snackbar.LENGTH_SHORT).show(); } } else { // Permission is missing and must be requested.
    * requestNetworkStatePermission(); }
    */
   if (ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET)
       == PackageManager.PERMISSION_GRANTED) {
     // Permission is already available, start network state preview
     Snackbar.make(mLayout, "Internet available.", Snackbar.LENGTH_SHORT).show();
     if (getNetworkStatus(mainContext) == true) {
       Snackbar.make(mLayout, "Network/Internet is available", Snackbar.LENGTH_SHORT).show();
       startGetScheduleActivity();
     } else {
       Snackbar.make(mLayout, "Network/Internet is not available", Snackbar.LENGTH_SHORT).show();
     }
   } else {
     // Permission is missing and must be requested.
     requestNetworkStatePermission();
   }
 }
コード例 #10
0
  private void updateCatagory() {

    final Dao<CatagoryModel, Integer> catagoryDoa;

    try {
      catagoryDoa = getHelper().getCatagoryDao();

      UpdateBuilder<CatagoryModel, Integer> updateBuilder = catagoryDoa.updateBuilder();
      updateBuilder.updateColumnValue("catagoryName", catagoryEditText.getText().toString());

      updateBuilder
          .where()
          .eq("categoryId", Integer.valueOf(catagoryModel.getCategoryId()))
          .and()
          .eq("catagoryName", catagoryModel.getCatagoryName());
      ;
      updateBuilder.update();

      Snackbar snackbar =
          Snackbar.make(view, "Catagory updated sucessfully!!", Snackbar.LENGTH_LONG);

      snackbar.show();

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
コード例 #11
0
  private void featchData() {

    progressBar.startIntro();
    progressBar.setProgress(0);
    if (!MyApplication.instance.isNetworkAvailable()) {
      try {
        Snackbar snackbar =
            Snackbar.make(relativeLayout, "لا يوجد اتصال بالانترنت", Snackbar.LENGTH_INDEFINITE)
                .setAction(
                    "اعد المحاولة",
                    new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                        featchData();
                      }
                    });
        snackbar.setActionTextColor(Color.RED);

        View sbView = snackbar.getView();
        TextView textView =
            (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
        textView.setTextColor(Color.YELLOW);

        snackbar.show();
      } catch (Exception e) {

      }
    } else {

      webView.stopLoading();
      webView.loadUrl(MyApplication.BASE_URL + urlExtention);
    }
  }
コード例 #12
0
 private void onFabClicked() {
   Snackbar testSnackbar =
       Snackbar.make(
           findViewById(android.R.id.content), "Snackbar clicked", Snackbar.LENGTH_SHORT);
   testSnackbar.show();
   /** Managing the {@link Snackbar} is not that hard either */
   RxSnackbar.dismisses(testSnackbar).subscribe(this::onSnackbarDismissed);
 }
コード例 #13
0
  private void onSwipeDelete(RecyclerView.ViewHolder viewHolder, final View rootView) {
    billId = ((TextView) viewHolder.itemView.findViewById(R.id.tvPayID)).getText().toString();
    getSingleBill();

    Snackbar snackbar =
        Snackbar.make(rootView, AppConfig.BILL_DELETED, Snackbar.LENGTH_LONG)
            .setAction(AppConfig.UNDO, mOnClickListener);
    snackbar.show();
  }
コード例 #14
0
  /** 登陆到主界面 */
  @OnClick(R.id.btn_login)
  void onLogin() {
    // 隐藏软键盘
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

    if (TextUtils.isEmpty(etUsername.getText().toString())
        || TextUtils.isEmpty(etPassword.getText().toString())) {
      Snackbar.make(clContainer, "少年呦 你是忘记写账号了还是密码呢?", Snackbar.LENGTH_LONG).show();
    } else {
      String username = etUsername.getText().toString();
      String password = etPassword.getText().toString();

      // 检测账号密码是否合法
      if (StringUtil.checkString(username) && StringUtil.checkString(password)) {
        Map<String, String> params = new HashMap<String, String>(2);
        params.put(StringConstant.USER_NAME, username);
        params.put(StringConstant.USER_PWD, password);
        RequestInfo info = new RequestInfo(StringConstant.SERVER_LOGIN_URL, params);
        httpTools.post(
            info,
            new HttpCallback() {
              @Override
              public void onStart() {}

              @Override
              public void onFinish() {}

              @Override
              public void onResult(String s) {
                // 服务端返回Json
                System.out.println(s);
                if ("null".equals(s)) {
                  Snackbar.make(clContainer, "少年呦 账号或密码不对", Snackbar.LENGTH_LONG).show();
                  return;
                }
                onReadJson(s);
              }

              @Override
              public void onError(Exception e) {}

              @Override
              public void onCancelled() {}

              @Override
              public void onLoading(long l, long l1) {}
            });

      } else {
        Snackbar.make(clContainer, "少年呦 账号和密码要符合长度要求呦", Snackbar.LENGTH_SHORT).show();
      }
    }

    //        startActivity(new Intent(LoginActivity.this, MainActivity.class));
  }
コード例 #15
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    ButterKnife.bind(this);

    tvTitle.setText("登陆");
    ivLogo.setVisibility(View.GONE);
    sharedPreferences = getSharedPreferences("user_sp", Context.MODE_PRIVATE);

    etPassword.setOnFocusChangeListener(
        new View.OnFocusChangeListener() {
          @Override
          public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
              // 22 33 娘
              ivBili22.setBackground(getResources().getDrawable(biliHide[0], null));
              ivBili33.setBackground(getResources().getDrawable(biliHide[1], null));

              // 用户名部分UI
              ivUsername.setBackground(getResources().getDrawable(usernameDrawable[1], null));
              viewUsername.setBackgroundColor(getResources().getColor(lineColorDark));

              // 密码部分UI
              ivPassword.setBackground(getResources().getDrawable(passwordDrawable[0], null));
              viewPassword.setBackgroundColor(getResources().getColor(lineColorPink));
            } else {
              // 22 33 娘
              ivBili22.setBackground(getResources().getDrawable(biliNormal[0], null));
              ivBili33.setBackground(getResources().getDrawable(biliNormal[1], null));

              // 用户名部分UI
              ivUsername.setBackground(getResources().getDrawable(usernameDrawable[0], null));
              viewUsername.setBackgroundColor(getResources().getColor(lineColorPink));

              // 密码部分UI
              ivPassword.setBackground(getResources().getDrawable(passwordDrawable[1], null));
              viewPassword.setBackgroundColor(getResources().getColor(lineColorDark));
            }
          }
        });

    if (Utils.checkNetConnection(getApplicationContext())) {
      Snackbar.make(clContainer, "少年呦 你联网了嘛?", Snackbar.LENGTH_LONG).show();
    }

    if (getIntent().getBooleanExtra("register", false)) {
      etUsername.setText(getIntent().getStringExtra("username"));
      Snackbar.make(clContainer, "注册成功 和我们签订契约吧", Snackbar.LENGTH_LONG).show();
    }

    // 初始化Volley
    HttpTools.init(getApplicationContext());
    httpTools = new HttpTools(getApplicationContext());
  }
コード例 #16
0
ファイル: SnackbarHelper.java プロジェクト: natix643/uome
  private void show(int stringId, int colorId, int length) {
    Snackbar snackbar = Snackbar.make(contentView, stringId, length);
    dismissOnClick(snackbar);

    TextView text =
        (TextView) snackbar.getView().findViewById(android.support.design.R.id.snackbar_text);
    text.setTextColor(activity.getResources().getColor(colorId));

    snackbar.show();
  }
コード例 #17
0
ファイル: Main.java プロジェクト: dzhan008/realexp
  public void Gain50Exp(View view) {
    user.gain_exp(50);
    mProgress.incrementProgressBy(50);

    Snackbar snackbar = Snackbar.make(view, "You got 50 EXP!", Snackbar.LENGTH_LONG);
    snackbar.setAction("Action", null).show();

    if (mProgress.getProgress() >= mProgress.getMax()) {
      LevelUp(view);
    }
  }
コード例 #18
0
 @OnClick(R.id.ok_button)
 public void newPermissionClicked() {
   if (!NetworkingUtils.isOnline(getContext())) {
     Snackbar.make(getView(), R.string.no_internet_connection, Snackbar.LENGTH_LONG).show();
     return;
   }
   User user = User.getUser(mPermissionEmailView.getText().toString());
   if (user == null) {
     Snackbar.make(getView(), getString(R.string.invalid_email), Snackbar.LENGTH_LONG).show();
     return;
   }
   user.saveLocal();
   int slaveId = 0;
   if (mSelectedSlave != null) {
     slaveId = mSelectedSlave.getId();
   }
   if (Permission.getType(mPermissionTypeView.getText().toString()) != Permission.ADMIN_PERMISSION
       && (mSlaves == null || mSlaves.size() == 0)) {
     Snackbar.make(getView(), R.string.master_without_slaves, Snackbar.LENGTH_LONG).show();
     return;
   }
   Permission adminPermission = User.getLoggedUser().getAdminPermission(mSelectedMaster);
   if (adminPermission == null) {
     Snackbar.make(getView(), R.string.you_are_not_admin, Snackbar.LENGTH_LONG).show();
     return;
   }
   String userKey = adminPermission.getKey();
   int permissionType = Permission.getType(mPermissionTypeView.getText().toString());
   String startDate =
       Permission.getDefaultDateString(mStartDateView.getText().toString())
           + "T"
           + mStartHourView.getText().toString();
   String endDate = "0";
   if (permissionType == Permission.TEMPORAL_PERMISSION) {
     endDate =
         Permission.getDefaultDateString(mEndDateView.getText().toString())
             + "T"
             + mEndHourView.getText().toString();
   }
   if (TextUtils.isEmpty(mKey)) {
     Permission permission =
         Permission.create(user, mSelectedMaster, permissionType, "", startDate, endDate, slaveId);
     mPermissionModifiedListener.onCreatePermissionClicked(permission, userKey);
     // If editing permission
   } else {
     mToEditPermission.setType(Permission.getType(mPermissionTypeView.getText().toString()));
     mToEditPermission.setStartDate(startDate);
     mToEditPermission.setEndDate(endDate);
     mToEditPermission.setSlaveId(slaveId);
     mPermissionModifiedListener.onModifyPermissionClicked(
         mToEditPermission, mOldSlaveId, userKey, mSelectedMaster.getId());
   }
 }
コード例 #19
0
 private void showErrorMessage(
     @StringRes int messageResId,
     @StringRes int actionLabelResid,
     View.OnClickListener actionListener) {
   Snackbar instance = Snackbar.make(getView(), messageResId, Snackbar.LENGTH_LONG);
   if (actionLabelResid != 0 && actionListener != null) {
     instance.setAction(actionLabelResid, actionListener);
     int colorRes = ViewUtils.getThemeColorAccent(getActivity().getTheme());
     instance.setActionTextColor(colorRes);
   }
   instance.show();
 }
コード例 #20
0
  public static Snackbar showSnackbar(
      View container, @StringRes int text, View.OnClickListener click) {
    if (container == null) {
      L.e("container == null, return null");
      return null;
    }

    Snackbar snackbar = Snackbar.make(container, text, Snackbar.LENGTH_INDEFINITE);
    snackbar.setAction(R.string.action_enable, click).show();

    return snackbar;
  }
コード例 #21
0
  private boolean validate() {
    if (creator.getInvite() == null) {
      return false;
    } else {
      if (creator.getInvite().date == 0l) {
        String message = "";
        if (creator.getInvite().time == 0l || TextUtils.isEmpty(inviteTitle.getText())) {
          message = getString(R.string.all_fields_error);
        } else {
          message = String.format(getString(R.string.one_field_error), "date");
        }
        Snackbar.make(inviteDetailsCard, message, Snackbar.LENGTH_LONG).show();
        return false;
      }
      if (creator.getInvite().time == 0l) {
        String message = "";
        if (creator.getInvite().date == 0l || TextUtils.isEmpty(inviteTitle.getText())) {
          message = getString(R.string.all_fields_error);
        } else {
          message = String.format(getString(R.string.one_field_error), "time");
        }
        Snackbar.make(inviteDetailsCard, message, Snackbar.LENGTH_LONG).show();
        return false;
      }
      if (TextUtils.isEmpty(inviteTitle.getText())) {
        String message = "";
        if (creator.getInvite().time == 0l || creator.getInvite().date == 0l) {
          message = getString(R.string.all_fields_error);
        } else {
          message = String.format(getString(R.string.one_field_error), "title");
        }
        Snackbar.make(inviteDetailsCard, message, Snackbar.LENGTH_LONG).show();
        return false;
      }

      DateTime time = new DateTime().withMillis(creator.getInvite().time);
      DateTime date = new DateTime().withMillis(creator.getInvite().date);
      DateTime when =
          new DateTime()
              .withYear(date.getYear())
              .withMonthOfYear(date.getMonthOfYear())
              .withDayOfMonth(date.getDayOfMonth())
              .withHourOfDay(time.getHourOfDay())
              .withMinuteOfHour(time.getMinuteOfHour());

      if (when.isBeforeNow()) {
        Snackbar.make(inviteDetailsCard, getString(R.string.wrong_datetime), Snackbar.LENGTH_LONG)
            .show();
        return false;
      }
    }
    return true;
  }
コード例 #22
0
 public void showProgressBar(boolean isShow) throws Exception {
   if (isShow) {
     progressBar.setVisibility(View.VISIBLE);
     if (snackbar != null) {
       snackbar.show();
     }
   } else {
     progressBar.setVisibility(View.GONE);
     if (snackbar != null) {
       snackbar.dismiss();
     }
   }
 }
コード例 #23
0
  protected void showToast(String message, boolean isLong) {

    @LayoutRes int rootView = getRootView();
    View view = this.findViewById(rootView);

    if (view == null) {
      Timber.e("view is null, cannot show toast");
      Timber.d("View id: '" + getLayoutResource() + "'");
      return;
    }

    Snackbar snackbar =
        Snackbar.make(view, message, isLong ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT);
    snackbar.show();
  }
コード例 #24
0
  private void requestNetworkStatePermission() {
    // Permission has not been granted and must be requested.

    /**
     * if (ActivityCompat.shouldShowRequestPermissionRationale(this,
     * Manifest.permission.ACCESS_NETWORK_STATE)) { // Provide an additional rationale to the user
     * if the permission was not granted // and the user would benefit from additional context for
     * the use of the permission. // Display a SnackBar with a button to request the missing
     * permission. Snackbar.make(mLayout, "Permission Access Network State is Required.",
     * Snackbar.LENGTH_INDEFINITE).setAction("OK", new View.OnClickListener() { @Override public
     * void onClick(View view) { // Request the permission
     * ActivityCompat.requestPermissions(MainActivity.this, new
     * String[]{Manifest.permission.ACCESS_NETWORK_STATE}, PERMISSION_REQUEST_NETWORK_STATE); }
     * }).show();
     *
     * <p>} else { Snackbar.make(mLayout, "Permission Access Network State is not available.
     * Requesting permission.", Snackbar.LENGTH_SHORT).show(); // Request the permission. The result
     * will be received in onRequestPermissionResult(). ActivityCompat.requestPermissions(this, new
     * String[]{Manifest.permission.ACCESS_NETWORK_STATE}, PERMISSION_REQUEST_NETWORK_STATE); }
     */
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.INTERNET)) {
      // Provide an additional rationale to the user if the permission was not granted
      // and the user would benefit from additional context for the use of the permission.
      // Display a SnackBar with a button to request the missing permission.
      Snackbar.make(mLayout, "Permission Internet is Required.", Snackbar.LENGTH_INDEFINITE)
          .setAction(
              "OK",
              new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                  // Request the permission
                  ActivityCompat.requestPermissions(
                      MainActivity.this,
                      new String[] {Manifest.permission.INTERNET},
                      PERMISSION_REQUEST_INTERNET);
                }
              })
          .show();

    } else {
      Snackbar.make(
              mLayout, "Internet is not available. Requesting permission.", Snackbar.LENGTH_SHORT)
          .show();
      // Request the permission. The result will be received in onRequestPermissionResult().
      ActivityCompat.requestPermissions(
          this, new String[] {Manifest.permission.INTERNET}, PERMISSION_REQUEST_INTERNET);
    }
  }
コード例 #25
0
  // 加载更多
  private void loadMore(final String url) {
    isLoading = true; // 正在加载
    if (HttpUtils.isNetworkConnected(mActivity)) {
      XUtil.GetJson(
          url,
          new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
              //                    PreUtils.putStringTo(Constant.CACHE, mActivity, url,
              // responseString);
              SQLiteDatabase db =
                  ((MainActivity) mActivity).getCacheDbHelper().getWritableDatabase();
              db.execSQL(
                  "replace into CacheList(date,json) values(" + date + ",' " + result + "')");
              db.close();
              parseBeforeJson(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
              //                    UIUtils.showToastSafe("解析失败: "+ex.toString());
            }
          });

    } else {
      SQLiteDatabase db = ((MainActivity) mActivity).getCacheDbHelper().getReadableDatabase();
      Cursor cursor = db.rawQuery("select * from CacheList where date = " + date, null);
      if (cursor.moveToFirst()) {
        String json = cursor.getString(cursor.getColumnIndex("json"));
        parseBeforeJson(json);
      } else {
        db.delete("CacheList", "date < " + date, null);
        isLoading = false;
        Snackbar sb = Snackbar.make(lv_news, "没有更多的离线内容了~", Snackbar.LENGTH_SHORT);
        sb.getView()
            .setBackgroundColor(
                mActivity
                    .getResources()
                    .getColor(
                        ((MainActivity) mActivity).isLight()
                            ? android.R.color.holo_blue_dark
                            : android.R.color.black));
        sb.show();
      }
      cursor.close();
      db.close();
    }
  }
コード例 #26
0
ファイル: WallAdapter.java プロジェクト: WunderEye/H2Icons
 private void checkForStoragePermission(int position, SimpleItemViewHolder holder) {
   if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
       == PackageManager.PERMISSION_GRANTED) {
     getWallpaper(position);
   } else {
     if (ActivityCompat.shouldShowRequestPermissionRationale(
         (Activity) context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
       Snackbar.make(
               holder.mainView, R.string.permission_storage_rationale, Snackbar.LENGTH_INDEFINITE)
           .setAction(
               R.string.ok,
               new View.OnClickListener() {
                 @Override
                 public void onClick(View view) {
                   ActivityCompat.requestPermissions(
                       (Activity) context,
                       new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
                       REQUEST_STORAGE);
                 }
               })
           .show();
     } else {
       reqPos = position;
       ActivityCompat.requestPermissions(
           ((Activity) context),
           new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
           REQUEST_STORAGE);
     }
   }
 }
コード例 #27
0
 private boolean handleContextItemSelected(MenuItem menu, int position) {
   if (position >= mVideoAdapter.getCount()) return false;
   MediaWrapper media = mVideoAdapter.getItem(position);
   if (media == null) return false;
   switch (menu.getItemId()) {
     case R.id.video_list_play_from_start:
       playVideo(media, true);
       return true;
     case R.id.video_list_play_audio:
       playAudio(media);
       return true;
     case R.id.video_list_info:
       Activity activity = getActivity();
       if (activity instanceof MainActivity)
         ((MainActivity) activity)
             .showSecondaryFragment(SecondaryActivity.MEDIA_INFO, media.getLocation());
       else {
         Intent i = new Intent(activity, SecondaryActivity.class);
         i.putExtra("fragment", "mediaInfo");
         i.putExtra("param", media.getLocation());
         startActivity(i);
       }
       return true;
     case R.id.video_list_delete:
       Snackbar.make(getView(), getString(R.string.file_deleted), Snackbar.LENGTH_LONG)
           .setAction(android.R.string.cancel, mCancelDeleteMediaListener)
           .show();
       Message msg = mDeleteHandler.obtainMessage(DELETE_MEDIA, position, 0);
       mDeleteHandler.sendMessageDelayed(msg, DELETE_DURATION);
       return true;
   }
   return false;
 }
コード例 #28
0
 private void showConnectionProblemMessage() {
   SnackbarExtensionKt.setTextColor(
           Snackbar.make(
               notificationRecyclerView, R.string.connectionProblems, Snackbar.LENGTH_SHORT),
           ColorUtil.INSTANCE.getColorArgb(R.color.white, getContext()))
       .show();
 }
コード例 #29
0
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
   int id = item.getItemId();
   if (id == android.R.id.home) {
     this.onBackPressed();
     return true;
   }
   if (id == R.id.action_favorite) {
     FavoritesManager fm = FavoritesManager.getInstance(getApplicationContext());
     if (isFavorite) {
       fm.remove(fm.find(book));
     } else {
       fm.add(book);
     }
     fm.save();
     isFavorite = !isFavorite;
     Snackbar.make(
             $(R.id.main_content),
             isFavorite ? R.string.favorite_add_finished : R.string.favorite_remove_finished,
             Snackbar.LENGTH_LONG)
         .show();
     invalidateOptionsMenu();
     return true;
   }
   if (id == R.id.action_download) {
     new Thread() {
       @Override
       public void run() {
         onActionDownloadClick();
       }
     }.start();
     return true;
   }
   return super.onOptionsItemSelected(item);
 }
コード例 #30
0
  void generatePass() {
    url = mURLView.getText().toString();
    if (!url.startsWith("www.") && !url.startsWith("http://")) {
      url = "www." + url;
    }
    if (!url.startsWith("http://")) {
      url = "http://" + url;
    }

    if (!isUrl(url)) {
      mURLView.setError("Please enter a valid URL");
      return;
    }

    if (mPasswordView.getText().length() < 8) {
      mPasswordView.setError("Please use a longer password");
      return;
    }

    saveUrl(url);

    Snackbar.make(mScrollView, "Password generated", Snackbar.LENGTH_LONG)
        .setAction(
            "Copy",
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                GeneratePassActivity.this.copyPassToClipboard();
              }
            })
        .show();
  }