public void widget4_4Back(RemoteViews views, AppWidgetManager manager) {
    if (viewMode == 0) {
      views.setViewVisibility(R.id.tvYear, View.VISIBLE);
      views.setViewVisibility(R.id.btWeek, View.GONE);
      views.setViewVisibility(R.id.btMonth, View.VISIBLE); // Visible
      Dates.NOW.setWeekData(--wIndex4_4);
      views.setTextViewText(R.id.tvYear, Dates.NOW.year + getString(R.string.year));
      views.setTextViewText(R.id.tvDate, setMonthWeek());
      Common.fetchWeekData();
      WeekCaptureView iv = new WeekCaptureView(this);
      iv.layout(0, 0, deviceWidth, deviceHeight * 7 / 10);
      iv.setDrawingCacheEnabled(true);
      Bitmap bitmap = iv.getDrawingCache();
      views.setImageViewBitmap(R.id.ivWeek, bitmap);
      widget4_4Setting(views, manager, bitmap);

    } else {
      views.setViewVisibility(R.id.tvYear, View.GONE);
      views.setViewVisibility(R.id.btWeek, View.VISIBLE); // Visible
      views.setViewVisibility(R.id.btMonth, View.GONE);
      Dates.NOW.setMonthData(--mIndex4_4);
      views.setTextViewText(R.id.tvDate, setYearMonth());
      widget4_4Setting(views, manager, null);
    }
  }
  @Override
  public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { //
    Cursor c =
        context.getContentResolver().query(StatusProvider.CONTENT_URI, null, null, null, null); //
    try {
      if (c.moveToFirst()) { //
        CharSequence user = c.getString(c.getColumnIndex(StatusData.C_USER)); //
        CharSequence createdAt =
            DateUtils.getRelativeTimeSpanString(
                context, c.getLong(c.getColumnIndex(StatusData.C_CREATED_AT)));
        CharSequence message = c.getString(c.getColumnIndex(StatusData.C_TEXT));

        // Loop through all instances of this widget
        for (int appWidgetId : appWidgetIds) { //
          Log.d(TAG, "Updating widget " + appWidgetId);
          RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.yamba_widget); //
          views.setTextViewText(R.id.textUser, user); //
          views.setTextViewText(R.id.textCreatedAt, createdAt);
          views.setTextViewText(R.id.textText, message);
          views.setOnClickPendingIntent(
              android.R.drawable.btn_default,
              PendingIntent.getActivity(
                  context, 0, new Intent(context, TimelineActivity.class), 0));
          appWidgetManager.updateAppWidget(appWidgetId, views); //
        }
      } else {
        Log.d(TAG, "No data to update");
      }
    } finally {
      c.close(); //
    }
    Log.d(TAG, "onUpdated");
  }
 public void fetchMonthData(RemoteViews views) {
   enrollCntHash.clear();
   for (WidgetID wID : WidgetIDRepo.getAllWidgetID(this)) {
     views.removeAllViews(wID.getTvID());
     WidgetIDRepo.deleteWithId(this, wID.getId());
   }
   int year = Dates.NOW.year;
   int month = Dates.NOW.month;
   long month_startMillies = Dates.NOW.getDateMillis(year, month, 1, 8, 0);
   long month_endMillies = Dates.NOW.getDateMillis(year, month, Dates.NOW.dayNumOfMonth, 23, 0);
   for (MyTime mt : MyTimeRepo.getMonthTimes(this, month_startMillies, month_endMillies)) {
     try {
       int dayCnt = mt.getDayofmonth() + Dates.NOW.dayOfWeek;
       int lID = getResources().getIdentifier("l" + dayCnt, "id", "com.daemin.timetable");
       if (enrollCntHash.containsKey(lID)) {
         int cnt = enrollCntHash.get(lID);
         if (cnt < 4) {
           enrollCntHash.put(lID, ++cnt);
           RemoteViews tv = new RemoteViews(getPackageName(), R.layout.widget_item);
           tv.setTextViewText(R.id.widget_item, mt.getName());
           views.addView(lID, tv);
           WidgetIDRepo.insertOrUpdate(this, new WidgetID(lID));
         }
       } else {
         enrollCntHash.put(lID, 0);
         RemoteViews tv = new RemoteViews(getPackageName(), R.layout.widget_item);
         tv.setTextViewText(R.id.widget_item, mt.getName());
         views.addView(lID, tv);
         WidgetIDRepo.insertOrUpdate(this, new WidgetID(lID));
       }
     } catch (NullPointerException e) {
       continue;
     }
   }
 }
  @Override
  public RemoteViews getViewAt(int position) {
    RemoteViews row;
    Match match = data.get(position);
    if (match.getTitle() != null) {
      row = new RemoteViews(context.getPackageName(), R.layout.widget_scores_section);
      row.setTextViewText(R.id.title, match.getTitle());
    } else {
      row = new RemoteViews(context.getPackageName(), R.layout.widget_scores_list_item);

      row.setTextViewText(R.id.home_name, match.getHome());
      row.setTextViewText(R.id.away_name, match.getAway());

      row.setImageViewResource(R.id.home_crest, match.getHomeCrest());

      row.setImageViewResource(R.id.away_crest, match.getAwayCrest());

      row.setTextViewText(R.id.data_textview, match.getMacthTime());
      row.setTextViewText(R.id.score_textview, match.getScore());
    }
    Intent fillInIntent = new Intent();
    fillInIntent.putExtra("ROW_NUMBER", position);
    row.setOnClickFillInIntent(R.id.row, fillInIntent);

    ;
    return row;
  }
  @Override
  public RemoteViews getViewAt(int position) {
    if (position == AdapterView.INVALID_POSITION
        || mCursor == null
        || !mCursor.moveToPosition(position)) {
      return null;
    }
    RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(), R.layout.widget_list);

    String homeTeamName = mCursor.getString(Utilities.DATABASE_HOME_COL);
    String awayTeamName = mCursor.getString(Utilities.DATABASE_AWAY_COL);

    remoteViews.setTextViewText(R.id.home_name, homeTeamName);
    remoteViews.setTextViewText(R.id.away_name, awayTeamName);

    String score =
        mUtilities.getScores(
            mCursor.getInt(Utilities.DATABASE_HOME_GOALS_COL),
            mCursor.getInt(Utilities.DATABASE_AWAY_GOALS_COL));
    remoteViews.setTextViewText(R.id.score_textview, score);

    remoteViews.setTextViewText(R.id.data_textview, mCursor.getString(Utilities.DATABASE_TIME_COL));

    remoteViews.setImageViewResource(
        R.id.home_crest, mUtilities.getTeamCrestByTeamName(homeTeamName));
    remoteViews.setImageViewResource(
        R.id.away_crest, mUtilities.getTeamCrestByTeamName(awayTeamName));

    return remoteViews;
  }
    @Override
    public RemoteViews getViewAt(int position) {
      RemoteViews row = new RemoteViews(context.getPackageName(), R.layout.widget_list_item);
      cursor.moveToPosition(position);
      Log.d(TAG, "view at " + position);
      row.setTextViewText(
          R.id.score_textview,
          Utilies.getScores(
              cursor.getInt(scoresAdapter.COL_HOME_GOALS),
              cursor.getInt(scoresAdapter.COL_AWAY_GOALS)));

      row.setTextViewText(R.id.home_name, cursor.getString(scoresAdapter.COL_HOME));
      row.setTextViewText(R.id.away_name, cursor.getString(scoresAdapter.COL_AWAY));

      row.setTextViewText(R.id.data_textview, cursor.getString(scoresAdapter.COL_MATCHTIME));

      Intent fillInIntent = new Intent();
      row.setOnClickFillInIntent(R.id.list_item, fillInIntent);

      row.setImageViewResource(
          R.id.home_crest,
          Utilies.getTeamCrestByTeamName(cursor.getString(scoresAdapter.COL_HOME)));
      row.setImageViewResource(
          R.id.away_crest,
          Utilies.getTeamCrestByTeamName(cursor.getString(scoresAdapter.COL_AWAY)));
      return row;
    }
  /** Creates a notification of the specified type for a contact. */
  public void createNotification(NotificationType type, int notificationId, Contact contact) {
    Notification notification = new Notification(-1, null, System.currentTimeMillis());

    notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;

    RemoteViews contentView = new RemoteViews(_context.getPackageName(), R.layout.notification);

    // set the photo
    contentView.setImageViewBitmap(
        R.id.notification_contact_photo, ContactsHelper.getPhoto(_context, contact));

    // set the verb, i.e. "call" or "text"
    contentView.setTextViewText(
        R.id.notification_notification_type, _context.getString(type.getVerbStringId()));

    // set the name and type
    contentView.setTextViewText(R.id.notification_contact_name, contact.getDisplayName());
    contentView.setTextViewText(R.id.notification_contact_type, contact.getType());

    // set the number
    contentView.setTextViewText(R.id.notification_contact_number, contact.getNumber());

    notification.contentView = contentView;

    // create the intent that will fire when the contact is selected
    Intent intent = new Intent(type.getAction(), Uri.parse(type.getScheme() + contact.getNumber()));
    PendingIntent contentIntent = PendingIntent.getActivity(_context, 0, intent, 0);
    notification.contentIntent = contentIntent;

    _manager.notify(notificationId, notification);
  }
  @Override
  public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    Log.v(TAG, "onStart");

    // RemoteViews is used with widget. This can be displayed in another process.
    RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.main);
    // Prepare Intent which is sent when button is clicked
    Intent buttonIntent = new Intent();

    // If this Intent is issued when button is clicked
    if (BUTTON_CLICK_ACTION.equals(intent.getAction())) {
      buttonIntent.setAction(BUTTON_CLICK_ACTION2);
      remoteViews.setTextViewText(R.id.text, "Push Button");
    } else {
      buttonIntent.setAction(BUTTON_CLICK_ACTION);
      remoteViews.setTextViewText(R.id.text, "WidgetSample");
    }

    // Handle this Intent as PendingIntent
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, buttonIntent, 0);
    remoteViews.setOnClickPendingIntent(R.id.button, pendingIntent);
    Log.v(TAG, "set PendingIntent here");
    Toast.makeText(this, "set PendingIntent", Toast.LENGTH_SHORT).show();

    // Update AppWidget display
    ComponentName thisWidget = new ComponentName(this, WidgetSample.class);
    AppWidgetManager manager = AppWidgetManager.getInstance(this);
    manager.updateAppWidget(thisWidget, remoteViews);
  }
  private void handleIsOpen(final Context mContext, final OpeningStatus openingStatus) {
    final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
    final int[] appWidgetIds =
        appWidgetManager.getAppWidgetIds(new ComponentName(mContext, AnalogWidget.class));
    final RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.analog_widget);
    views.setTextViewText(R.id.appwidget_text, mContext.getText(R.string.refreshing_analog));
    views.setTextColor(
        R.id.appwidget_text, ContextCompat.getColor(mContext, android.R.color.primary_text_dark));
    // Instruct the widget manager to update the widget
    for (int appWidgetId : appWidgetIds) {
      appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    CharSequence widgetText;
    if (openingStatus.open) {
      widgetText = mContext.getString(R.string.widget_open_analog);
      views.setTextColor(R.id.appwidget_text, ContextCompat.getColor(mContext, R.color.openColor));
    } else {
      widgetText = mContext.getString(R.string.widget_closed_analog);
      views.setTextColor(
          R.id.appwidget_text, ContextCompat.getColor(mContext, R.color.closedColor));
    }

    views.setTextViewText(R.id.appwidget_text, widgetText);
    views.setOnClickPendingIntent(R.id.appwidget_text, getPendingSelfIntent(mContext));
    // Instruct the widget manager to update the widget
    for (int appWidgetId : appWidgetIds) {
      appWidgetManager.updateAppWidget(appWidgetId, views);
    }
  }
  @Override
  public RemoteViews getViewAt(int position) {
    RemoteViews rView = new RemoteViews(mContext.getPackageName(), R.layout.widget_view_lesson);
    Lesson lesson = mLessons[position];
    rView.setTextViewText(R.id.widget_lesson_name, lesson.fields.get("subject"));
    rView.setTextViewText(R.id.widget_lesson_time, lesson.fields.get("timePeriod"));
    rView.setTextViewText(R.id.widget_lesson_teacher, lesson.fields.get("teacher"));

    if (!lesson.fields.get("auditorium").equals("")) {
      rView.setTextViewText(R.id.widget_lesson_auditorium, lesson.fields.get("auditorium"));
    }

    String lessonType = lesson.fields.get("subjectType");

    if (lessonType.equals("лр")) {
      rView.setInt(
          R.id.widget_lesson_type_color, "setBackgroundColor", (Color.parseColor("#FF4444")));
    } else if (lessonType.equals("пз")) {
      rView.setInt(
          R.id.widget_lesson_type_color, "setBackgroundColor", (Color.parseColor("#FFBB33")));
    } else if (lessonType.equals("лк")) {
      rView.setInt(
          R.id.widget_lesson_type_color, "setBackgroundColor", (Color.parseColor("#99CC00")));
    } else {
      rView.setInt(R.id.widget_lesson_type_color, "setBackgroundColor", (Color.WHITE));
    }

    rView.setInt(R.id.widget_separateline, "setBackgroundColor", Color.WHITE);

    return rView;
  }
  public void onReceive(Context context, Intent intent) {

    Log.d("TimeSetReceiver", "onReceive");

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);

    ComponentName thisWidget; // 组件名
    AppWidgetManager manager; // AppWidget管理器

    thisWidget = new ComponentName(context, CalendarWidget.class);
    manager = AppWidgetManager.getInstance(context);

    Calendar calendar = Calendar.getInstance();

    int day = calendar.get(Calendar.DAY_OF_MONTH);
    int month = calendar.get(Calendar.MONTH) + 1;
    int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
    Lunar lunar = new Lunar(calendar);

    Log.d("TimeSetReceiver", month + "," + day + lunar.toString());

    String month_week = month + "月" + "          周" + weekArray[week];
    views.setTextViewText(R.id.month_week, month_week);
    views.setTextViewText(R.id.nongli, lunar.toString());
    views.setTextViewText(R.id.day, Html.fromHtml("<B>" + String.valueOf(day) + "</B>"));

    manager.updateAppWidget(thisWidget, views);

    Log.d("TimeSetReceiver", "updateAppWidget finish");
  }
  @Override
  public void onHandleIntent(Intent intent) {
    ComponentName me = new ComponentName(this, AppWidget.class);
    RemoteViews updateViews = new RemoteViews("apt.tutorial", R.layout.widget);
    RestaurantHelper helper = new RestaurantHelper(this);
    AppWidgetManager mgr = AppWidgetManager.getInstance(this);

    try {
      Cursor c = helper.getReadableDatabase().rawQuery(SQL_QUERY_COUNT, null);
      c.moveToFirst();
      int count = c.getInt(0);
      c.close();
      if (count > 0) {
        int offset = (int) (count * Math.random());
        String args[] = {String.valueOf(offset)};
        c = helper.getReadableDatabase().rawQuery(SQL_QUERY_SELECT, args);
        c.moveToFirst();
        updateViews.setTextViewText(R.id.name, c.getString(1));
        Intent i = new Intent(this, DetailForm.class);
        i.putExtra(LunchList.ID_EXTRA, c.getString(0));
        PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        updateViews.setOnClickPendingIntent(R.id.name, pi);
        c.close();
      } else {
        updateViews.setTextViewText(R.id.title, this.getString(R.string.empty));
      }
    } finally {
      helper.close();
    }

    Intent i = new Intent(this, WidgetService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    updateViews.setOnClickPendingIntent(R.id.next, pi);
    mgr.updateAppWidget(me, updateViews);
  }
  public static void updateWidgets(
      final Context context,
      @Nonnull final AppWidgetManager appWidgetManager,
      @Nonnull final int[] appWidgetIds,
      @Nonnull final BigInteger balance) {
    final Configuration config =
        new Configuration(PreferenceManager.getDefaultSharedPreferences(context));
    final Spannable balanceStr =
        new SpannableString(
            GenericUtils.formatValue(balance, config.getBtcPrecision(), config.getBtcShift()));
    WalletUtils.formatSignificant(balanceStr, WalletUtils.SMALLER_SPAN);

    for (final int appWidgetId : appWidgetIds) {
      final RemoteViews views =
          new RemoteViews(context.getPackageName(), R.layout.wallet_balance_widget_content);
      views.setTextViewText(R.id.widget_wallet_prefix, config.getBtcPrefix());
      views.setTextViewText(R.id.widget_wallet_balance, balanceStr);
      views.setOnClickPendingIntent(
          R.id.widget_button_balance,
          PendingIntent.getActivity(context, 0, new Intent(context, WalletActivity.class), 0));
      views.setOnClickPendingIntent(
          R.id.widget_button_request,
          PendingIntent.getActivity(
              context, 0, new Intent(context, RequestCoinsActivity.class), 0));
      views.setOnClickPendingIntent(
          R.id.widget_button_send,
          PendingIntent.getActivity(context, 0, new Intent(context, SendCoinsActivity.class), 0));
      views.setOnClickPendingIntent(
          R.id.widget_button_send_qr,
          PendingIntent.getActivity(context, 0, new Intent(context, SendCoinsQrActivity.class), 0));

      appWidgetManager.updateAppWidget(appWidgetId, views);
    }
  }
Example #14
0
  @Override
  public void onUpdate(Context ctxt, AppWidgetManager mgr, int[] appWidgetIds) {
    ComponentName me = new ComponentName(ctxt, AppWidget.class);
    RemoteViews updateViews = new RemoteViews("apt.tutorial", R.layout.widget);
    SQLiteDatabase db = (new RestaurantSQLiteHelper(ctxt)).getReadableDatabase();

    try {
      Cursor c = db.rawQuery("SELECT COUNT(*) FROM restaurants", null);

      c.moveToFirst();

      int count = c.getInt(0);

      c.close();

      if (count > 0) {
        int offset = (int) (count * Math.random());
        String args[] = {String.valueOf(offset)};

        c = db.rawQuery("SELECT name FROM restaurants LIMIT 1 OFFSET ?", args);
        c.moveToFirst();
        updateViews.setTextViewText(R.id.name, c.getString(0));
      } else {
        updateViews.setTextViewText(R.id.name, ctxt.getString(R.string.empty));
      }
    } finally {
      db.close();
    }

    mgr.updateAppWidget(me, updateViews);
  }
Example #15
0
  public static void sendNotif(Context context) {

    NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.av1)
            .setContentTitle("My notification")
            .setContentText("Hello World!")
            .setAutoCancel(true);

    RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification);
    // contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher);
    contentView.setTextViewText(
        R.id.resto, Controller.currentGroupSelected.getGroup().getRestaurant().getName());
    contentView.setTextViewText(R.id.group, Controller.currentGroupSelected.getGroup().getName());

    mBuilder.setContent(contentView);

    Intent resultIntent = new Intent(context, RecapActivity.class);

    PendingIntent resultPendingIntent =
        PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(resultPendingIntent);

    // Sets an ID for the notification
    int mNotificationId = 1;
    // Gets an instance of the NotificationManager service
    NotificationManager mNotifyMgr =
        (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    // Builds the notification and issues it.
    mNotifyMgr.notify(mNotificationId, mBuilder.build());
  }
