Jef*_*eff 10 android widget homescreen
有人能告诉我如何检查我的小部件是否已放置在主屏幕上?
我的应用程序中有一些代码,只有在小部件放在主屏幕上时才能运行.
Waz*_*_Be 45
只是说,但......
int ids[] = AppWidgetManager.getInstance(this).getAppWidgetIds(new ComponentName(this,MyAppWidgetProvider.class));
Toast.makeText(this, "Number of widgets: "+ids.length, Toast.LENGTH_LONG).show();
Run Code Online (Sandbox Code Playgroud)
您需要自己存储该信息.我通常使用应用程序首选项,但您可以使用任何东西.通常小部件使用服务进行通信,因此您的代码可能在服务中,但使用首选项允许您的应用程序的任何部分访问它.
在扩展AppWidgetProvider的widget类中,当窗口小部件放在主屏幕上时调用onEnabled,并且在删除onDeleted时(通常)调用onDeleted.删除所有副本时调用onDisabled.
所以在你的小部件提供者的代码中:
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
setWidgetActive(true);
context.startService(new Intent(appContext, WidgetUpdateService.class));
}
@Override
public void onDisabled(Context context) {
Context appContext = context.getApplicationContext();
setWidgetActive(false);
context.stopService(new Intent(appContext, WidgetUpdateService.class));
super.onDisabled(context);
}
private void setWidgetActive(boolean active){
Context appContext = context.getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext);
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(Constants.WIDGET_ACTIVE, active);
edit.commit();
}
Run Code Online (Sandbox Code Playgroud)
在代码的其他地方,您将通过以下方式检查窗口小部件是否处于活动状态:
public boolean isWidgetActive(Context context){
Context appContext = context.getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getBoolean(Constants.WIDGET_ACTIVE, false);
}
Run Code Online (Sandbox Code Playgroud)
我知道这是一个老问题,但今天看到这个我看到@ larsona1接受的答案有几个问题:
我找到了第一个问题的解决方案.根本不需要共享偏好,因为它无论如何都是不可靠的.必须在运行时检查它.
// in some class you define a static variable, say in S.java
static boolean sWidgetMayExist = true;
Run Code Online (Sandbox Code Playgroud)
在您的小部件提供商:
// MyAppWidgetProvider.java
// to respond to runtime changes, when widgets are added and removed
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
S.sWidgetMayExist = true;
}
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
S.sWidgetMayExist = true;
}
Run Code Online (Sandbox Code Playgroud)
并且,在您的服务代码中添加以下内容:
AppWidgetManager manager = null;
RemoteViews views = null;
ComponentName widgetComponent = null;
// ..and in your update thread
if (!S.sWidgetMayExist) { return; }
if (manager == null || widgetComponent == null) {
widgetComponent = new ComponentName(c,
MyAppWidgetProvider.class);
manager = AppWidgetManager.getInstance(c);
}
if (manager.getAppWidgetIds(widgetComponent) == null) {
S.sWidgetMayExist = false;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7379 次 |
| 最近记录: |