public void updateViews(Context context, RemoteViews views) { views.setViewVisibility(R.id.tv_init_pomt, View.INVISIBLE); views.setViewVisibility(R.id.rl_root_content, View.VISIBLE); updateTimeViews(views); updateWeatherViews(context, views); sendClickEvent(context, views); }
private void updateWidgets() { RemoteViews widget = new RemoteViews(getPackageName(), R.layout.ticker_widget); widget.setOnClickPendingIntent( R.id.feed_ticker_tap_area, PendingIntent.getActivity(this, 0, new Intent(this, HomeActivity.class), 0)); Cursor unread = getContentResolver() .query( FeedData.EntryColumns.CONTENT_URI, new String[] {FeedData.ALL_UNREAD_NUMBER}, null, null, null); if (unread != null) { if (unread.moveToFirst()) { int unread_count = unread.getInt(0); if (unread_count > 0) { widget.setTextViewText(R.id.feed_ticker, String.valueOf(unread_count)); widget.setViewVisibility(R.id.feed_ticker, View.VISIBLE); widget.setViewVisibility(R.id.feed_ticker_circle, View.VISIBLE); } else { widget.setViewVisibility(R.id.feed_ticker, View.INVISIBLE); widget.setViewVisibility(R.id.feed_ticker_circle, View.INVISIBLE); } } unread.close(); } AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); appWidgetManager.updateAppWidget( new ComponentName(getPackageName(), TickerWidgetProvider.class.getName()), widget); }
private void refreshText(AppWidgetManager mgr, int widgetId) { RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.appwidget); remoteViews.setViewVisibility(R.id.text, View.INVISIBLE); remoteViews.setViewVisibility(R.id.progress, View.VISIBLE); mgr.updateAppWidget(widgetId, remoteViews); }
/** 带按钮的通知栏 */ 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); }
private void setTextView(RemoteViews remoteViews, int viewId, String text) { if (text != null) { remoteViews.setViewVisibility(viewId, View.VISIBLE); remoteViews.setTextViewText(viewId, text); } else { remoteViews.setViewVisibility(viewId, View.GONE); } }
@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); }
private void updateForScreenSize(RemoteViews views) { Display display = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); if (metrics.density <= 0.75) { views.setViewVisibility(SEPARATOR_IDS[3], View.INVISIBLE); views.setViewVisibility(TEXT_IDS[4], View.INVISIBLE); } }
public void configureBackground(Context context, RemoteViews rv) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (prefs.getBoolean(CalendarPreferences.PREF_SHOW_HEADER, true)) { rv.setViewVisibility(R.id.action_bar, View.VISIBLE); } else { rv.setViewVisibility(R.id.action_bar, View.GONE); } int bgTrans = prefs.getInt( CalendarPreferences.PREF_BACKGROUND_TRANSPARENCY, PREF_BACKGROUND_TRANSPARENCY_DEFAULT); rv.setInt( R.id.widget_background, METHOD_SET_BACKGROUND_RESOURCE, transparencyToDrawableRes(bgTrans)); }
public void widget4_4Month(RemoteViews views, AppWidgetManager manager) { pref.edit().putInt("viewMode", 1).apply(); viewMode = 1; wIndex4_4 = 0; views.setViewVisibility(R.id.tvYear, View.GONE); views.setViewVisibility(R.id.btWeek, View.VISIBLE); // Visible views.setViewVisibility(R.id.ivWeek, View.GONE); views.setViewVisibility(R.id.llMonth, View.VISIBLE); Dates.NOW.setMonthData(mIndex4_4); views.setViewVisibility(R.id.btMonth, View.GONE); views.setTextViewText(R.id.tvDate, setYearMonth()); widget4_4Setting(views, manager, null); }
/** If there are actions, shows the button related views, and adds a button for each action. */ private void addActionButtons(RemoteViews bigView) { // Remove the existing buttons in case an existing notification is being updated. bigView.removeAllViews(R.id.buttons); // Always set the visibility of the views associated with the action buttons. The current // visibility state is not known as perhaps an existing notification is being updated. int visibility = mActions.isEmpty() ? View.GONE : View.VISIBLE; bigView.setViewVisibility(R.id.button_divider, visibility); bigView.setViewVisibility(R.id.buttons, visibility); Resources resources = mContext.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); for (Action action : mActions) { RemoteViews view = new RemoteViews(mContext.getPackageName(), R.layout.web_notification_button); // If there is an icon then set it and add some padding. if (action.iconBitmap != null || action.iconId != 0) { if (useMaterial()) { view.setInt(R.id.button_icon, "setColorFilter", BUTTON_ICON_COLOR_MATERIAL); } int iconWidth = 0; if (action.iconBitmap != null) { view.setImageViewBitmap(R.id.button_icon, action.iconBitmap); iconWidth = action.iconBitmap.getWidth(); } else if (action.iconId != 0) { view.setImageViewResource(R.id.button_icon, action.iconId); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(resources, action.iconId, options); iconWidth = options.outWidth; } iconWidth = dpToPx(Math.min(pxToDp(iconWidth, metrics), MAX_ACTION_ICON_WIDTH_DP), metrics); // Set the padding of the button so the text does not overlap with the icon. Flip // between left and right manually as RemoteViews does not expose a method that sets // padding in a writing-direction independent way. int buttonPadding = dpToPx(BUTTON_PADDING_START_DP + BUTTON_ICON_PADDING_DP, metrics) + iconWidth; int buttonPaddingLeft = LocalizationUtils.isLayoutRtl() ? 0 : buttonPadding; int buttonPaddingRight = LocalizationUtils.isLayoutRtl() ? buttonPadding : 0; view.setViewPadding(R.id.button, buttonPaddingLeft, 0, buttonPaddingRight, 0); } view.setTextViewText(R.id.button, action.title); view.setOnClickPendingIntent(R.id.button, action.intent); bigView.addView(R.id.buttons, view); } }
private void freshAnim(final Context context) { // 刷新的帧动画 final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.weather_widget); views.setViewVisibility(R.id.pb_fresh_weather, View.VISIBLE); views.setImageViewResource(R.id.iv_fresh_weather, R.drawable.weather_widget_icon_yin_l); ComponentName provider = new ComponentName(context, WeatherWidget.class); AppWidgetManager.getInstance(context).updateAppWidget(provider, views); }
/** * Set up English voice search button in the widget * * @param context * @param remoteView */ private void setupEnglishVoiceSearch(Context context, RemoteViews remoteView) { if (Device.DEVICE_TYPE.equals(Device.DeviceType.Google_TV)) { remoteView.setViewVisibility(R.id.eng_voice, View.INVISIBLE); } else { // ---this intent points to activity that should handle results--- Intent activityIntent2 = new Intent(_actionVoiceSearch); PendingIntent resultsPendingIntent2 = PendingIntent.getService(context, 0, activityIntent2, 0); // ---this intent calls the English voice recognition--- Intent englishVoiceIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); englishVoiceIntent.putExtra( RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); englishVoiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 2); englishVoiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak your search"); englishVoiceIntent.putExtra( RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, resultsPendingIntent2); // ---wraps speech recognition intent--- PendingIntent englishPendingIntent = PendingIntent.getActivity( context, randomGenerator.nextInt(100), englishVoiceIntent, PendingIntent.FLAG_CANCEL_CURRENT); remoteView.setOnClickPendingIntent(R.id.eng_voice, englishPendingIntent); } }
/** 显示自定义的带进度条通知栏 */ private void showCustomProgressNotify(String status) { RemoteViews mRemoteViews = new RemoteViews(getPackageName(), R.layout.view_custom_progress); mRemoteViews.setImageViewResource(R.id.custom_progress_icon, R.drawable.icon); mRemoteViews.setTextViewText(R.id.tv_custom_progress_title, "今日头条"); mRemoteViews.setTextViewText(R.id.tv_custom_progress_status, status); if (progress >= 100 || downloadThread == null) { mRemoteViews.setProgressBar(R.id.custom_progressbar, 0, 0, false); mRemoteViews.setViewVisibility(R.id.custom_progressbar, View.GONE); } else { mRemoteViews.setProgressBar(R.id.custom_progressbar, 100, progress, false); mRemoteViews.setViewVisibility(R.id.custom_progressbar, View.VISIBLE); } mBuilder.setContent(mRemoteViews).setContentIntent(getDefalutIntent(0)).setTicker("头条更新"); Notification nitify = mBuilder.build(); nitify.contentView = mRemoteViews; mNotificationManager.notify(notifyId, nitify); }
@Override protected void onHandleIntent(Intent intent) { Log.i(LOG, "Called"); AppWidgetManager mgr = AppWidgetManager.getInstance(getApplicationContext()); int[] widgetIds = mgr.getAppWidgetIds(new ComponentName(getApplicationContext(), CamWidgetProvider.class)); for (int widgetId : widgetIds) { Log.i(LOG, "Updating widget id " + widgetId); refreshText(mgr, widgetId); SharedPreferences prefs = getApplicationContext() .getSharedPreferences(CamWidgetConfigure.PREFS_NAME, Context.MODE_PRIVATE); List<String> cameraSet = split(prefs.getString(CamWidgetConfigure.CAMERA_SET + "_" + widgetId, "")); List<String> temps = new ArrayList<String>(); for (String camId : cameraSet) { int retries = 3; String temp = null; for (int i = 0; i < retries && temp == null; i++) { temp = tempFromCamera(Integer.valueOf(camId)); } temps.add(temp); } StringBuilder result = new StringBuilder(); for (String temp : temps) { if (temp == null) { result.append("?"); } else { result.append(temp); } result.append("\n"); } if (result.length() > 0) { result.delete(result.length() - 1, result.length()); } RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.appwidget); remoteViews.setTextViewText(R.id.text, result.toString()); remoteViews.setViewVisibility(R.id.text, View.VISIBLE); remoteViews.setViewVisibility(R.id.progress, View.INVISIBLE); mgr.updateAppWidget(widgetId, remoteViews); } }
private static RemoteViews getRemoteView(Context context, TaskSnippet taskInfo) { Date today = new Date(); RemoteViews view = new RemoteViews(context.getPackageName(), R.layout.home_widget); view.setTextViewText(R.id.taskName, taskInfo.taskName); final String dateString = today.format("MMM").toUpperCase() + " " + today.getDay(); Log.d(Constants.LogTag, String.format("getRemoteView: Date is %s", dateString)); final int selectedId = taskInfo.doneToday ? R.id.currentDateSelected : R.id.currentDate; view.setTextViewText(selectedId, dateString); view.setViewVisibility( R.id.currentDate, R.id.currentDate == selectedId ? View.VISIBLE : View.GONE); view.setViewVisibility( R.id.currentDateSelected, R.id.currentDateSelected == selectedId ? View.VISIBLE : View.GONE); return view; }
private void updateWeatherViews(Context context, RemoteViews views) { // 先查询当前城市 String localCity = DatabaseHelper.getLocalCity(context); // 再通过contentprovider获取当前城市的信息 WeatherInfo weatherInfo = DatabaseHelper.getTodayData( context, localCity); // WeatherResolver.getNowData(context, "北京"); if (weatherInfo != null) { String weather; if (DateUtil.isNight()) { weather = weatherInfo.getValueByKey(WeatherInfo.WEATHER_NIGHT); if (TextUtils.isEmpty(weather)) { weather = weatherInfo.getValueByKey(WeatherInfo.WEATHER_DAY); } } else { weather = weatherInfo.getValueByKey(WeatherInfo.WEATHER_DAY); } String maxtemper = weatherInfo.getValueByKey(WeatherInfo.MAXTEMPER); String mintemper = weatherInfo.getValueByKey(WeatherInfo.MINTEMPER); String temper = mintemper + "\b~\b" + maxtemper + context.getResources().getString(R.string.temperature_sign); views.setTextViewText(R.id.tv_widget_temper, temper); views.setImageViewResource( R.id.iv_weather, ResourceUtil.getResourceByWeather(weather, true, true)); if (!TextUtils.isEmpty(weather) && weather.length() > 5) { weather = weather.substring(0, 4) + ".."; } views.setTextViewText(R.id.tv_widget_weather, weather); String city = weatherInfo.getValueByKey(WeatherInfo.CITY_NAME); views.setTextViewText( R.id.tv_location_city, city.substring(city.indexOf("|") + 1, city.length())); views.setViewVisibility(R.id.rl_weather, View.VISIBLE); views.setViewVisibility(R.id.rl_fresh_weather, View.INVISIBLE); } }
public void widget4_4Week(RemoteViews views, AppWidgetManager manager) { pref.edit().putInt("viewMode", 0).apply(); viewMode = 0; wIndex4_4 = 0; mIndex4_4 = 0; views.setViewVisibility(R.id.tvYear, View.VISIBLE); views.setViewVisibility(R.id.btWeek, View.GONE); views.setViewVisibility(R.id.btMonth, View.VISIBLE); // Visible views.setViewVisibility(R.id.ivWeek, View.VISIBLE); views.setViewVisibility(R.id.llMonth, View.GONE); Dates.NOW.setWeekData(wIndex4_4); WeekCaptureView iv = new WeekCaptureView(this); views.setTextViewText(R.id.tvYear, Dates.NOW.year + getString(R.string.year)); views.setTextViewText(R.id.tvDate, setMonthWeek()); Common.fetchWeekData(); 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); }
/** Display folders */ public void displayFolders(RemoteViews remoteViews) { int displayedFolder = 0; for (Folder folderValues : mFoldersSortedSet) { int viewId = getFolderViewId(displayedFolder); if (viewId == 0) { continue; } remoteViews.setViewVisibility(viewId, View.VISIBLE); int color[] = new int[] {folderValues.getBackgroundColor(mDefaultBgColor)}; Bitmap bitmap = Bitmap.createBitmap(color, 1, 1, Bitmap.Config.RGB_565); remoteViews.setImageViewBitmap(viewId, bitmap); if (++displayedFolder == MAX_DISPLAYED_FOLDERS_COUNT) { break; } } for (int i = displayedFolder; i < MAX_DISPLAYED_FOLDERS_COUNT; i++) { remoteViews.setViewVisibility(getFolderViewId(i), View.GONE); } }
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); } }
/** * 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; }
public void configureActionBar(Context context, RemoteViews rv) { String formattedDate = DateUtils.formatDateTime( context, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY); rv.setTextViewText(R.id.calendar_current_date, formattedDate.toUpperCase(Locale.getDefault())); Intent startConfigIntent = new Intent(context, WidgetConfigurationActivity.class); PendingIntent menuPendingIntent = PendingIntent.getActivity(context, 0, startConfigIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.overflow_menu, menuPendingIntent); Intent intent = CalendarIntentUtil.createNewEventIntent(); if (isIntentAvailable(context, intent)) { PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.add_event, pendingIntent); } else { rv.setViewVisibility(R.id.add_event, View.GONE); } }
/** 显示软件下载对话框 */ private void showDownloadNotification() { // 构造软件下载对话框 if (notification == null) notification = new Notification( android.R.drawable.stat_sys_download, mContext.getString(R.string.soft_updating), System.currentTimeMillis()); else { notification.icon = android.R.drawable.stat_sys_download; notification.tickerText = mContext.getString(R.string.soft_updating); notification.when = System.currentTimeMillis(); } notification.flags |= Notification.FLAG_ONGOING_EVENT; RemoteViews contentView = new RemoteViews(mContext.getPackageName(), R.layout.download_notification); notification.contentView = contentView; contentView.setTextViewText( R.id.notificationTitle, mContext.getResources().getString(R.string.notify_downloading) + mContext.getString(R.string.theme_box_name)); contentView.setTextViewText(R.id.notificationPercent, "0%"); contentView.setProgressBar(R.id.notificationProgress, 100, 0, true); contentView.setViewVisibility(R.id.cancel, View.VISIBLE); Intent it = new Intent(mContext, UIStaticsReceiver.class); it.setAction("com.coco.personalCenter.stop.update"); PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, it, 0); contentView.setOnClickPendingIntent(R.id.cancel, pendingIntent); Intent intent = new Intent(); intent.putExtra("notifyID", id); PendingIntent contentIntent = PendingIntent.getActivity( mContext, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT); notification.contentIntent = contentIntent; manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(id, notification); // 下载文件 downloadApk(); // cancel(cancelUpdate = true; // dialogIsShow = false;) }
@Override public RemoteViews getViewAt(int position) { RemoteViews row = new RemoteViews(context.getPackageName(), R.layout.widget_list_item); cursor.moveToPosition(position); Build build = FlowManager.getModelAdapter(Build.class).loadFromCursor(cursor); row.setTextViewText(R.id.build_number, "Build #" + build.getNumber()); row.setTextViewText(R.id.build_state, ": " + build.getState()); row.setTextViewText(R.id.build_duration, String.valueOf(build.getDuration())); row.setTextViewText(R.id.build_finished, String.valueOf(build.getFinishedAt())); if (build.isPullRequest()) { row.setTextViewText(R.id.build_pull_request_title, build.getPullRequestTitle()); } else { row.setViewVisibility(R.id.build_pull_request_title, View.GONE); } GHCommit commit = build.getCommit(); if (commit != null) { row.setTextViewText(R.id.build_commit_message, commit.getMessage()); row.setTextViewText(R.id.build_commit_person, commit.getAuthorName()); row.setTextViewText(R.id.build_branch, commit.getBranch()); } return row; }
/** Shows the work profile badge if it is needed. */ private void addWorkProfileBadge(RemoteViews view) { Resources resources = mContext.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); int size = dpToPx(WORK_PROFILE_BADGE_SIZE_DP, metrics); int[] colors = new int[size * size]; // Create an immutable bitmap, so that it can not be reused for painting a badge into it. Bitmap bitmap = Bitmap.createBitmap(colors, size, size, Bitmap.Config.ARGB_8888); Drawable inputDrawable = new BitmapDrawable(resources, bitmap); Drawable outputDrawable = ApiCompatibilityUtils.getUserBadgedDrawableForDensity( mContext, inputDrawable, null /* badgeLocation */, metrics.densityDpi); // The input bitmap is immutable, so the output drawable will be a different instance from // the input drawable if the work profile badge was applied. if (inputDrawable != outputDrawable && outputDrawable instanceof BitmapDrawable) { view.setImageViewBitmap( R.id.work_profile_badge, ((BitmapDrawable) outputDrawable).getBitmap()); view.setViewVisibility(R.id.work_profile_badge, View.VISIBLE); } }
// Init notification UI. private void initNotifyView( Context context, RemoteViews panelView, ChatMsgBaseInfo message, ContactInfo contact, Bitmap srcPhoto) { if (contact != null) { Bitmap photo = ImageLoaderManager.createCircleImage(srcPhoto); if (photo != null) { panelView.setViewVisibility(R.id.notify_profile_logogram_tv, View.GONE); panelView.setViewVisibility(R.id.notify_profile_iv, View.VISIBLE); panelView.setImageViewBitmap(R.id.notify_profile_iv, photo); } else { panelView.setViewVisibility(R.id.notify_profile_iv, View.VISIBLE); panelView.setImageViewResource( R.id.notify_profile_iv, CommonUtils.getPhotoBgResId(contact.getUsername())); panelView.setViewVisibility(R.id.notify_profile_logogram_tv, View.VISIBLE); panelView.setTextViewText( R.id.notify_profile_logogram_tv, contact.getUsername().substring(contact.getUsername().length() - 1)); } panelView.setTextViewText(R.id.notify_sender_tv, contact.getUsername()); } else { panelView.setTextViewText(R.id.notify_sender_tv, message.getContact()); panelView.setViewVisibility(R.id.notify_profile_logogram_tv, View.GONE); panelView.setViewVisibility(R.id.notify_profile_iv, View.VISIBLE); panelView.setImageViewResource(R.id.notify_profile_iv, R.drawable.contact_default_profile); } // TODO: ADD Emoji parser later. // panelView.setTextViewText(R.id.notify_msg_content_tv, // EmojiParser.getInstance(context).getSmileyText(message.getData())); panelView.setTextViewText(R.id.notify_msg_content_tv, message.getData()); panelView.setTextViewText( R.id.notify_time_tv, TimeFormattedUtil.getDetailDisplayTime(context, message.getTime())); }
/** * Update a single widget. * * @param context {@link Context} * @param appWidgetManager {@link AppWidgetManager} * @param appWidgetId id of widget */ static void updateWidget( final Context context, final AppWidgetManager appWidgetManager, final int appWidgetId) { Log.d(TAG, "updateWidget(" + appWidgetId + ")"); final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); final long pid = p.getLong(WIDGET_PLANID + appWidgetId, -1L); final boolean showShortname = p.getBoolean(WIDGET_SHORTNAME + appWidgetId, false); final boolean showCost = p.getBoolean(WIDGET_COST + appWidgetId, false); final boolean showBillPeriod = p.getBoolean(WIDGET_BILLPERIOD + appWidgetId, false); final boolean showIcon = p.getBoolean(WIDGET_ICON + appWidgetId, false); final boolean smallWidget = p.getBoolean(WIDGET_SMALL + appWidgetId, false); final Float statsTextSize = p.getFloat(WIDGET_STATS_TEXTSIZE + appWidgetId, StatsAppWidgetConfigure.DEFAULT_TEXTSIZE); final Float planTextSize = p.getFloat(WIDGET_PLAN_TEXTSIZE + appWidgetId, StatsAppWidgetConfigure.DEFAULT_TEXTSIZE); final int textColor = p.getInt(WIDGET_TEXTCOLOR + appWidgetId, StatsAppWidgetConfigure.DEFAULT_TEXTCOLOR); final int bgColor = p.getInt(WIDGET_BGCOLOR + appWidgetId, StatsAppWidgetConfigure.DEFAULT_BGCOLOR); Log.d(TAG, "planid: " + pid); final ContentResolver cr = context.getContentResolver(); if (pid < 0L) { return; } final long ppid = DataProvider.Plans.getParent(cr, pid); long bid = -1L; String pname = null; float cpp = 0F; int ltype = DataProvider.LIMIT_TYPE_NONE; long limit = 0L; int ptype = -1; String where; int upc, upm, ups; boolean isMerger; String billdayWhere = null; Cursor cursor = cr.query( DataProvider.Plans.CONTENT_URI, DataProvider.Plans.PROJECTION, DataProvider.Plans.ID + " = ?", new String[] {String.valueOf(pid)}, null); if (cursor.moveToFirst()) { if (showShortname) { pname = cursor.getString(DataProvider.Plans.INDEX_SHORTNAME); } else { pname = cursor.getString(DataProvider.Plans.INDEX_NAME); } ptype = cursor.getInt(DataProvider.Plans.INDEX_TYPE); bid = cursor.getLong(DataProvider.Plans.INDEX_BILLPERIOD_ID); ltype = cursor.getInt(DataProvider.Plans.INDEX_LIMIT_TYPE); limit = DataProvider.Plans.getLimit(ptype, ltype, cursor.getLong(DataProvider.Plans.INDEX_LIMIT)); upc = cursor.getInt(DataProvider.Plans.INDEX_MIXED_UNITS_CALL); upm = cursor.getInt(DataProvider.Plans.INDEX_MIXED_UNITS_MMS); ups = cursor.getInt(DataProvider.Plans.INDEX_MIXED_UNITS_SMS); cpp = cursor.getFloat(DataProvider.Plans.INDEX_COST_PER_PLAN); final String s = cursor.getString(DataProvider.Plans.INDEX_MERGED_PLANS); where = DataProvider.Plans.parseMergerWhere(pid, s); if (s == null || s.length() == 0) { isMerger = false; } else { isMerger = true; } } else { return; } cursor.close(); int bpos = 0; int bmax = -1; if (bid >= 0L) { cursor = cr.query( DataProvider.Plans.CONTENT_URI, DataProvider.Plans.PROJECTION, DataProvider.Plans.ID + " = ?", new String[] {String.valueOf(bid)}, null); if (cursor.moveToFirst()) { final int bp = cursor.getInt(DataProvider.Plans.INDEX_BILLPERIOD); final long bday = cursor.getLong(DataProvider.Plans.INDEX_BILLDAY); billdayWhere = DataProvider.Plans.getBilldayWhere(bp, bday, null); if (showBillPeriod && bp != DataProvider.BILLPERIOD_INFINITE) { Calendar billDay = Calendar.getInstance(); billDay.setTimeInMillis(bday); billDay = DataProvider.Plans.getBillDay(bp, billDay, null, false); final Calendar nextBillDay = DataProvider.Plans.getBillDay(bp, billDay, null, true); final long pr = billDay.getTimeInMillis() / CallMeter.MILLIS; final long nx = (nextBillDay.getTimeInMillis() // . / CallMeter.MILLIS) - pr; long nw = System.currentTimeMillis(); nw = (nw / CallMeter.MILLIS) - pr; bmax = (int) nx; bpos = (int) nw; } } cursor.close(); } Log.d(TAG, "bpos/bmax: " + bpos + "/" + bmax); billdayWhere = DbUtils.sqlAnd(billdayWhere, where); int used = 0; PlanStatus ps = PlanStatus.get( cr, billdayWhere, isMerger && ptype == DataProvider.TYPE_MIXED, upc, upm, ups); if (ps == null) { ps = new PlanStatus(); } else { Log.d(TAG, "plan: " + pid); Log.d(TAG, "count: " + ps.count); Log.d(TAG, "cost: " + ps.cost); Log.d(TAG, "billedAmount: " + ps.billedAmount); used = DataProvider.Plans.getUsed(ptype, ltype, ps.billedAmount, ps.cost); } if (ppid >= 0L) { ps.cost = 0F; } else { ps.cost += cpp; } String stats = Plans.formatAmount(ptype, ps.billedAmount, p.getBoolean(Preferences.PREFS_SHOWHOURS, true)); if (ptype == DataProvider.TYPE_CALL) { stats += " (" + ps.count + ")"; } if (limit > 0) { stats += "\n" + (used * CallMeter.HUNDRET / limit) + "%"; } if (showCost && ps.cost > 0F) { stats += "\n" + String.format(Preferences.getCurrencyFormat(context), ps.cost); } Log.d(TAG, "limit: " + limit); Log.d(TAG, "used: " + used); Log.d(TAG, "stats: " + stats); final int widgetLayout = smallWidget ? R.layout.stats_appwidget_small : R.layout.stats_appwidget; final RemoteViews views = new RemoteViews(context.getPackageName(), widgetLayout); views.setImageViewBitmap(R.id.widget_bg, getBackground(bgColor, bmax, bpos, limit, used)); views.setTextViewText(R.id.plan, pname); views.setTextViewText(R.id.stats, stats); views.setFloat(R.id.plan, "setTextSize", planTextSize); views.setFloat(R.id.stats, "setTextSize", statsTextSize); views.setTextColor(R.id.plan, textColor); views.setTextColor(R.id.stats, textColor); views.setOnClickPendingIntent( R.id.widget, PendingIntent.getActivity(context, 0, new Intent(context, Plans.class), 0)); if (showIcon) { views.setViewVisibility(R.id.widget_icon, android.view.View.VISIBLE); switch (ptype) { case DataProvider.TYPE_DATA: views.setImageViewResource(R.id.widget_icon, R.drawable.data); break; case DataProvider.TYPE_CALL: views.setImageViewResource(R.id.widget_icon, R.drawable.phone); break; case DataProvider.TYPE_SMS: case DataProvider.TYPE_MMS: views.setImageViewResource(R.id.widget_icon, R.drawable.message); break; case DataProvider.TYPE_MIXED: views.setImageViewResource(R.id.widget_icon, R.drawable.phone); break; } } appWidgetManager.updateAppWidget(appWidgetId, views); }
/* * Return the full View */ public RemoteViews getStyledView( final CharSequence date, final Conversation conversation, final FolderUri folderUri, final int ignoreFolderType, final SpannableStringBuilder senders, final String filteredSubject) { final boolean isUnread = !conversation.read; final String snippet = conversation.getSnippet(); final boolean hasAttachments = conversation.hasAttachments; // Add style to date final CharSequence styledDate = addStyle(date, DATE_FONT_SIZE, DATE_TEXT_COLOR); // Add style to subject final int subjectColor = isUnread ? SUBJECT_TEXT_COLOR_UNREAD : SUBJECT_TEXT_COLOR_READ; final SpannableStringBuilder subjectAndSnippet = new SpannableStringBuilder( Conversation.getSubjectAndSnippetForDisplay(mContext, filteredSubject, snippet)); if (isUnread) { subjectAndSnippet.setSpan( new StyleSpan(Typeface.BOLD), 0, filteredSubject.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } subjectAndSnippet.setSpan( new ForegroundColorSpan(subjectColor), 0, subjectAndSnippet.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); final CharSequence styledSubject = addStyle(subjectAndSnippet, SUBJECT_FONT_SIZE, 0); // Paper clip for attachment Bitmap paperclipBitmap = null; if (hasAttachments) { paperclipBitmap = ATTACHMENT; } // Inflate and fill out the remote view final RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(), R.layout.widget_conversation_list_item); remoteViews.setTextViewText(R.id.widget_senders, senders); remoteViews.setTextViewText(R.id.widget_date, styledDate); remoteViews.setTextViewText(R.id.widget_subject, styledSubject); if (paperclipBitmap != null) { remoteViews.setViewVisibility(R.id.widget_attachment, View.VISIBLE); remoteViews.setImageViewBitmap(R.id.widget_attachment, paperclipBitmap); } else { remoteViews.setViewVisibility(R.id.widget_attachment, View.GONE); } if (isUnread) { remoteViews.setViewVisibility(R.id.widget_unread_background, View.VISIBLE); remoteViews.setViewVisibility(R.id.widget_read_background, View.GONE); } else { remoteViews.setViewVisibility(R.id.widget_unread_background, View.GONE); remoteViews.setViewVisibility(R.id.widget_read_background, View.VISIBLE); } if (mContext.getResources().getBoolean(R.bool.display_folder_colors_in_widget)) { mFolderDisplayer = new WidgetFolderDisplayer(mContext); mFolderDisplayer.loadConversationFolders(conversation, folderUri, ignoreFolderType); mFolderDisplayer.displayFolders(remoteViews); } return remoteViews; }
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_WIDGET_UPDATE.equals(action)) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.vlcwidget); String title = intent.getStringExtra("title"); String artist = intent.getStringExtra("artist"); boolean isplaying = intent.getBooleanExtra("isplaying", false); Bitmap cover = intent.getParcelableExtra("cover"); views.setTextViewText(R.id.songName, title); views.setTextViewText(R.id.artist, artist); views.setImageViewResource( R.id.play_pause, isplaying ? R.drawable.ic_pause : R.drawable.ic_play); if (cover != null) views.setImageViewBitmap(R.id.cover, cover); else views.setImageViewResource(R.id.cover, R.drawable.cone); views.setViewVisibility( R.id.timeline_parent, artist != null && artist.length() > 0 ? View.VISIBLE : View.INVISIBLE); /* commands */ Intent iBackward = new Intent(ACTION_REMOTE_BACKWARD); Intent iPlay = new Intent(ACTION_REMOTE_PLAYPAUSE); Intent iStop = new Intent(ACTION_REMOTE_STOP); Intent iForward = new Intent(ACTION_REMOTE_FORWARD); Intent iVlc = new Intent(); iVlc.setClassName(VLC_PACKAGE, isplaying ? VLC_PLAYER : VLC_MAIN); iVlc.putExtra(START_FROM_NOTIFICATION, true); PendingIntent piBackward = PendingIntent.getBroadcast(context, 0, iBackward, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piPlay = PendingIntent.getBroadcast(context, 0, iPlay, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piStop = PendingIntent.getBroadcast(context, 0, iStop, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piForward = PendingIntent.getBroadcast(context, 0, iForward, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piVlc = PendingIntent.getActivity(context, 0, iVlc, PendingIntent.FLAG_UPDATE_CURRENT); views.setOnClickPendingIntent(R.id.backward, piBackward); views.setOnClickPendingIntent(R.id.play_pause, piPlay); views.setOnClickPendingIntent(R.id.stop, piStop); views.setOnClickPendingIntent(R.id.forward, piForward); views.setOnClickPendingIntent(R.id.cover, piVlc); ComponentName widget = new ComponentName(context, VLCAppWidgetProvider.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(widget, views); } else if (ACTION_WIDGET_UPDATE_POSITION.equals(action)) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.vlcwidget); float pos = intent.getFloatExtra("position", 0f); views.setProgressBar(R.id.timeline, 100, (int) (100 * pos), false); ComponentName widget = new ComponentName(context, VLCAppWidgetProvider.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(widget, views); } else super.onReceive(context, intent); }
@Override public void setViewVisibility(int viewId, int visibility) { mRemoteViews.setViewVisibility(viewId, visibility); }
@Override protected void onHandleIntent(Intent intent) { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(this, NextGameWidgetProvider.class)); String sortOrder = GamesContract.GamesEntry.COLUMN_DATE + " ASC"; String selectionAllGames = GamesContract.GamesEntry.COLUMN_TEAM_NAME + " = " + "'" + Utilities.getFullNameFromQuery(Utilities.getPreferredTeam(getApplicationContext())) + "'"; String selectionUnfinished = selectionAllGames + " and " + GamesContract.GamesEntry.COLUMN_TEAM_SCORE + " = -1"; Cursor data = getContentResolver() .query( GamesContract.GamesEntry.CONTENT_URI, null, selectionUnfinished, null, sortOrder); if (data == null) { return; } if (!data.moveToFirst()) { data.close(); return; } for (int appWidgetId : appWidgetIds) { RemoteViews views = new RemoteViews(getPackageName(), R.layout.widget_last_game); int widgetWidth = getWidgetWidth(appWidgetManager, appWidgetId); int smallWidth = getResources().getDimensionPixelSize(R.dimen.widget_last_game_small_width); int middleWidth = getResources().getDimensionPixelSize(R.dimen.widget_last_game_middle_width); data.moveToFirst(); if (widgetWidth <= smallWidth) { views.setViewVisibility(R.id.list_item_score_home_team, View.GONE); views.setViewVisibility(R.id.list_item_score_away_team, View.GONE); views.setViewVisibility(R.id.list_item_date, View.GONE); } else if (widgetWidth <= middleWidth) { views.setViewVisibility(R.id.list_item_score_home_team, View.GONE); views.setViewVisibility(R.id.list_item_score_away_team, View.GONE); views.setViewVisibility(R.id.list_item_date, View.VISIBLE); } else { views.setViewVisibility(R.id.list_item_score_home_team, View.VISIBLE); views.setViewVisibility(R.id.list_item_score_away_team, View.VISIBLE); views.setViewVisibility(R.id.list_item_date, View.VISIBLE); } Event event = new Event(data); if (Utilities.isHomeGame(event)) { views.setImageViewResource( R.id.list_item_logo_away_team, Utilities.getTeamLogo( getApplicationContext(), data.getString(data.getColumnIndex(GamesContract.GamesEntry.COLUMN_TEAM_NAME)))); views.setTextViewText( R.id.list_item_score_away_team, String.format( getString(R.string.win_loss_divider), data.getString( data.getColumnIndex(GamesContract.GamesEntry.COLUMN_TEAM_EVENTS_WON)), data.getString( data.getColumnIndex(GamesContract.GamesEntry.COLUMN_TEAM_EVENTS_LOST)))); views.setImageViewResource( R.id.list_item_logo_home_team, Utilities.getTeamLogo( getApplicationContext(), data.getString( data.getColumnIndex(GamesContract.GamesEntry.COLUMN_OPPONENT_NAME)))); views.setTextViewText( R.id.list_item_score_home_team, String.format( getString(R.string.win_loss_divider), data.getString( data.getColumnIndex(GamesContract.GamesEntry.COLUMN_OPPONENT_EVENTS_WON)), data.getString( data.getColumnIndex(GamesContract.GamesEntry.COLUMN_OPPONENT_EVENTS_LOST)))); } else { views.setImageViewResource( R.id.list_item_logo_away_team, Utilities.getTeamLogo( getApplicationContext(), data.getString( data.getColumnIndex(GamesContract.GamesEntry.COLUMN_OPPONENT_NAME)))); views.setTextViewText( R.id.list_item_score_away_team, String.format( getString(R.string.win_loss_divider), data.getString( data.getColumnIndex(GamesContract.GamesEntry.COLUMN_OPPONENT_EVENTS_WON)), data.getString( data.getColumnIndex(GamesContract.GamesEntry.COLUMN_OPPONENT_EVENTS_LOST)))); views.setImageViewResource( R.id.list_item_logo_home_team, Utilities.getTeamLogo( getApplicationContext(), data.getString(data.getColumnIndex(GamesContract.GamesEntry.COLUMN_TEAM_NAME)))); views.setTextViewText( R.id.list_item_score_home_team, String.format( getString(R.string.win_loss_divider), data.getString( data.getColumnIndex(GamesContract.GamesEntry.COLUMN_TEAM_EVENTS_WON)), data.getString( data.getColumnIndex(GamesContract.GamesEntry.COLUMN_TEAM_EVENTS_LOST)))); } views.setTextViewText( R.id.list_item_date, Utilities.getDaysBefore( data.getString(data.getColumnIndex(GamesContract.GamesEntry.COLUMN_DATE)))); data.close(); // 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_container, pendingIntent); // Tell the AppWidgetManager to perform an update on the current app widget appWidgetManager.updateAppWidget(appWidgetId, views); } }