/**
   * Called when the BroadcastReceiver receives an Intent broadcast. Checks to see whether the
   * intent's action is _listClickAction. If it is, the app widget displays a Toast message for the
   * current item.
   */
  @Override
  public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(_listClickAction)) {
      // ---Launch video search in the browser---
      String searchText = intent.getStringExtra("search_text");
      String linkScheme1 = intent.getStringExtra("scheme1");
      String linkScheme2 = intent.getStringExtra("scheme2");
      Intent browserIntent = null; // new Intent(_listClickAction);
      try {
        browserIntent =
            new Intent(
                Intent.ACTION_VIEW,
                Uri.parse(linkScheme1 + URLEncoder.encode(searchText, "UTF-8") + linkScheme2));
      } catch (UnsupportedEncodingException e) {
        BugSenseHandler.sendExceptionMessage("Widget4x4Provider", "onReceive", e);
        Crashlytics.setString("Widget4x4Provider", "onReceive");
        Crashlytics.logException(e);

        if (ApplicationContext.DEBUG_MODE) e.printStackTrace();
      }

      browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      browserIntent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
      context.startActivity(browserIntent);
    } else if (intent.getAction().equals("android.appwidget.action.APPWIDGET_UPDATE")) {
      // ---Update the widget with latest search---
      final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
      onUpdate(context, mgr, appWidgetIds);
    }
    super.onReceive(context, intent);
  }
  /** Issues a notification to inform the user that server has sent a message. */
  private static void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager =
        (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    String title = context.getString(R.string.app_name);

    Intent notificationIntent = new Intent(context, MainActivity.class);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    // Play default notification sound
    notification.defaults |= Notification.DEFAULT_SOUND;

    // notification.sound = Uri.parse("android.resource://" + context.getPackageName() +
    // "your_sound_file_name.mp3");

    // Vibrate if vibrate is enabled
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0, notification);
  }
Example #3
0
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    TaskViewHolder holder;
    if (convertView == null) {
      LayoutInflater inflater =
          (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      convertView = inflater.inflate(row, null);
      holder = new TaskViewHolder();
      convertView.setTag(holder);
    } else {
      holder = (TaskViewHolder) convertView.getTag();
    }

    if ((tours == null) || ((position + 1) > tours.size()))
      return convertView; // Can't extract item

    Tour obj = tours.get(position);
    holder.image = (ImageView) convertView.findViewById(R.id.tourImage);
    Drawable img =
        mContext
            .getResources()
            .getDrawable(
                mContext
                    .getResources()
                    .getIdentifier(obj.getImage(), "drawable", mContext.getPackageName()));
    holder.image.setImageDrawable(img);
    holder.name = (TextView) convertView.findViewById(R.id.tourNameLbl);
    holder.name.setText(obj.getName());
    holder.totalHours = (TextView) convertView.findViewById(R.id.totalHoursLbl);
    holder.totalHours.setText(obj.getTotalHours() + "h");
    holder.totalKms = (TextView) convertView.findViewById(R.id.totalKmsLbl);
    holder.totalKms.setText(obj.getTotalKms() + "Km");

    return convertView;
  }
 public static int getLeftDrawerWidth(Context ctx) {
   Configuration config = ctx.getResources().getConfiguration();
   int screenWidthDp = Math.round(dpToPx(ctx.getResources(), config.smallestScreenWidthDp));
   int toolbarHeight = getDimenFromAttribute(ctx, R.attr.actionBarSize);
   return Math.min(
       screenWidthDp - toolbarHeight, dimenInPx(ctx.getResources(), R.dimen.drawer_max_width));
 }
