private void updateRingtoneName(int type, Preference preference, int msg) {
   if (preference == null) return;
   Context context = getActivity();
   if (context == null) return;
   Uri ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(context, type);
   CharSequence summary = context.getString(com.android.internal.R.string.ringtone_unknown);
   // Is it a silent ringtone?
   if (ringtoneUri == null) {
     summary = context.getString(com.android.internal.R.string.ringtone_silent);
   } else {
     // Fetch the ringtone title from the media provider
     try {
       Cursor cursor =
           context
               .getContentResolver()
               .query(ringtoneUri, new String[] {MediaStore.Audio.Media.TITLE}, null, null, null);
       if (cursor != null) {
         if (cursor.moveToFirst()) {
           summary = cursor.getString(0);
         }
         cursor.close();
       }
     } catch (SQLiteException sqle) {
       // Unknown title for the ringtone
     }
   }
   mHandler.sendMessage(mHandler.obtainMessage(msg, summary));
 }
 public static String list(Context c, Vector<BaseObject> objs) {
   String ret = new String();
   if (objs.size() == 0) return ret;
   if (objs.size() == 1) {
     ret = objs.firstElement().getName();
     return ret;
   }
   if (objs.size() == 2) {
     ret =
         objs.get(0).getName()
             + " "
             + c.getString(R.string.stringhandler_and1)
             + " "
             + objs.get(1).getName();
     return ret;
   }
   for (int i = 0; i < objs.size() - 1; i++) {
     ret += objs.get(i).getName();
     if (i < objs.size() - 2) {
       ret += c.getString(R.string.stringhandler_comma);
       ret += " ";
     } else {
       ret += c.getString(R.string.stringhandler_and2);
       ret += " ";
     }
   }
   ret += objs.lastElement().getName();
   return ret;
 }
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

    VideoHolder holder;

    // The item at the current position
    final YouTubeContent.YouTubeVideo item = YouTubeContent.ITEMS.get(position);

    if (convertView == null) {
      // Create the row
      final LayoutInflater inflater =
          (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      convertView = inflater.inflate(R.layout.row_layout, parent, false);

      // Create the video holder
      holder = new VideoHolder();

      // Set the title
      holder.title = (TextView) convertView.findViewById(R.id.textView_title);
      holder.title.setText(item.title);

      // Initialise the thumbnail
      holder.thumb = (YouTubeThumbnailView) convertView.findViewById(R.id.imageView_thumbnail);
      holder.thumb.setTag(item.id);
      holder.thumb.initialize(mContext.getString(R.string.DEVELOPER_KEY), this);

      convertView.setTag(holder);
    } else {
      // Create it again
      holder = (VideoHolder) convertView.getTag();
      final YouTubeThumbnailLoader loader = mLoaders.get(holder.thumb);

      if (item != null) {
        // Set the title
        holder.title.setText(item.title);

        // Setting the video id can take a while to actually change the image
        // in the meantime the old image is shown.
        // Removing the image will cause the background color to show instead, not ideal
        // but preferable to flickering images.
        holder.thumb.setImageBitmap(null);

        if (loader == null) {
          // Loader is currently initialising
          holder.thumb.setTag(item.id);
        } else {
          // The loader is already initialised
          // Note that it's possible to get a DeadObjectException here
          try {
            loader.setVideo(item.id);
          } catch (IllegalStateException exception) {
            // If the Loader has been released then remove it from the map and re-init
            mLoaders.remove(holder.thumb);
            holder.thumb.initialize(mContext.getString(R.string.DEVELOPER_KEY), this);
          }
        }
      }
    }
    return convertView;
  }
  public VideoHdrWidget(CameraManager cam, Context context) {
    super(cam, context, R.drawable.ic_widget_placeholder); // TODO: Icon, video hdr

    setVideoOnly(true);

    // We cannot inflate from XML here, because there are device-specific keys and values
    Camera.Parameters params = mCamManager.getParameters();
    if (params == null) {
      return;
    }

    if (params.get(KEY_SONY_VIDEO_HDR) != null) {
      // Use Sony values
      setKey(KEY_SONY_VIDEO_HDR);
      addValue("off", R.drawable.ic_widget_hdr_off, context.getString(R.string.disabled));
      addValue("on", R.drawable.ic_widget_hdr_on, context.getString(R.string.enabled));
    } else if (params.get(KEY_QCOM_VIDEO_HDR) != null) {
      // Use Qcom values
      setKey(KEY_QCOM_VIDEO_HDR);
      addValue("0", R.drawable.ic_widget_hdr_off, context.getString(R.string.disabled));
      addValue("1", R.drawable.ic_widget_hdr_on, context.getString(R.string.enabled));
    }

    getToggleButton().setHintText(R.string.widget_videohdr);
  }
