是否可以从主屏幕小部件访问 MainActivity 中的方法?
Is it possible to access a method in MainActivity from a Homescreen Widget?
我为我的应用制作了一个主屏幕小部件。我需要它与我的 MainActivity 中的方法进行通信。
我该怎么做?
开发文档提到 "control widgets" 但没有解释如何实现它们。(https://developer.android.com/guide/topics/appwidgets/overview#control-widgets)。
我是否需要服务或接口来在小部件和 MainActivity 之间进行通信?
我尝试过的:
我尝试使用 SharedPreferences 将我的点击计数器值从我的 WidgetProvider OnReceive 方法传递到我的 MainActivity。这在某种程度上确实有效,但它需要双向实时通信,所以它不合适。这就是为什么我在考虑服务方面的原因。但是会有更好的选择吗?
如果我使用某项服务,它会是特定的吗?像 "RemoteViewsService" 或 "IntentService"?
这是我的 WidgetProvider 中的代码示例:
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (ACTION_SIMPLE_APPWIDGET.equals(intent.getAction())) {
if (mCounter < optionsStrings.length - 1) {
mCounter++;
} else {
mCounter = 0;
}
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.app_widget);
stringText = optionsStrings[mCounter];
views.setTextViewText(R.id.appwidget_text, stringText);
根据计数器的值,我需要在MainActivity中触发各种方法。
MainActivity
可能是destoyed when you try to communicate with it. You'll need a service that both your Widget and Activity can communicate with. From what I understand, a IntentService可能是你想要的。
当 MainActivity
启动时,您需要附加到您的服务并询问它最近发送的 counter
值。然后,你应该可以做你想做的事了。
我为我的应用制作了一个主屏幕小部件。我需要它与我的 MainActivity 中的方法进行通信。
我该怎么做?
开发文档提到 "control widgets" 但没有解释如何实现它们。(https://developer.android.com/guide/topics/appwidgets/overview#control-widgets)。
我是否需要服务或接口来在小部件和 MainActivity 之间进行通信?
我尝试过的:
我尝试使用 SharedPreferences 将我的点击计数器值从我的 WidgetProvider OnReceive 方法传递到我的 MainActivity。这在某种程度上确实有效,但它需要双向实时通信,所以它不合适。这就是为什么我在考虑服务方面的原因。但是会有更好的选择吗?
如果我使用某项服务,它会是特定的吗?像 "RemoteViewsService" 或 "IntentService"?
这是我的 WidgetProvider 中的代码示例:
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (ACTION_SIMPLE_APPWIDGET.equals(intent.getAction())) {
if (mCounter < optionsStrings.length - 1) {
mCounter++;
} else {
mCounter = 0;
}
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.app_widget);
stringText = optionsStrings[mCounter];
views.setTextViewText(R.id.appwidget_text, stringText);
根据计数器的值,我需要在MainActivity中触发各种方法。
MainActivity
可能是destoyed when you try to communicate with it. You'll need a service that both your Widget and Activity can communicate with. From what I understand, a IntentService可能是你想要的。
当 MainActivity
启动时,您需要附加到您的服务并询问它最近发送的 counter
值。然后,你应该可以做你想做的事了。