Example #5
0
  public static void postIModNotification(Context context) {
    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    if (!MLPreferences.getPrefsApps(context)
        .getBoolean(Common.SHOW_IMOD_RESET_NOTIFICATION, false)) {
      nm.cancel(IMOD_NOTIFICATION_ID);
      return;
    }
    Intent notifyIntent = new Intent(context, ActionActivity.class);
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notifyIntent.putExtra(ActionsHelper.ACTION_EXTRA_KEY, R.id.radio_imod_reset);

    NotificationCompat.Builder builder =
        new NotificationCompat.Builder(context)
            .setContentTitle(context.getString(R.string.action_imod_reset))
            .setContentText("")
            .setSmallIcon(R.drawable.ic_apps_24dp)
            .setContentIntent(
                PendingIntent.getActivity(
                    context.getApplicationContext(),
                    0,
                    notifyIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT))
            .setOngoing(true)
            .setAutoCancel(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
      builder.setShowWhen(false);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      builder
          .setPriority(NotificationCompat.PRIORITY_MIN)
          .setCategory(NotificationCompat.CATEGORY_STATUS)
          .setColor(ContextCompat.getColor(context, R.color.accent));
    }
    nm.notify(IMOD_NOTIFICATION_ID, builder.build());
  }
Example #6
0
  void initCustomViewAbove() {
    //		setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
    setDescendantFocusability(FOCUS_BEFORE_DESCENDANTS);
    setClickable(true);
    setFocusable(true);
    setWillNotDraw(false);
    final Context context = getContext();
    mScroller = new Scroller(context, sInterpolator);
    final ViewConfiguration configuration = ViewConfiguration.get(context);
    mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
    mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
    mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
    setInternalPageChangeListener(
        new SimpleOnPageChangeListener() {
          public void onPageSelected(int position) {
            if (mViewBehind != null) {
              switch (position) {
                case 0:
                case 2:
                  mViewBehind.setChildrenEnabled(true);
                  break;
                case 1:
                  mViewBehind.setChildrenEnabled(false);
                  break;
              }
            }
          }
        });

    final float density = context.getResources().getDisplayMetrics().density;
    mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density);
  }
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    LayoutInflater vi;
    vi = LayoutInflater.from(mContext);
    v = vi.inflate(R.layout.categories_listview_items, null);
    Category c = getItem(position);

    if (c != null) {

      TextView name = (TextView) v.findViewById(R.id.categories_listview_items_name);
      ImageView icon = (ImageView) v.findViewById(R.id.categories_listview_items_icon);

      if (name != null) {

        name.setTypeface(typeface);
        name.setText(c.getName());
      }
      if (icon != null)
        icon.setImageResource(
            mContext
                .getResources()
                .getIdentifier(c.getIconFileName(), "drawable", mContext.getPackageName()));
    }

    return v;
  }
  @Override
  public int delete(Uri uri, String selection, String[] selectionArgs) {
    SelectionBuilder builder = new SelectionBuilder();
    final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
    final int match = sUriMatcher.match(uri);
    int count;
    switch (match) {
      case ROUTE_EMOTES:
        count =
            builder
                .table(EmotesContract.Emote.TABLE_NAME)
                .where(selection, selectionArgs)
                .delete(db);
        break;
      case ROUTE_EMOTES_ID:
        String id = uri.getLastPathSegment();
        count =
            builder
                .table(EmotesContract.Emote.TABLE_NAME)
                .where(EmotesContract.Emote._ID + "=?", id)
                .where(selection, selectionArgs)
                .delete(db);
        break;
      default:
        throw new UnsupportedOperationException("Unknown uri: " + uri);
    }

    // Send broadcast to registered ContentObservers, to refresh UI.
    Context ctx = getContext();
    assert ctx != null;
    ctx.getContentResolver().notifyChange(uri, null, false);

    return count;
  }