Example #16
0
  @Override
  public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    super.onUpdate(context, appWidgetManager, appWidgetIds);

    for (int i = 0; i < appWidgetIds.length; i++) {
      GregorianCalendar cal = new GregorianCalendar();

      SimpleDateFormat weekFormat = new SimpleDateFormat("EEE");
      String strWeek = weekFormat.format(cal.getTime());

      SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM dd");
      String strDate = dateFormat.format(cal.getTime());

      RemoteViews remote = new RemoteViews(context.getPackageName(), R.layout.myapp_widget);
      remote.setTextViewText(R.id.tvDate, strDate);
      remote.setTextViewText(R.id.tvWeekDay, strWeek);

      Intent intent = new Intent(context, MyAppWidget.class);
      intent.setAction(ACTION_MYAPPWIDGET_DISPLAY);
      intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);

      PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
      remote.setOnClickPendingIntent(R.id.btnWidget, pIntent);

      appWidgetManager.updateAppWidget(appWidgetIds[i], remote);
    }
  }
 private void fillNotificationView(RemoteViews view, JttTime time) {
   StringResources sr = RuntimeResources.get(this).getInstance(StringResources.class);
   view.setTextViewText(R.id.image, time.hour.glyph);
   view.setTextViewText(R.id.title, sr.getHrOf(time.hour.ordinal()));
   view.setTextViewText(R.id.quarter, sr.getQuarter(time.quarter.ordinal()));
   int hour_ticks = time.quarter.ordinal() * JttTime.TICKS_PER_QUARTER + time.ticks;
   view.setProgressBar(R.id.fraction, JttTime.TICKS_PER_HOUR, hour_ticks, false);
 }
  /** 带按钮的通知栏 */
  public void showButtonNotify() {
    NotificationCompat.Builder mBuilder = new Builder(this);
    RemoteViews mRemoteViews =
        new RemoteViews(getPackageName(), R.layout.activity_notification_view_custom_button);
    mRemoteViews.setImageViewResource(R.id.custom_song_icon, R.drawable.notification_sing_icon);
    // API3.0 以上的时候显示按钮,否则消失
    mRemoteViews.setTextViewText(R.id.tv_custom_song_singer, "周杰伦");
    mRemoteViews.setTextViewText(R.id.tv_custom_song_name, "七里香");
    // 如果版本号低于(3。0),那么不显示按钮
    if (BaseTools.getSystemVersion() <= 9) {
      mRemoteViews.setViewVisibility(R.id.ll_custom_button, View.GONE);
    } else {
      mRemoteViews.setViewVisibility(R.id.ll_custom_button, View.VISIBLE);
      //
      if (isPlay) {
        mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.drawable.notification_btn_pause);
      } else {
        mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.drawable.notification_btn_play);
      }
    }

    // 点击的事件处理
    Intent buttonIntent = new Intent(ACTION_BUTTON);
    /* 上一首按钮 */
    buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PREV_ID);
    // 这里加了广播,所及INTENT的必须用getBroadcast方法
    PendingIntent intent_prev =
        PendingIntent.getBroadcast(this, 1, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_prev, intent_prev);
    /* 播放/暂停 按钮 */
    buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PALY_ID);
    PendingIntent intent_paly =
        PendingIntent.getBroadcast(this, 2, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_play, intent_paly);
    /* 下一首 按钮 */
    buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_NEXT_ID);
    PendingIntent intent_next =
        PendingIntent.getBroadcast(this, 3, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_next, intent_next);

    mBuilder
        .setContent(mRemoteViews)
        .setContentIntent(getDefalutIntent(Notification.FLAG_ONGOING_EVENT))
        .setWhen(System.currentTimeMillis())
        // 通知产生的时间,会在通知信息里显示
        .setTicker("正在播放")
        .setPriority(Notification.PRIORITY_DEFAULT)
        // 设置该通知优先级
        .setOngoing(true)
        .setSmallIcon(R.drawable.notification_sing_icon);
    Notification notify = mBuilder.build();
    notify.flags = Notification.FLAG_ONGOING_EVENT;
    // 会报错,还在找解决思路
    // notify.contentView = mRemoteViews;
    // notify.contentIntent = PendingIntent.getActivity(this, 0, new
    // Intent(), 0);
    mNotificationManager.notify(200, notify);
  }
  @Override
  protected void onHandleIntent(Intent intent) {

    // Retrieve all of the Today widget ids: these are the widgets we need to update
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
    int[] appWidgetIds =
        appWidgetManager.getAppWidgetIds(
            new ComponentName(this, FootbalScoresWidgetProvider.class));

    for (int appWidgetId : appWidgetIds) {
      RemoteViews views = new RemoteViews(this.getPackageName(), R.layout.widget_layout);

      Intent mainIntent = new Intent(this, MainActivity.class);
      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, mainIntent, 0);
      views.setOnClickPendingIntent(R.id.widget, pendingIntent);

      Uri u = DatabaseContract.scores_table.buildScoreWithDate();
      Date today = new Date();
      SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
      String sToday = fmt.format(today);

      // sToday = "2015-11-08";
      // fmt = new SimpleDateFormat("dd");
      // sToday = fmt.format(today);
      // int nToday = Integer.parseInt(sToday) - 7;
      // sToday = "2015-11-07";

      Cursor c = this.getContentResolver().query(u, INFO, null, new String[] {sToday}, null);
      if (c.moveToFirst()) {
        hometeam = c.getString(c.getColumnIndex(DatabaseContract.scores_table.HOME_COL));
        awayTeam = c.getString(c.getColumnIndex(DatabaseContract.scores_table.AWAY_COL));
        homeGoals = c.getString(c.getColumnIndex(DatabaseContract.scores_table.HOME_GOALS_COL));
        awayGoals = c.getString(c.getColumnIndex(DatabaseContract.scores_table.AWAY_GOALS_COL));
        matchTime = c.getString(c.getColumnIndex(DatabaseContract.scores_table.TIME_COL));
        fmt = new SimpleDateFormat("EEE, MMM d");
        gameDetail = fmt.format(today);
        if (!homeGoals.equals("-1")) {
          gameDetail += this.getResources().getString(R.string.full_time);
          views.setTextViewText(R.id.home_side_score, homeGoals);
          views.setTextViewText(R.id.away_side_score, awayGoals);
        } else {
          gameDetail += " " + this.getResources().getString(R.string.at) + " " + matchTime;
        }

        views.setTextViewText(R.id.home_side, hometeam);
        views.setTextViewText(R.id.away_side, awayTeam);
        views.setTextViewText(R.id.match_time, gameDetail);

      } else {
        views.setTextViewText(R.id.home_side, this.getResources().getString(R.string.no_games));
      }
      c.close();

      appWidgetManager.updateAppWidget(appWidgetId, views);
    }
  }
  @Override
  protected void onHandleIntent(Intent intent) {
    Intent service_start = new Intent(getApplicationContext(), myFetchService.class);
    getApplicationContext().startService(service_start);

    Cursor scores =
        getApplicationContext()
            .getContentResolver()
            .query(DatabaseContract.scores_table.buildScores(), null, null, null, null);

    scores.moveToFirst();
    String lastestHome = scores.getString(scoresAdapter.COL_HOME);
    String lastestAway = scores.getString(scoresAdapter.COL_AWAY);
    Integer lastestScoreHome = scores.getInt(scoresAdapter.COL_HOME_GOALS);
    Integer lastestScoreAway = scores.getInt(scoresAdapter.COL_AWAY_GOALS);
    String lastestMatchTime = scores.getString(scoresAdapter.COL_MATCHTIME);

    // Retrieve all of the Today widget ids: these are the widgets we need to update
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
    int[] appWidgetIds =
        appWidgetManager.getAppWidgetIds(new ComponentName(this, ScoreWidgetProvider.class));

    for (int appWidgetId : appWidgetIds) {
      int layoutId = R.layout.widget_score_small;
      RemoteViews views = new RemoteViews(getPackageName(), layoutId);

      // views.widget_home_name.setText(cursor.getString(COL_HOME));
      views.setTextViewText(R.id.widget_home_name, lastestHome);
      views.setTextViewText(R.id.widget_away_name, lastestAway);
      views.setTextViewText(R.id.widget_date_textview, lastestMatchTime);
      views.setTextViewText(
          R.id.widget_score_textview, Utilies.getScores(lastestScoreHome, lastestScoreAway));
      views.setImageViewResource(
          R.id.widget_home_crest, Utilies.getTeamCrestByTeamName(lastestHome));
      views.setImageViewResource(
          R.id.widget_away_crest, Utilies.getTeamCrestByTeamName(lastestAway));

      // Add the data to the RemoteViews
      // Content Descriptions for RemoteViews were only added in ICS MR1
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
        views.setContentDescription(
            R.id.widget_score_textview,
            "Score " + Utilies.getScores(lastestScoreHome, lastestScoreAway));
        views.setContentDescription(R.id.widget_date_textview, "Time " + lastestMatchTime);
      }

      // Create an Intent to launch MainActivity
      Intent launchIntent = new Intent(this, MainActivity.class);
      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, launchIntent, 0);
      views.setOnClickPendingIntent(R.id.widget, pendingIntent);

      // Tell the AppWidgetManager to perform an update on the current app widget
      appWidgetManager.updateAppWidget(appWidgetId, views);
    }
  }
