在官方的SDK中有这么一段话
If you return RESULT_OK
using Activity.setResult()
, the AppWidget will be added, and you will receive an ACTION_APPWIDGET_UPDATE
broadcast for this AppWidget. If you returnRESULT_CANCELED
, the host will cancel the add and not display this AppWidget, and you will receive a ACTION_APPWIDGET_DELETED
broadcast.
大概就是需要setResult来告诉widget是否设置成功,使用大概如下
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_CANCELED, resultValue);
finish();
但是坑爹的是 and you will receive a
ACTION_APPWIDGET_DELETED
broadcast.这句,我在AppWidgetProvider根本就没收到这个广播啊。。。设置RESULT_OK时也没收到ACTION_APPWIDGET_UPDATE的广播。。。
我的解决办法:
自己发广播啊。。。
PS:
我看了看官方API DEMOS里的那个样例也是没有收到相应的广播,感觉就压根没发送啊。。。
我看这貌似是个BUG,详见http://code.google.com/p/android/issues/detail?id=2539,很多年前报告过,最近又有人反应RESULT_CANCELED是无法删除Ghost Widget,我试了试,AppWidgetId是会保留,而且在update方法调用时依然是会有该id传入的。。。
PS2这是个存在了5年的bug。。。
网上有一些变通的方法
http://www.rinofinazzo.com/blog/2011/12/23/android-phantom-widgets-fix/
基本思想就是自己标记哪些是Ghost Widget,然后再删除。