Example #9
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();
    }
  }
  public void RefreshTotalChecked(
      TextView totalCheckedTextView, TextView tvName, LinearLayout layout, int position) {
    ShoppingList shoppingList = shoppingLists.get(position);
    String text =
        DataManager.shoppingListGetChecked(shoppingList) + "/" + shoppingList.getItems().size();
    totalCheckedTextView.setText(text);

    boolean shoppingListIsChecked = DataManager.shoppingListIsChecked(shoppingList);
    if (shoppingListIsChecked) {
      DataManager.setShoppingListIsChecked(shoppingList, true);
      layout
          .getBackground()
          .setColorFilter(
              context.getResources().getColor(R.color.itemListBackgroundChecked),
              PorterDuff.Mode.MULTIPLY);
      tvName.setPaintFlags(tvName.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
    } else {
      DataManager.setShoppingListIsChecked(shoppingList, false);
      layout
          .getBackground()
          .setColorFilter(
              context.getResources().getColor(R.color.itemListBackground),
              PorterDuff.Mode.MULTIPLY);
      tvName.setPaintFlags(tvName.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
    }
  }
Example #11
0
  static void answerfix(Context context) {
    try {
      Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON);
      buttonDown.putExtra(
          Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
      context.sendOrderedBroadcast(buttonDown, "android.permission.CALL_PRIVILEGED");

      // froyo and beyond trigger on buttonUp instead of buttonDown
      Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
      buttonUp.putExtra(
          Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
      context.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");

      Intent headSetUnPluggedintent = new Intent(Intent.ACTION_HEADSET_PLUG);
      headSetUnPluggedintent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
      headSetUnPluggedintent.putExtra("state", 1); // 0 = unplugged 1 =
      // Headset with
      // microphone 2 =
      // Headset without
      // microphone
      headSetUnPluggedintent.putExtra("name", "Headset");
      // TODO: Should we require a permission?
      context.sendOrderedBroadcast(headSetUnPluggedintent, null);

    } catch (Exception e) {

    }
  }
Example #12
0
  /**
   * Create and returns the Bitmap image from local storage optimized by size
   *
   * @param imageID - filename of the image
   * @param reqSize - maximum side of image returns default image (DEFAULT_IMAGE_NAME) if image
   *     can't be loaded used in ArticleViewAdapter.getView()
   */
  public static Bitmap getBitmapFromStorage(Context context, String imageID, int reqSize) {
    Log.d(TAG, ".getBitmapFromFilePath(), image=" + imageID + ", size=" + reqSize);

    Bitmap result = null;
    // construct full file name
    String fileName = imageID + JPEG_SUFFIX;
    File imageFile = new File(context.getExternalFilesDir(Utils.TYPE_PICTURE), fileName);

    // if image file exists trying to load, optimize and decode
    if (imageFile.exists()) {
      // First decode with inJustDecodeBounds=true to check dimensions
      BitmapFactory.Options bmOptions = new BitmapFactory.Options();
      bmOptions.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(imageFile.getAbsolutePath(), bmOptions);
      // Calculate inSampleSize
      bmOptions.inSampleSize = calculateImageInSampleSize(bmOptions, reqSize, reqSize);

      // Decode bitmap with inSampleSize set from file with given options
      bmOptions.inJustDecodeBounds = false;
      bmOptions.inPurgeable = true;
      result = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), bmOptions);
    }
    // if can't be loaded and decoded, load default image from local storage instead
    if (result == null) {
      Log.d(TAG, ".getBitmapFromFilePath(), cann't decode image:" + imageFile.getAbsolutePath());
      File file = new File(context.getExternalFilesDir(TYPE_PICTURE), DEFAULT_IMAGE_NAME);
      result = BitmapFactory.decodeFile(file.getAbsolutePath());
    }
    return result;
  }
Example #13
0
  public static String getDeviceID(Context context) {

    /*
     * The drawback of this approach is, if the service was opened when
     * the device is in airplane mode. MobiSens will think this is a
     * different phone.
     */
    if (globalDeviceID != null) {
      return globalDeviceID;
    }

    TelephonyManager telManager =
        (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    String deviceID = telManager.getDeviceId();

    if (deviceID == null) {
      WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
      WifiInfo wifiInf = wifiMan.getConnectionInfo();
      deviceID = wifiInf.getMacAddress();
    }

    globalDeviceID = deviceID;
    return globalDeviceID;
  }
Example #14
0
  public LanguageControl(Context context) {
    mContext = context;
    sp = PreferenceManager.getDefaultSharedPreferences(context);
    languageList.clear();
    languageList.add(
        new LanguageBean(
            mContext.getResources().getString(R.string.setup_name_language_china), CHINA));
    //		languageList.add(new LanguageBean(mContext
    //				.getString(R.string.setup_name_language_china_tw), CHINA_TW));
    languageList.add(
        new LanguageBean(mContext.getString(R.string.setup_name_language_English), ENGLISH));
    //		languageList.add(new LanguageBean(mContext
    //				.getString(R.string.setup_name_language_ar), AR));
    //		languageList.add(new LanguageBean(mContext
    //				.getString(R.string.setup_name_language_id), "id-ID"));
    //		languageList.add(new LanguageBean(mContext
    //				.getString(R.string.setup_name_language_pt), "pt"));
    //		languageList.add(new LanguageBean(mContext
    //				.getString(R.string.setup_name_language_vi), "vi"));
    //		languageList.add(new LanguageBean(mContext
    //				.getString(R.string.setup_name_language_ru), "ru"));

    // languageList.add(CHINA_CN);
    Locale locale = new Locale(CHINA_TW);
    //	SetWiFiActivity.writeLog("--------------" + locale.getLanguage());
  }
Example #15
0
  void registerSensorListeners() {
    if (config.useAccelerometer) {
      manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
      if (manager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() == 0) {
        accelerometerAvailable = false;
      } else {
        Sensor accelerometer = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
        accelerometerListener =
            new SensorListener(
                this.nativeOrientation, this.accelerometerValues, this.magneticFieldValues);
        accelerometerAvailable =
            manager.registerListener(
                accelerometerListener, accelerometer, SensorManager.SENSOR_DELAY_GAME);
      }
    } else accelerometerAvailable = false;

    if (config.useCompass) {
      if (manager == null)
        manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
      Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
      if (sensor != null) {
        compassAvailable = accelerometerAvailable;
        if (compassAvailable) {
          compassListener =
              new SensorListener(
                  this.nativeOrientation, this.accelerometerValues, this.magneticFieldValues);
          compassAvailable =
              manager.registerListener(compassListener, sensor, SensorManager.SENSOR_DELAY_GAME);
        }
      } else {
        compassAvailable = false;
      }
    } else compassAvailable = false;
    Gdx.app.log("AndroidInput", "sensor listener setup");
  }
  @Override
  public void onReceive(Context context, Intent intent) {

    Log.i("WifiO", "RecvTempDisable");

    LogWO logg = new LogWO(context);
    logg.log("WifiOpti Service disabled for 5m");

    SharedPreferences sett = context.getSharedPreferences("WifiOpti", 2);
    SharedPreferences.Editor settEditor = sett.edit();

    settEditor.putBoolean("WifiOptiServiced", false);
    settEditor.putBoolean("WifiOptiTempDisabled", true);
    settEditor.commit();

    // Turn off service
    Intent serviceIntent = new Intent(context, WifiOptiService.class);
    context.stopService(serviceIntent);

    // Schedule restart
    Intent alarmIntent = new Intent(context, RecvTempResume.class);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());
    cal.add(Calendar.MINUTE, 5);

    Log.d("WifiO", " -> " + cal.getTime().toString());

    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
  }
Example #17
0
  public void setAsCurrent() {
    if (mUri == null) {
      return;
    }
    Cursor cur = mContext.getContentResolver().query(mUri, null, null, null, null);
    cur.moveToFirst();
    int index = cur.getColumnIndex("_id");
    String apnId = cur.getString(index);
    cur.close();

    ContentValues values = new ContentValues();
    values.put("apn_id", apnId);
    if (mSlot == -1) {
      mContext
          .getContentResolver()
          .update(Uri.parse("content://telephony/carriers/preferapn"), values, null, null);
    } else {
      int simNo = mSlot + 1;
      mContext
          .getContentResolver()
          .update(
              Uri.parse("content://telephony/carriers_sim" + simNo + "/preferapn"),
              values,
              null,
              null);
    }
  }
  @Override
  public void storeTokenEntry(byte[] keyHandle, TokenEntry tokenEntry) {
    Boolean isSave = true;
    List<String> tokens = getTokenEntries();
    for (String tokenStr : tokens) {
      TokenEntry token = new Gson().fromJson(tokenStr, TokenEntry.class);
      if (token.getIssuer().equalsIgnoreCase(tokenEntry.getIssuer())) {
        isSave = false;
      }
    }
    if (isSave) {
      String keyHandleKey = keyHandleToKey(keyHandle);

      final String tokenEntryString = new Gson().toJson(tokenEntry);
      if (BuildConfig.DEBUG)
        Log.d(
            TAG,
            "Storing new keyHandle: " + keyHandleKey + " with tokenEntry: " + tokenEntryString);

      final SharedPreferences keySettings =
          context.getSharedPreferences(U2F_KEY_PAIR_FILE, Context.MODE_PRIVATE);

      keySettings.edit().putString(keyHandleKey, tokenEntryString).apply(); // commit();

      final SharedPreferences keyCounts =
          context.getSharedPreferences(U2F_KEY_COUNT_FILE, Context.MODE_PRIVATE);
      keyCounts.edit().putInt(keyHandleKey, 0).apply(); // commit();
    }
  }
Example #19
0
 /** 获取指定路径的apk的资源 */
 @SuppressWarnings({"rawtypes", "unchecked"})
 public static Resources getAPKResources(String apkPath) throws Exception {
   Context context = UIUtils.getContext();
   if (null == context) {
     return null;
   }
   String PathAssetManager = "android.content.res.AssetManager";
   Class assetMagCls = Class.forName(PathAssetManager);
   Constructor assetMagCt = assetMagCls.getConstructor((Class[]) null);
   Object assetMag = assetMagCt.newInstance((Object[]) null);
   Class[] typeArgs = new Class[1];
   typeArgs[0] = String.class;
   Method assetMagAddAssetPathMtd = assetMagCls.getDeclaredMethod("addAssetPath", typeArgs);
   Object[] valueArgs = new Object[1];
   valueArgs[0] = apkPath;
   assetMagAddAssetPathMtd.invoke(assetMag, valueArgs);
   Resources res = context.getResources();
   typeArgs = new Class[3];
   typeArgs[0] = assetMag.getClass();
   typeArgs[1] = res.getDisplayMetrics().getClass();
   typeArgs[2] = res.getConfiguration().getClass();
   Constructor resCt = Resources.class.getConstructor(typeArgs);
   valueArgs = new Object[3];
   valueArgs[0] = assetMag;
   valueArgs[1] = res.getDisplayMetrics();
   valueArgs[2] = res.getConfiguration();
   res = (Resources) resCt.newInstance(valueArgs);
   return res;
 }
Example #20
0
  public static void Show(
      final Context context, final SimpleCommandConsole cli, final KActivityStatus mStatus) {
    // mChecked = 1;
    LayoutInflater mLI = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final LinearLayout mLL = (LinearLayout) mLI.inflate(R.layout.alert_dialog_kuaipan_create, null);

    final EditText meditText = (EditText) mLL.findViewById(R.id.new_filename);

    Builder mBuilder =
        new AlertDialog.Builder(context)
            .setTitle(R.string.CreateKPFileDialog_title)
            .setView(mLL)
            .setPositiveButton(
                R.string.m_New,
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int which) {
                    String mNewFolderName = meditText.getText().toString().trim();
                    try {
                      cli.do_mkdir(mNewFolderName);
                      mStatus.KActivityResult(10, 1, 1, "");
                      Toast.makeText(context, "操作成功!", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                      e.printStackTrace();
                    }
                  }
                })
            .setNeutralButton(context.getString(R.string.cancel), null);
    mBuilder.show();
  }
  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));
  }
  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);
  }
  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);
  }