Example #21
0
  private void updateTimeViews(RemoteViews views) {
    String lunarDate = DateUtil.getLunarDate();
    String nowWeek = DateUtil.getNowWeek();
    String dateAsYYYY_MM_DD = DateUtil.getDateAsYYYY_MM_DD(System.currentTimeMillis());

    LogUtil.log("test", "dateAsYYYY_MM_DD=" + dateAsYYYY_MM_DD); // ///////////////////

    views.setTextViewText(R.id.tv_date, dateAsYYYY_MM_DD);
    views.setTextViewText(R.id.tv_week, nowWeek);
    views.setTextViewText(R.id.tv_lunar_date, lunarDate);
  }
Example #22
0
 /**
  * 自定义通知
  *
  * @param builder
  * @return
  */
 private NotificationCompat.Builder selfDefindNotification(NotificationCompat.Builder builder) {
   // 得到自定义通知布局文件对象
   RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notificatoindemo03);
   // 给布局文件对象属性设置值
   remoteViews.setImageViewResource(R.id.myselfnotificationIV, R.drawable.icon);
   remoteViews.setTextViewText(R.id.myselfnoticationTV1, "消息");
   remoteViews.setTextViewText(R.id.myselfnoticationTV2, "要放假了");
   // 把布局对象放入到通知的内容中
   builder.setContent(remoteViews);
   return builder;
 }
  @Override
  public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    Log.d("Updating Room Widgets...");
    // Perform this loop procedure for each App Widget that belongs to this provider
    for (int i = 0; i < appWidgetIds.length; i++) {
      int appWidgetId = appWidgetIds[i];
      RemoteViews remoteViews =
          new RemoteViews(
              context.getResources().getString(eu.power_switch.shared.R.string.PACKAGE_NAME),
              R.layout.widget_room);

      try {
        RoomWidget roomWidget = DatabaseHandler.getRoomWidget(appWidgetId);
        Room room = DatabaseHandler.getRoom(roomWidget.getRoomId());
        if (room != null) {
          Apartment apartment = DatabaseHandler.getApartment(room.getApartmentId());

          // update UI
          remoteViews.setTextViewText(
              R.id.textView_room_widget_name, apartment.getName() + ": " + room.getName());

          // set button action
          remoteViews.setOnClickPendingIntent(
              R.id.button_on,
              WidgetIntentReceiver.buildRoomWidgetButtonPendingIntent(
                  context,
                  apartment,
                  room,
                  context.getString(R.string.on),
                  ConfigureRoomWidgetActivity.ROOM_INTENT_ID_OFFSET + appWidgetId));
          remoteViews.setOnClickPendingIntent(
              R.id.button_off,
              WidgetIntentReceiver.buildRoomWidgetButtonPendingIntent(
                  context,
                  apartment,
                  room,
                  context.getString(R.string.off),
                  ConfigureRoomWidgetActivity.ROOM_INTENT_ID_OFFSET + appWidgetId + 1));
          remoteViews.setViewVisibility(R.id.linearlayout_room_widget, View.VISIBLE);
        } else {
          remoteViews.setTextViewText(
              R.id.textView_room_widget_name, context.getString(R.string.room_not_found));
          remoteViews.setViewVisibility(R.id.linearlayout_room_widget, View.GONE);
        }
      } catch (Exception e) {
        Log.e(e);
        remoteViews.setTextViewText(
            R.id.textView_room_widget_name, context.getString(R.string.unknown_error));
        remoteViews.setViewVisibility(R.id.linearlayout_room_widget, View.GONE);
      }
      appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
    }
    super.onUpdate(context, appWidgetManager, appWidgetIds);
  }
