700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > android widget 发送广播 android-从应用程序向小部件发送数据

android widget 发送广播 android-从应用程序向小部件发送数据

时间:2023-11-06 09:35:21

相关推荐

android widget 发送广播 android-从应用程序向小部件发送数据

我被困在一个特殊的场景中.用户从应用程序更新时间后,我需要立即更新我的小部件.我确实通过发送Intent Extras数据来尝试广播,但是没有这样做.当前,我的数据存储在AppWidgetProvider中,我需要将此数据发送到服务

公共类CountdownWidget扩展了AppWidgetProvider {

????// SharedPreferences userDefaults;

// update rate in milliseconds

public static final int UPDATE_RATE = 1800000; // 30 minute

public static String nameOne = "";

@Override

public void onDeleted(Context context, int[] appWidgetIds) {

for (int appWidgetId : appWidgetIds) {

setAlarm(context, appWidgetId, -1);

}

super.onDeleted(context, appWidgetIds);

}

@Override

public void onReceive(Context context, Intent intent) {

// TODO Auto-generated method stub

Bundle extras = intent.getExtras();

nameOne = extras.getString("NAME_ONE");

Log.e("Name: ", nameOne);

super.onReceive(context, intent);

}

@Override

public void onUpdate(Context context, AppWidgetManager appWidgetManager,

int[] appWidgetIds) {

for (int appWidgetId : appWidgetIds) {

setAlarm(context, appWidgetId, UPDATE_RATE);

}

super.onUpdate(context, appWidgetManager, appWidgetIds);

}

public static void setAlarm(Context context, int appWidgetId, int updateRate) {

// Log.e("", "Updating Widget Service");

PendingIntent newPending = makeControlPendingIntent(context,

CountdownService.UPDATE, appWidgetId);

AlarmManager alarms = (AlarmManager) context

.getSystemService(Context.ALARM_SERVICE);

if (updateRate >= 0) {

alarms.setRepeating(AlarmManager.ELAPSED_REALTIME,

SystemClock.elapsedRealtime(), updateRate, newPending);

} else {

// on a negative updateRate stop the refreshing

alarms.cancel(newPending);

}

}

public static PendingIntent makeControlPendingIntent(Context context,

String command, int appWidgetId) {

Intent active = new Intent(context, CountdownService.class);

active.setAction(command);

active.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

// this Uri data is to make the PendingIntent unique, so it wont be

// updated by FLAG_UPDATE_CURRENT

// so if there are multiple widget instances they wont override each

// other

Uri data = Uri.withAppendedPath(

Uri.parse("countdownwidget://widget/id/#" + command

+ appWidgetId), String.valueOf(appWidgetId));

active.setData(data);

return (PendingIntent.getService(context, 0, active,

PendingIntent.FLAG_UPDATE_CURRENT));

}

}

如您所见,nameOne是一个静态变量.我可以使用getExtras在onReceive方法上接收数据,但是我无法将这些数据传递给CountdownService服务.

我确实尝试了CountdownWidget.nameOne,但仍然无法满足服务中的数据要求.

任何帮助将不胜感激.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。