Exemple #5
0
 /**
  * Creates directories if necessary and returns fully qualified file
  *
  * @return output file name
  * @throws IOException
  */
 private String setupFile(File directory, ExportType exportType) throws IOException {
   if (directory != null) {
     // Check for /sdcard/astrid directory. If it doesn't exist, make it.
     if (directory.exists() || directory.mkdir()) {
       String fileName;
       switch (exportType) {
         case EXPORT_TYPE_SERVICE:
           fileName = String.format(BackupConstants.BACKUP_FILE_NAME, getDateForExport());
           break;
         case EXPORT_TYPE_MANUAL:
           fileName = String.format(BackupConstants.EXPORT_FILE_NAME, getDateForExport());
           break;
         case EXPORT_TYPE_ON_UPGRADE:
           fileName = String.format(BackupConstants.UPGRADE_FILE_NAME, latestSetVersionName);
           break;
         default:
           throw new IllegalArgumentException("Invalid export type"); // $NON-NLS-1$
       }
       return directory.getAbsolutePath() + File.separator + fileName;
     } else {
       // Unable to make the /sdcard/astrid directory.
       throw new IOException(
           context.getString(R.string.DLG_error_sdcard, directory.getAbsolutePath()));
     }
   } else {
     // Unable to access the sdcard because it's not in the mounted state.
     throw new IOException(context.getString(R.string.DLG_error_sdcard_general));
   }
 }