Example #24
0
  private static void updateWidget(
      Context context,
      AppWidgetManager appWidgetManager,
      WidgetModel widgetModel,
      ArrayList<ArrivalModel> arrivals) {
    // Set the base layout to use
    int layoutResId =
        widgetModel.getSize() == WidgetUtils.SIZE_1X1
            ? R.layout.widget_layout_1x1
            : R.layout.widget_layout_2x1;
    RemoteViews updatedViews = new RemoteViews(context.getPackageName(), layoutResId);

    // Set widget background colors
    updatedViews.setInt(
        R.id.tv_widget_title,
        SET_BACKGROUND_COLOR,
        WidgetUtils.getPrimaryColorInt(context, widgetModel.getBgColor()));
    updatedViews.setInt(
        R.id.layout_widget_arrivals,
        SET_BACKGROUND_COLOR,
        WidgetUtils.getSecondaryColorInt(context, widgetModel.getBgColor()));

    // If the user set the widget color to white, we have to change the colors of
    // some UI elements so that they show properly.
    if (widgetModel.getBgColor() == WidgetUtils.BG_WHITE) {
      updatedViews.setTextColor(R.id.tv_widget_title, Color.DKGRAY);
      updatedViews.setTextColor(R.id.tv_widget_arrival_1, Color.DKGRAY);
      updatedViews.setTextColor(R.id.tv_widget_arrival_2, Color.DKGRAY);
      updatedViews.setInt(R.id.iv_widget_divider_1, SET_BACKGROUND_COLOR, Color.DKGRAY);
      if (getNumArrivalsToShow(widgetModel) == 3) {
        // There is a third arrival text to update
        updatedViews.setTextColor(R.id.tv_widget_arrival_3, Color.DKGRAY);
        updatedViews.setInt(R.id.iv_widget_divider_2, SET_BACKGROUND_COLOR, Color.DKGRAY);
      }
    }

    // Set the widget title
    updatedViews.setTextViewText(R.id.tv_widget_title, widgetModel.getTitle());

    // Update the shown arrival times
    for (int i = 0; i < Math.min(arrivals.size(), getNumArrivalsToShow(widgetModel)); i++) {
      updatedViews.setTextViewText(
          ARRIVAL_TEXTVIEW_RES_ID[i], String.valueOf(arrivals.get(i).getMinsUntilArrival()));
    }

    // Set the widget to refresh on click
    updatedViews.setOnClickPendingIntent(
        R.id.tv_widget_title, createRefreshIntent(context, widgetModel.getWidgetId()));
    updatedViews.setOnClickPendingIntent(
        R.id.layout_widget_arrivals, createRefreshIntent(context, widgetModel.getWidgetId()));

    // Update the widget view
    appWidgetManager.updateAppWidget(widgetModel.getWidgetId(), updatedViews);
  }
 /**
  * 设置下载进度和当前的网速
  *
  * @param progress
  * @param netSpeed
  */
 private void setProgressAndNetSpeed(int progress, long netSpeed) {
   remoteViews.setTextViewText(R.id.download_notication_title, bookName + "   " + progress + "%");
   remoteViews.setProgressBar(R.id.progress, 100, progress, false);
   remoteViews.setTextViewText(R.id.tv_progress, netSpeed + "kb/s");
   if (android.os.Build.VERSION.SDK_INT <= 9)
     remoteViews.setTextColor(
         R.id.download_notication_title,
         mContext.getResources().getColor(R.color.alarm_playback_color));
   notifiManger.notify(NOTIFI_ID, notification);
   lastTotalRxBytes = getTotalRxBytes();
   lastTimeStamp = System.currentTimeMillis();
 }
  protected void updateCoordinates(double latitude, double longitude) {

    Geocoder coder = new Geocoder(this);
    List<Address> addresses = null;
    StringBuilder address = new StringBuilder();
    String latlng = "";

    Log.i(APP_TAG, "update location");

    try {
      addresses = coder.getFromLocation(latitude, longitude, 2);

      if (null != addresses && addresses.size() > 0) {
        int addressCount = addresses.get(0).getMaxAddressLineIndex();

        if (-1 != addressCount) {
          for (int index = 0; index <= addressCount; ++index) {
            address.append(addresses.get(0).getAddressLine(index));

            if (index < addressCount) address.append(", ");
          }
        } else {
          address.append(addresses.get(0).getFeatureName());
          address.append(", ");
          address.append(addresses.get(0).getSubAdminArea());
          address.append(", ");
          address.append(addresses.get(0).getAdminArea());
        }
      }

      Log.i(APP_TAG, addresses.get(0).toString());
    } catch (Exception e) {
      e.printStackTrace();
    }

    coder = null;
    addresses = null;

    latlng = "lat " + latitude + ", lng " + longitude;

    RemoteViews views = new RemoteViews(getPackageName(), R.layout.main_widget_ui);

    views.setTextViewText(
        R.id.txtMyAddress, address.toString().equals("") ? "không có sẵn" : address.toString());
    views.setTextViewText(R.id.txtLatLng, latlng);

    lastAddress = address.toString() + "\n" + latlng;

    ComponentName thisWidget = new ComponentName(this, SimpleWidget.class);
    AppWidgetManager manager = AppWidgetManager.getInstance(this);
    manager.updateAppWidget(thisWidget, views);
  }
 /** Sets the track name, artist name, and album art in the normal layout */
 private void initCollapsedLayout(
     final String trackName, final String artistName, final Bitmap albumArt) {
   // Track name (line one)
   mNotificationTemplate.setTextViewText(
       R.id.notification_base_line_one, trackName != null ? trackName : "---");
   // Artist name (line two)
   mNotificationTemplate.setTextViewText(
       R.id.notification_base_line_two, artistName != null ? artistName : "---");
   // Album art
   if (albumArt != null) {
     mNotificationTemplate.setImageViewBitmap(R.id.notification_base_image, albumArt);
   }
 }
  private void updateWidgetPictureAndButtonListener(Context context) {
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

    // updating view
    remoteViews.setTextViewText(R.id.title, getTitle());
    remoteViews.setTextViewText(R.id.desc, getDesc(context));

    // re-registering for click listener
    remoteViews.setOnClickPendingIntent(
        R.id.sync_button, MyWidgetProvider.buildButtonPendingIntent(context));

    MyWidgetProvider.pushWidgetUpdate(context.getApplicationContext(), remoteViews);
  }
  /*
   * Build the RemoteViews for the notification. We also need to add the appropriate "back stack"
   * so when user goes into the CastPlayerActivity, she can have a meaningful "back" experience.
   */
  private RemoteViews build(MediaInfo info, Bitmap bitmap, boolean isPlaying)
      throws CastException, TransientNetworkDisconnectionException, NoConnectionException {
    Bundle mediaWrapper = Utils.fromMediaInfo(mCastManager.getRemoteMediaInformation());
    Intent contentIntent = new Intent(this, mTargetActivity);

    contentIntent.putExtra("media", mediaWrapper);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    stackBuilder.addParentStack(mTargetActivity);

    stackBuilder.addNextIntent(contentIntent);
    if (stackBuilder.getIntentCount() > 1) {
      stackBuilder.editIntentAt(1).putExtra("media", mediaWrapper);
    }

    // Gets a PendingIntent containing the entire back stack
    PendingIntent resultPendingIntent =
        stackBuilder.getPendingIntent(NOTIFICATION_ID, PendingIntent.FLAG_UPDATE_CURRENT);

    MediaMetadata mm = info.getMetadata();

    RemoteViews rv = new RemoteViews(getPackageName(), R.layout.custom_notification);
    if (mIsIcsOrAbove) {
      addPendingIntents(rv, isPlaying, info);
    }
    if (null != bitmap) {
      rv.setImageViewBitmap(R.id.iconView, bitmap);
    } else {
      bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dummy_album_art);
      rv.setImageViewBitmap(R.id.iconView, bitmap);
    }
    rv.setTextViewText(R.id.titleView, mm.getString(MediaMetadata.KEY_TITLE));
    String castingTo =
        getResources().getString(R.string.casting_to_device, mCastManager.getDeviceName());
    rv.setTextViewText(R.id.subTitleView, castingTo);
    mNotification =
        new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_action_notification)
            .setContentIntent(resultPendingIntent)
            .setContent(rv)
            .setAutoCancel(false)
            .setOngoing(true)
            .build();

    // to get around a bug in GB version, we add the following line
    // see https://code.google.com/p/android/issues/detail?id=30495
    mNotification.contentView = rv;

    return rv;
  }