Example #24
0
 public void register(Context context, Looper thread, UserHandle user, boolean externalStorage) {
   if (mRegisteredContext != null) {
     throw new IllegalStateException("Already registered");
   }
   mRegisteredContext = context;
   if (thread == null) {
     synchronized (sLock) {
       if (sBackgroundThread == null) {
         sBackgroundThread =
             new HandlerThread("PackageMonitor", android.os.Process.THREAD_PRIORITY_BACKGROUND);
         sBackgroundThread.start();
         sBackgroundHandler = new Handler(sBackgroundThread.getLooper());
       }
       mRegisteredHandler = sBackgroundHandler;
     }
   } else {
     mRegisteredHandler = new Handler(thread);
   }
   if (user != null) {
     context.registerReceiverAsUser(this, user, sPackageFilt, null, mRegisteredHandler);
     context.registerReceiverAsUser(this, user, sNonDataFilt, null, mRegisteredHandler);
     if (externalStorage) {
       context.registerReceiverAsUser(this, user, sExternalFilt, null, mRegisteredHandler);
     }
   } else {
     context.registerReceiver(this, sPackageFilt, null, mRegisteredHandler);
     context.registerReceiver(this, sNonDataFilt, null, mRegisteredHandler);
     if (externalStorage) {
       context.registerReceiver(this, sExternalFilt, null, mRegisteredHandler);
     }
   }
 }
  /**
   * Creates a new CaptureRenderer, based on an Inside3dRenderer with the given mesh as Skybox.
   *
   * @param context - Context of the application.
   * @param skybox
   * @param cameraManager
   */
  public CaptureRenderer(Context context, Cube skybox, CameraManager cameraManager) {
    // based on Inside3dRenderer. We are inside a skybox.
    super(context);
    mSkybox = skybox;
    super.setSurroundingMesh(mSkybox);
    super.setFovDeg(DEFAULT_FOV_DEG);

    // init attributes
    mCameraManager = cameraManager;
    mCameraManager.addSnapshotEventListener(this);
    mContext = context;

    mMarkerBitmap = BitmapDecoder.safeDecodeBitmap(mContext.getResources(), MARKER_RESSOURCE_ID);
    mContourBitmap = BitmapDecoder.safeDecodeBitmap(mContext.getResources(), CONTOUR_RESSOURCE_ID);

    // if auto samplig enabled
    if (mSampleRate == 0) {
      mSampleRate = (int) mCameraManager.getCameraResolution();
      mSampleRate = (int) (ceilPowOf2(mSampleRate) / SNAPSHOT_AUTO_SAMPLE_RATIO);
    }

    mViewMatrix = new float[16];
    Matrix.setIdentityM(mViewMatrix, 0);

    // create dots and snapshot lists
    mSnapshots = new ArrayList<Snapshot3D>();
    mDots = new LinkedList<Snapshot3D>();
    mContours43 = new LinkedList<Snapshot3D>();
    mContours34 = new LinkedList<Snapshot3D>();
    mContours = mContours43;
    mTargetsLock = new ReentrantLock();
    mSnapshotsLock = new ReentrantLock();
  }