Exemple #6
0
  @Override
  public void onChange(boolean selfChange) {
    Log.d("C3PO", "Received settings change!");

    super.onChange(selfChange);
    Log.d("C3PO", "Settings change detected");

    int vol = audioManager.getStreamVolume(AudioManager.STREAM_RING);
    int max_vol = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
    if (vol == oldVolume) {
      return;
    }
    oldVolume = vol;
    SimplMessageAndroid msg_out = new SimplMessageAndroid();
    try {
      msg_out.addParam(Param.MSGID, -1);
      msg_out.addParam(Param.CURRENT_VOLUME, vol);
      msg_out.addParam(Param.MAX_VOLUME, max_vol);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    try {
      Socket s =
          new Socket(
              context.getString(R.string.comm_relay_ip),
              Integer.parseInt(context.getString(R.string.comm_relay_outbound)));
      SecureChannel channel = new SecureChannelAndroid(new RSAUtilImpl(context));
      channel.serialize(msg_out, s);
      Log.d("C3PO", "Sent notification of change");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #7
0
  /**
   * Helper method to convert the database representation of the date into something to display to
   * users. As classy and polished a user experience as "20140102" is, we can do better.
   *
   * @param context Context to use for resource localization
   * @param dateInMillis The date in milliseconds
   * @return a user-friendly representation of the date.
   */
  public static String getFriendlyDayString(Context context, long dateInMillis) {
    // The day string for forecast uses the following logic:
    // For today: "Today, June 8"
    // For tomorrow:  "Tomorrow"
    // For the next 5 days: "Wednesday" (just the day name)
    // For all days after that: "Mon Jun 8"

    Time time = new Time();
    time.setToNow();
    long currentTime = System.currentTimeMillis();
    int julianDay = Time.getJulianDay(dateInMillis, time.gmtoff);
    int currentJulianDay = Time.getJulianDay(currentTime, time.gmtoff);

    // If the date we're building the String for is today's date, the format
    // is "Today, June 24"
    if (julianDay == currentJulianDay) {
      String today = context.getString(R.string.today);
      int formatId = R.string.format_full_friendly_date;
      return String.format(
          context.getString(formatId, today, getFormattedMonthDay(context, dateInMillis)));
    } else if (julianDay < currentJulianDay + 7) {
      // If the input date is less than a week in the future, just return the day name.
      return getDayName(context, dateInMillis);
    } else {
      // Otherwise, use the form "Mon Jun 3"
      SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
      return shortenedDateFormat.format(dateInMillis);
    }
  }
 private void pauseRefresh() {
   isAnimDoing = true;
   textRefreshTop.setText(con.getString(R.string.library_refresh_start));
   textRefreshBottom.setText(con.getString(R.string.library_loadmore_start));
   doAnim2(imgArrawTop);
   doAnim(imgArrawBottom);
 }
  private void populateDiffs(PoiViewHolder holder, ViewGroup parent, PoiUpdateWrapper poiWrapper) {
    holder.getDetailsWrapper().removeAllViews();
    TagChangeViewHolder tagChangeViewHolder;

    if (poiWrapper.isPositionChanged()) {
      View positionChanged = inflater.inflate(R.layout.single_changes_line_layout, parent, false);
      tagChangeViewHolder = new TagChangeViewHolder(positionChanged);
      String positionChangedStr =
          HtmlFontHelper.getBold(context.getString(R.string.position))
              + HtmlFontHelper.addColor(context.getString(R.string.changed), HtmlFontHelper.ORANGE);
      tagChangeViewHolder
          .getNewTag()
          .setText(Html.fromHtml(positionChangedStr), TextView.BufferType.SPANNABLE);
      holder.getDetailsWrapper().addView(positionChanged);
    }

    for (PoiDiffWrapper poiDiffWrapper : poiWrapper.getPoiDiff()) {
      View singleLine = inflater.inflate(R.layout.single_changes_line_layout, parent, false);

      tagChangeViewHolder = new TagChangeViewHolder(singleLine);
      tagChangeViewHolder
          .getNewTag()
          .setText(
              Html.fromHtml(poiDiffWrapper.getColoredDetail(true)), TextView.BufferType.SPANNABLE);
      tagChangeViewHolder
          .getOldTag()
          .setText(
              Html.fromHtml(poiDiffWrapper.getColoredDetail(false)), TextView.BufferType.SPANNABLE);

      holder.getDetailsWrapper().addView(singleLine);
    }
  }
Exemple #10
0
 /**
  * Wrapper to set status to disabled
  *
  * @param context
  */
 public static void updateStatusDisabled(Context context) {
   setStatusBroadcast(
       context,
       context.getString(R.string.status_disabled),
       context.getString(R.string.status_disabled_subtitle),
       StatusCodes.DISABLED);
 }
  private void showNotification(Context context) {
    nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent intent = new Intent(context, MoodPopUp.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra(Constants.REMINDER_ID, reminderID);
    int notifRequestCode = 6000 + requestCode;
    PendingIntent pendingIntent =
        PendingIntent.getActivity(
            context, notifRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder notificationBuilder =
        new Notification.Builder(context)
            .setContentIntent(pendingIntent)
            .setContentText(context.getString(R.string.popup_title))
            .setSmallIcon(R.drawable.ic_mood_notification_icon)
            .setWhen(System.currentTimeMillis())
            .setTicker(context.getString(R.string.popup_title))
            .setContentTitle(context.getString(R.string.popup_mood_text))
            .setDefaults(Notification.DEFAULT_SOUND)
            .setAutoCancel(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      notificationBuilder.setColor(context.getResources().getColor(R.color.darkPurple));
    }

    Notification notification = notificationBuilder.build();
    notification.deleteIntent =
        PendingIntent.getBroadcast(context, notifRequestCode, getDeleteIntent(context), 0);
    Log.i(TAG, "Notified. reminder ID = " + reminderID);
    nm.notify(notifRequestCode, notification);
  }
Exemple #12
0
  public static String getArtUrlForWeatherCondition(Context context, int weatherId) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String formatArtUrl =
        prefs.getString(
            context.getString(R.string.pref_art_pack_key),
            context.getString(R.string.pref_art_pack_sunshine));

    // Based on weather code data found at:
    // http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
    if (weatherId >= 200 && weatherId <= 232) {
      return String.format(Locale.US, formatArtUrl, "storm");
    } else if (weatherId >= 300 && weatherId <= 321) {
      return String.format(Locale.US, formatArtUrl, "light_rain");
    } else if (weatherId >= 500 && weatherId <= 504) {
      return String.format(Locale.US, formatArtUrl, "rain");
    } else if (weatherId == 511) {
      return String.format(Locale.US, formatArtUrl, "snow");
    } else if (weatherId >= 520 && weatherId <= 531) {
      return String.format(Locale.US, formatArtUrl, "rain");
    } else if (weatherId >= 600 && weatherId <= 622) {
      return String.format(Locale.US, formatArtUrl, "snow");
    } else if (weatherId >= 701 && weatherId <= 761) {
      return String.format(Locale.US, formatArtUrl, "fog");
    } else if (weatherId == 761 || weatherId == 781) {
      return String.format(Locale.US, formatArtUrl, "storm");
    } else if (weatherId == 800) {
      return String.format(Locale.US, formatArtUrl, "clear");
    } else if (weatherId == 801) {
      return String.format(Locale.US, formatArtUrl, "light_clouds");
    } else if (weatherId >= 802 && weatherId <= 804) {
      return String.format(Locale.US, formatArtUrl, "clouds");
    }
    return null;
  }
Exemple #13
0
 /**
  * Helper method to return whether or not Sunshine is using local graphics.
  *
  * @param context Context to use for retrieving the preference
  * @return true if Sunshine is using local graphics, false otherwise.
  */
 public static boolean usingLocalGraphics(Context context) {
   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
   String sunshineArtPack = context.getString(R.string.pref_art_pack_sunshine);
   return prefs
       .getString(context.getString(R.string.pref_art_pack_key), sunshineArtPack)
       .equals(sunshineArtPack);
 }
 private void getDownloadStatus(Context context, int status, int reason) {
   switch (status) {
     case DownloadManager.STATUS_SUCCESSFUL:
       Toast.makeText(
               context,
               String.format(context.getString(R.string.successful), productName),
               Toast.LENGTH_LONG)
           .show();
       break;
     case DownloadManager.STATUS_FAILED:
       Toast.makeText(context, context.getString(R.string.failed) + reason, Toast.LENGTH_LONG)
           .show();
       break;
     case DownloadManager.STATUS_PAUSED:
       Toast.makeText(context, context.getString(R.string.paused) + reason, Toast.LENGTH_LONG)
           .show();
       break;
     case DownloadManager.STATUS_PENDING:
       Toast.makeText(context, R.string.pending, Toast.LENGTH_LONG).show();
       break;
     case DownloadManager.STATUS_RUNNING:
       Toast.makeText(context, R.string.running, Toast.LENGTH_LONG).show();
       break;
   }
 }
  public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();
    if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
      final int level = intent.getIntExtra(BatteryManager.EXTRA_DOCK_LEVEL, 0);
      mDockStatus =
          intent.getIntExtra(
              BatteryManager.EXTRA_DOCK_STATUS, BatteryManager.DOCK_BATTERY_STATUS_UNKNOWN);
      mDockPresent = intent.getBooleanExtra(BatteryManager.EXTRA_DOCK_PRESENT, false);

      int N = mIconViews.size();
      for (int i = 0; i < N; i++) {
        ImageView v = mIconViews.get(i);
        v.setImageLevel(level);
        v.setContentDescription(mContext.getString(R.string.accessibility_battery_level, level));
      }

      N = mLabelViews.size();
      for (int i = 0; i < N; i++) {
        TextView v = mLabelViews.get(i);
        v.setText(mContext.getString(BATTERY_TEXT_STYLE_MIN, level));
      }

      updateBattery();
    }
  }
Exemple #16
0
 public void updateDetails() {
   SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
   String yes = mContext.getString(R.string.gcm_yes);
   String no = mContext.getString(R.string.gcm_no);
   Boolean pref_year7 = preferences.getBoolean("pref_year7", false);
   Boolean pref_year8 = preferences.getBoolean("pref_year8", false);
   Boolean pref_year9 = preferences.getBoolean("pref_year9", false);
   Boolean pref_year10 = preferences.getBoolean("pref_year10", false);
   Boolean pref_year11 = preferences.getBoolean("pref_year11", false);
   Boolean pref_year12 = preferences.getBoolean("pref_year12", false);
   Boolean pref_year13 = preferences.getBoolean("pref_year13", false);
   email = preferences.getString("email", null);
   if (pref_year7) year7 = yes;
   else year7 = no;
   if (pref_year8) year8 = yes;
   else year8 = no;
   if (pref_year9) year9 = yes;
   else year9 = no;
   if (pref_year10) year10 = yes;
   else year10 = no;
   if (pref_year11) year11 = yes;
   else year11 = no;
   if (pref_year12) year12 = yes;
   else year12 = no;
   if (pref_year13) year13 = yes;
   else year13 = no;
   if (gcm == null) gcm = GoogleCloudMessaging.getInstance(mContext);
   if (!getRegistrationId().isEmpty()) update();
 }
  private String hostNameMessage(X509Certificate cert, String hostname) {
    StringBuffer si = new StringBuffer();

    si.append(master.getString(R.string.mtm_hostname_mismatch, hostname));
    si.append("\n\n");
    try {
      Collection<List<?>> sans = cert.getSubjectAlternativeNames();
      if (sans == null) {
        si.append(cert.getSubjectDN());
        si.append("\n");
      } else
        for (List<?> altName : sans) {
          Object name = altName.get(1);
          if (name instanceof String) {
            si.append("[");
            si.append((Integer) altName.get(0));
            si.append("] ");
            si.append(name);
            si.append("\n");
          }
        }
    } catch (CertificateParsingException e) {
      e.printStackTrace();
      si.append("<Parsing error: ");
      si.append(e.getLocalizedMessage());
      si.append(">\n");
    }
    si.append("\n");
    si.append(master.getString(R.string.mtm_connect_anyway));
    si.append("\n\n");
    si.append(master.getString(R.string.mtm_cert_details));
    certDetails(si, cert);
    return si.toString();
  }
  /**
   * 指定のIntentがNotActivityFoundExceptionにならずに使えるか調べる<br>
   * 処理できるアプリが存在しない場合指定のアプリをダウンロードさせる
   *
   * @param context
   * @param intent 処理できるか調べたいIntent
   * @param appName 処理できなかったときダウンロードさせるアプリの名前
   * @param packageName 処理できなかったときダウンロードさせるアプリのpackage名
   * @return 処理できるならtrue, 処理できないならfalse
   */
  public static boolean canResolveActivity(
      Context context, Intent intent, String appName, String packageName) {
    sContext = context;

    ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(intent, 0);

    // 対応できるAppがインストールされていればそのまま処理
    if (resolveInfo != null) {
      return true;
    }

    // なければ、Marketに取得しにいくか聞く。
    sPackageName = packageName;
    AlertDialog.Builder diagBldr = new AlertDialog.Builder(context);
    diagBldr.setTitle(context.getString(R.string.cant_resolve_intent_title, appName));
    diagBldr.setMessage(context.getString(R.string.cant_resolve_intent_message));

    diagBldr.setPositiveButton(context.getString(R.string.go_market), sOnClick);
    diagBldr.setNegativeButton(context.getString(R.string.ignore), sOnClick);

    diagBldr.setCancelable(true);
    diagBldr.create();
    diagBldr.show();

    return false;
  }
  /**
   * Helper method to get the fake account to be used with SyncAdapter, or make a new one if the
   * fake account doesn't exist yet. If we make a new account, we call the onAccountCreated method
   * so we can initialize things.
   *
   * @param context The context used to access the account service
   * @return a fake account.
   */
  public static Account getSyncAccount(Context context) {
    // Get an instance of the Android account manager
    AccountManager accountManager =
        (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);

    // Create the account type and default account
    Account newAccount =
        new Account(
            context.getString(R.string.app_name), context.getString(R.string.sync_account_type));

    // If the password doesn't exist, the account doesn't exist
    if (null == accountManager.getPassword(newAccount)) {

      /*
       * Add the account and account type, no password or user data
       * If successful, return the Account object, otherwise report an error.
       */
      if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
        return null;
      }
      /*
       * If you don't set android:syncable="true" in
       * in your <provider> element in the manifest,
       * then call ContentResolver.setIsSyncable(account, AUTHORITY, 1)
       * here.
       */
      onAccountCreated(newAccount, context);
    }
    return newAccount;
  }
 private void bingSong(ViewHolder holder, LabelStory story) {
   if (LabelStory.TYPE_ONLINEAUDIO.equals(story.getType())) {
     if (story.getThumbImages() != null) {
       AvatarManager.getInstance(context)
           .displaySingerAvatar(
               story.getThumbImages()[0], holder.mAnimView, R.drawable.ic_sound_pic_normal);
     }
     JSONObject jsonObject = VoiceUtiles.getContentJson(story.getContent());
     if (jsonObject != null) {
       holder.songName.setText(
           jsonObject.optString(CommandFields.Dynamic.SONG_NAME) == null
               ? context.getString(R.string.song_name, context.getString(R.string.music_unknown))
               : context.getString(
                   R.string.song_name, jsonObject.optString(CommandFields.Dynamic.SONG_NAME)));
       holder.singName.setText(
           jsonObject.optString(CommandFields.Dynamic.SINGER_NAME) == null
               ? context.getString(
                   R.string.singer_name, context.getString(R.string.music_unknown))
               : context.getString(
                   R.string.singer_name,
                   jsonObject.optString(CommandFields.Dynamic.SINGER_NAME)));
       holder.titleText.setText(jsonObject.optString(CommandFields.Dynamic.DYNAMIC_CONTENT));
     }
   } else {
     holder.titleText.setText(story.getContent());
     holder.mAnimView.setImageResource(R.drawable.ic_sound_play);
     holder.songName.setText(
         context.getString(R.string.song_name, context.getString(R.string.music_unknown)));
     holder.singName.setText(
         context.getString(R.string.singer_name, context.getString(R.string.music_unknown)));
   }
 }
  public void launchNotification(Context context, Events event) throws Exception {
    NotificationManager nManager =
        (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Log.e("Notification", "Notification up");

    NotificationCompat.Builder notificationBuilder =
        new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_event_white_36dp)
            .setContentTitle(context.getString(R.string.app_name))
            .setContentText(
                context.getString(R.string.notification1)
                    + " "
                    + event.getTitle()
                    + context.getString(R.string.notification2));

    Intent i = new Intent(context, EventFragment.class);
    i.putExtra("image", event.getImage());
    i.putExtra("title", event.getTitle());
    i.putExtra("description", event.getDescription());
    i.putExtra("date", event.getDate());
    i.putExtra("price", event.getPrice());
    i.putExtra("time", event.getTime());
    i.putExtra("notification", 0);

    PendingIntent contentIntent =
        PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    notificationBuilder.setContentIntent(contentIntent);
    notificationBuilder.setAutoCancel(true);

    nManager.notify(123, notificationBuilder.build());
  }
  public void onClick(View view) {
    final Context context = view.getContext();

    AlertDialog.Builder dialog = new AlertDialog.Builder(context);
    final EditText input = new EditText(context);
    input.setText(String.valueOf(degrees));
    input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
    input.setSelectAllOnFocus(true);
    dialog.setView(input);
    dialog.setOnCancelListener((OnCancelListener) context);
    dialog.setPositiveButton(
        context.getString(R.string.ok),
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
            try {
              degrees = Double.parseDouble(input.getText().toString());
            } catch (NumberFormatException exception) {
              Toast.makeText(context, R.string.error_no_number_entered, Toast.LENGTH_SHORT).show();
            }
            dialog.cancel();
          }
        });
    dialog.setNeutralButton(
        context.getString(R.string.cancel_button),
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
          }
        });

    AlertDialog finishedDialog = dialog.create();
    finishedDialog.setOnShowListener(Utils.getBrickDialogOnClickListener(context, input));

    finishedDialog.show();
  }