Example #30
0
  /**
   * You can do heaving lifting in here, synchronously. For example, if you need to process an
   * image, fetch something from the network, etc., it is ok to do it here, synchronously. A loading
   * view will show up in lieu of the actual contents in the interim.
   */
  public RemoteViews getViewAt(int position) {
    final RemoteViews rv =
        new RemoteViews(mContext.getPackageName(), R.layout.stackview_widget_item);

    if (mPhotos.size() == 0) {
      updatePhotos();
    }

    /* Fetch the photo synchronously */
    final Photo photo = mPhotos.get(position);
    Bitmap bitmap = null;
    try {
      bitmap = Picasso.with(mContext).load(photo.getSmallUrl()).get();
    } catch (IOException e) {
      e.printStackTrace();
    }
    rv.setImageViewBitmap(R.id.image_item, bitmap);

    /* Set the overlay views and owner info */
    rv.setViewVisibility(R.id.imageOverlay, View.VISIBLE);
    String viewsText =
        String.format(
            "%s: %s", mContext.getString(R.string.views), String.valueOf(photo.getViews()));
    rv.setTextViewText(R.id.viewsText, viewsText);
    if (photo.getOwner() != null) {
      rv.setTextViewText(R.id.ownerText, photo.getOwner().getUsername());
    }

    /* Show ribbon in corner if photo is new */
    // TODO: create list of new photos to enable this
    // rv.setVisibility(R.id.imageNewRibbon, View.INVISIBLE);
    // if (mNewPhotos != null) {
    // for (Photo p : mNewPhotos) {
    // if (p.getId().equals(photo.getId())) {
    // holder.imageNewRibbon.setVisibility(View.VISIBLE);
    // }
    // }
    // }

    /* Next, we set a fill-intent which will be used to fill-in the pending
     * intent template which is set on the collection view in
     * StackWidgetProvider. */
    Bundle extras = new Bundle();
    extras.putInt(StackWidgetProvider.VIEW_INDEX, position);
    extras.putString(PhotoViewerActivity.KEY_PHOTO_LIST_FILE, PhotoViewerActivity.PHOTO_LIST_FILE);
    Intent fillInIntent = new Intent();
    fillInIntent.putExtras(extras);
    rv.setOnClickFillInIntent(R.id.image_layout, fillInIntent);

    return rv;
  }