Example #26
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));
   }
 }
  @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");
  }
Example #28
0
  /** 对拖拽图片不同的点击事件处理 */
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    int X = (int) event.getX();

    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        dragBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.lock_touch);
        heartView.setImageBitmap(dragBitmap);
        linearLayoutL.setBackgroundResource(R.drawable.left_bg_default);
        linearLayoutR.setBackgroundResource(R.drawable.left_bg_default);
        locationX = (int) event.getX();
        Log.i(TAG, "是否点击到位=" + isActionDown(event));
        return isActionDown(event); // 判断是否点击了滑动区�?

      case MotionEvent.ACTION_MOVE: // 保存x轴方向,绘制图画
        locationX = X;
        invalidate(); // 重新绘图
        return true;

      case MotionEvent.ACTION_UP: // 判断是否解锁成功
        dragBitmap =
            BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_slide_circle_n);
        heartView.setImageBitmap(dragBitmap);
        linearLayoutL.setBackgroundColor(getResources().getColor(R.color.transparent));
        linearLayoutR.setBackgroundResource(getResources().getColor(R.color.transparent));
        if (!unLockLeft() && !unLockRight()) { // 没有解锁成功,动画应该回滚
          flag = false;
          handleActionUpEvent(event); // 动画回滚
        }
        return true;
    }
    return super.onTouchEvent(event);
  }
 private boolean loadDataFromSMS() {
   Uri uriSms = Uri.parse("content://sms/inbox");
   boolean loadResult = false;
   String sort_by = SMSViewingAdapter.SMS_DATE_FIELD + " DESC";
   Context context = getApplicationContext();
   Cursor inboxSMSCursor =
       context
           .getContentResolver()
           .query(
               uriSms,
               new String[] {
                 SMSViewingAdapter.SMS_ID_FIELD,
                 SMSViewingAdapter.SMS_DATE_FIELD,
                 SMSViewingAdapter.SMS_BODY_FIELD
               },
               null,
               null,
               sort_by);
   loadResult = true;
   if ((inboxSMSCursor != null) && (inboxSMSCursor.moveToFirst())) {
     SMSParcer smsParcer = new SMSParcer();
     // for (int j = 0; j < 10000000; j++);
     do {
       smsParcer.setParcedString(
           inboxSMSCursor.getString(
               inboxSMSCursor.getColumnIndex(SMSViewingAdapter.SMS_BODY_FIELD)));
       if (smsParcer.isMatch()) {
         loadResult = myDBAdapter.insertTransaction(smsParcer.getTransactionData());
       }
     } while ((inboxSMSCursor.moveToNext()) && (loadResult));
     inboxSMSCursor.close();
   }
   return loadResult;
 }
 @Override
 public void onReceive(Context context, Intent intent) {
   // Log.v(TAG, "Receiving: " + intent.getAction());
   if (intent.getAction().equals(OppProbe.getStatusAction(probeName))) {
     OppProbe.Status status = new OppProbe.Status(intent.getExtras());
     if (probeName.equals(status.getName())) {
       Log.i(TAG, "Is a status action for " + probeName);
       long nonce = intent.getLongExtra(OppProbe.ReservedParamaters.NONCE.name, 0L);
       Log.i(TAG, "Nonce is " + nonce + "'");
       if (!sent && nonce != 0L) {
         sent = true;
         expirationTimer.cancel();
         try {
           context.unregisterReceiver(DataResponder.this);
         } catch (IllegalArgumentException e) {
           // already removed;
         }
         final Intent i = new Intent(OppProbe.getGetAction(probeName));
         Log.i(TAG, "Sending intent '" + i.getAction() + "'");
         i.setPackage(context.getPackageName()); // Send only to this app for right now
         i.putExtra(OppProbe.ReservedParamaters.PACKAGE.name, context.getPackageName());
         if (requestId != null && !"".equals(requestId)) {
           i.putExtra(OppProbe.ReservedParamaters.REQUEST_ID.name, requestId);
         }
         i.putExtra(OppProbe.ReservedParamaters.REQUESTS.name, requests);
         i.putExtra(OppProbe.ReservedParamaters.NONCE.name, nonce);
         context.sendBroadcast(i);
       }
     }
   }
 }