Exemple #23
0
  /**
   * Deal with a synchronization exception. If requested, will show an error to the user (unless
   * synchronization is happening in background)
   *
   * @param context
   * @param tag error tag
   * @param e exception
   * @param showError whether to display a dialog
   */
  protected void handleException(String tag, Exception e, boolean displayError) {
    // TODO: When Crittercism supports it, report error to them
    final Context context = ContextManager.getContext();
    getUtilities().setLastError(e.toString());

    String message = null;

    // occurs when application was closed
    if (e instanceof IllegalStateException) {
      exceptionService.reportError(tag + "-caught", e); // $NON-NLS-1$
    }

    // occurs when network error
    else if (e instanceof IOException) {
      exceptionService.reportError(tag + "-io", e); // $NON-NLS-1$
      message = context.getString(R.string.SyP_ioerror);
    }

    // unhandled error
    else {
      message = context.getString(R.string.DLG_error, e.toString());
      exceptionService.reportError(tag + "-unhandled", e); // $NON-NLS-1$
    }

    if (displayError && context instanceof Activity && message != null) {
      DialogUtilities.okDialog((Activity) context, message, null);
    }
  }
    @Override
    public void onDownloadFinished(Context context, DownloadsUtil.DownloadInfo info) {
      File localFile = new File(info.localFilename);
      if (!localFile.isFile()) return;

      if (moduleVersion.md5sum != null && !moduleVersion.md5sum.isEmpty()) {
        try {
          String actualMd5Sum = HashUtil.md5(localFile);
          if (!moduleVersion.md5sum.equals(actualMd5Sum)) {
            Toast.makeText(
                    context,
                    context.getString(
                        R.string.download_md5sum_incorrect, actualMd5Sum, moduleVersion.md5sum),
                    Toast.LENGTH_LONG)
                .show();
            DownloadsUtil.removeById(context, info.id);
            return;
          }
        } catch (Exception e) {
          Toast.makeText(
                  context,
                  context.getString(R.string.download_could_not_read_file, e.getMessage()),
                  Toast.LENGTH_LONG)
              .show();
          DownloadsUtil.removeById(context, info.id);
          return;
        }
      }

      PackageManager pm = context.getPackageManager();
      PackageInfo packageInfo = pm.getPackageArchiveInfo(info.localFilename, 0);

      if (packageInfo == null) {
        Toast.makeText(context, R.string.download_no_valid_apk, Toast.LENGTH_LONG).show();
        DownloadsUtil.removeById(context, info.id);
        return;
      }

      if (!packageInfo.packageName.equals(moduleVersion.module.packageName)) {
        Toast.makeText(
                context,
                context.getString(
                    R.string.download_incorrect_package_name,
                    packageInfo.packageName,
                    moduleVersion.module.packageName),
                Toast.LENGTH_LONG)
            .show();
        DownloadsUtil.removeById(context, info.id);
        return;
      }

      Intent installIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
      installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      installIntent.setDataAndType(Uri.fromFile(localFile), DownloadsUtil.MIME_TYPE_APK);
      // installIntent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
      // installIntent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
      installIntent.putExtra(
          Intent.EXTRA_INSTALLER_PACKAGE_NAME, context.getApplicationInfo().packageName);
      context.startActivity(installIntent);
    }
  public void showIssue(final String issue) {
    LayoutInflater inflate =
        (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflate.inflate(R.layout.touzhu_succe, null);
    final AlertDialog dialog = new AlertDialog.Builder(context).create();
    TextView textContent = (TextView) view.findViewById(R.id.touzhu_succe_text);
    Button ok = (Button) view.findViewById(R.id.touzhu_succe_button_sure);
    Button cancel = (Button) view.findViewById(R.id.touzhu_succe_button_share);
    ok.setBackgroundResource(R.drawable.loginselecter);
    cancel.setBackgroundResource(R.drawable.loginselecter);
    ok.setText(context.getString(R.string.dialog_issue_text_ok));
    cancel.setText(context.getString(R.string.dialog_issue_text_cancel));
    textContent.setText(context.getString(R.string.dialog_issue_text_content) + issue + "期。");
    ok.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            dialog.cancel();
            touzhuIssue(issue);
          }
        });
    cancel.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            dialog.cancel();
            finish();
          }
        });

    dialog.show();
    dialog.getWindow().setContentView(view);
  }
  /**
   * Choosing which date must be shown depending on sorting criteria
   *
   * @return String ith formatted date
   */
  public static String getDateText(Context mContext, Note note) {
    String dateText;
    SharedPreferences prefs =
        mContext.getSharedPreferences(Constants.PREFS_NAME, mContext.MODE_MULTI_PROCESS);
    String sort_column = prefs.getString(Constants.PREF_SORTING_COLUMN, "");

    // Creation
    if (sort_column.equals(DbHelper.KEY_CREATION)) {
      dateText = mContext.getString(R.string.creation) + " " + note.getCreationShort(mContext);
    }
    // Reminder
    else if (sort_column.equals(DbHelper.KEY_ALARM)) {
      String alarmShort = note.getAlarmShort(mContext);

      if (alarmShort.length() == 0) {
        dateText = mContext.getString(R.string.no_reminder_set);
      } else {
        dateText = mContext.getString(R.string.alarm_set_on) + " " + note.getAlarmShort(mContext);
      }
    }
    // Others
    else {
      dateText =
          mContext.getString(R.string.last_update) + " " + note.getLastModificationShort(mContext);
    }
    return dateText;
  }
  public RC3500_A_IP44_DE(
      Context context, Long id, String name, LinkedList<Boolean> dips, Long roomId) {
    super(context, id, name, BRAND, MODEL, TYPE_DIPS, roomId);
    dipList = new LinkedList<>();

    if (dips != null && dips.size() == 10) {
      dipList.add(new DipSwitch("1", dips.get(0)));
      dipList.add(new DipSwitch("2", dips.get(1)));
      dipList.add(new DipSwitch("3", dips.get(2)));
      dipList.add(new DipSwitch("4", dips.get(3)));
      dipList.add(new DipSwitch("5", dips.get(4)));
      dipList.add(new DipSwitch("A", dips.get(5)));
      dipList.add(new DipSwitch("B", dips.get(6)));
      dipList.add(new DipSwitch("C", dips.get(7)));
      dipList.add(new DipSwitch("D", dips.get(8)));
      dipList.add(new DipSwitch("E", dips.get(9)));
    } else {
      dipList.add(new DipSwitch("1", false));
      dipList.add(new DipSwitch("2", false));
      dipList.add(new DipSwitch("3", false));
      dipList.add(new DipSwitch("4", false));
      dipList.add(new DipSwitch("5", false));
      dipList.add(new DipSwitch("A", false));
      dipList.add(new DipSwitch("B", false));
      dipList.add(new DipSwitch("C", false));
      dipList.add(new DipSwitch("D", false));
      dipList.add(new DipSwitch("E", false));
    }

    buttons.add(new Button(Button.BUTTON_ON_ID, context.getString(R.string.on), id));
    buttons.add(new Button(Button.BUTTON_OFF_ID, context.getString(R.string.off), id));
  }
Exemple #28
0
  /**
   * @see Message for default values to understand behaviour of overloaded methods broadcasts error
   *     and logs it
   */
  @Background
  public void showError(Message message) {
    if (message == null) {
      throw new IllegalArgumentException("null message");
    }
    ErrorType errorType = message.getType();
    String header = message.getHeader();
    String detail = message.getDetail();
    Integer logPriority = message.getLogPriority();

    String finalMessage;

    switch (message.getType()) {
      case REST_MINOR:
      case REST_MAJOR:
        finalMessage =
            context.getString(R.string.rest_request_failed, getConnectionDetails() + detail);
        break;
      default:
        finalMessage =
            header == null
                ? detail
                : context.getString(R.string.message_detailed_info, header, detail);
        break;
    }

    if (logPriority == null) {
      logPriority = errorType.getDefaultLogPriority();
    }

    showError(errorType, logPriority, finalMessage);
  }
  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d(this.getClass().toString(), "alarm received");
    NotificationManager notificationManager =
        (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent notificationIntent = new Intent(context, HourlyreminderActivity.class);
    PendingIntent pendingIntent =
        PendingIntent.getActivity(
            context, REQUESTCODE, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder builder = new Notification.Builder(context);
    builder
        .setContentIntent(pendingIntent)
        .setSmallIcon(R.drawable.alarm_icon)
        .setTicker(context.getString(R.string.notification_status_bar_text))
        .setWhen(System.currentTimeMillis())
        .setAutoCancel(true)
        .setDefaults(Notification.DEFAULT_ALL)
        .setContentTitle(context.getString(R.string.notification_title))
        .setContentText(context.getString(R.string.notification_message));
    Notification notification = builder.getNotification();
    // TODO: text updaten bij meerdere

    notificationManager.notify(1, notification);
    Log.d(this.getClass().toString(), "notification send");
  }
  public RemoteViews getRemoteViews(Context context, int id, String date) {
    RemoteViews remoteViews =
        new RemoteViews(context.getPackageName(), R.layout.appwidget_timetable);
    Application.getComponent(context).inject(this);
    User user = mSharedPreferenceHelper.getUser();
    mSharedPreferenceHelper.setDateForWidget(date);
    remoteViews.setTextViewText(R.id.value_widget, user.getTitleValue());
    if (user.getType() < 2) {
      if (TimetableUtils.getDayOfWeek(date)
              == TimetableUtils.getDayOfWeek(TimetableUtils.todayDate())
          && TimetableUtils.getParity(date) == TimetableUtils.getParity(TimetableUtils.todayDate()))
        remoteViews.setTextViewText(
            R.id.day_widget,
            String.format(context.getString(R.string.today), TimetableUtils.getDayOfWeek(date)));
      else remoteViews.setTextViewText(R.id.day_widget, TimetableUtils.getDayOfWeek(date));
      remoteViews.setTextViewText(R.id.date_widget, TimetableUtils.getParity(date) + " неделя");
    } else {
      if (TimetableUtils.todayDate().equals(date))
        remoteViews.setTextViewText(
            R.id.day_widget,
            String.format(context.getString(R.string.today), TimetableUtils.getDayOfWeek(date)));
      else remoteViews.setTextViewText(R.id.day_widget, TimetableUtils.getDayOfWeek(date));

      remoteViews.setTextViewText(R.id.date_widget, TimetableUtils.getDayAndMonth(date));
    }
    setUpPreviousButton(context, remoteViews, id, date);
    setUpNextButton(context, remoteViews, id, date);
    setUpTodayButton(context, remoteViews, id);
    setUpAdapter(context, remoteViews, id, date);
    setUpHeaderClick(context, remoteViews, id);
    return remoteViews;
  }