当 Widget 从主机中删除时,AppWidget 更新服务不会停止
我想做的是,一旦 AppWidget 从用户 Android 手机的主屏幕中删除,我想停止更新 AppWidget 的后台服务。
这是我正在使用的代码...不明白出了什么问题?
@Override
public void onDeleted(Context context, int[] appWidgetIds){
Intent serviceIntent = new Intent(context, UpdateService.class);
context.stopService(serviceIntent);
super.onDeleted(context, appWidgetIds);
}
有什么想法吗?感谢您的帮助。
What I am trying to do is once the AppWidget is removed from the homescreen of the user's Android phone, I want to stop the background service that Updates the AppWidget.
Here is the code that I am using...don't understand whats wrong?
@Override
public void onDeleted(Context context, int[] appWidgetIds){
Intent serviceIntent = new Intent(context, UpdateService.class);
context.stopService(serviceIntent);
super.onDeleted(context, appWidgetIds);
}
Any ideas? Thanks for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过大量研究,我终于修复了它。我的目标是如果所有 AppWidget 实例都从屏幕上删除,则停止后台服务。
这就是它的作用...
使用共享首选项来切换 1 和 0。当用户将小部件的第一个实例放在屏幕上时,SharePref 切换为 1。当应用程序小部件的最后一个实例从屏幕上删除时,它会切换回 0。
服务中的@Override OnReceive方法。监听这些广播 - AppWidget Enabled(当小部件的第一个实例放置在屏幕上时广播),AppWidget 禁用(当小部件的最后一个实例从屏幕上删除时由操作系统广播)
当AppWidget已禁用时广播调用重写方法OnDisabled方法。
3.在@Override OnDisabled方法中调用stopService。作品完美。
请记住 OnDeleted 和 OnDisabled 之间的区别。 OnDeleted 在删除小部件的实例时调用,但这并不意味着被删除的小部件是最后一个。我希望即使屏幕上只有一个小部件实例,我的服务仍然可以运行。
*此外,如果您不想执行上述所有操作并让 Android 负责服务等...请使用 IntentService。 **
After a lot of Research I finally fixed it. My goal here was to stop the background service if all AppWidget instances are removed from the screen.
This is what did it...
Used shared preferences to toggle 1 and 0. SharePref toggled to 1 when the very first instance of the widget is put on the screen by the user. It is toggled back to 0 when the last instance of the App widget is removed from the screen.
@Override OnReceive method in the Service. Listen for these broadcasts - AppWidget Enabled (broadcast when the very first instance of the widget is put on the screen) , AppWidget Disabled (broadcast by the OS when the very last instance of the widget is removed from the screen)
When AppWidget Disabled is broadcast call the overridden method OnDisabled method.
3.In @Override OnDisabled method call stopService. Works perfect.
Remember the difference between OnDeleted and OnDisabled. OnDeleted is called when an instance of the widget is removed, it doesn't mean that the widget being deleted is the last one. I wanted my service to still run even if there was a single widget instance on the screen.
*Also if you do not want to do all of the above and let Android take care of the Service etc...use IntentService. **
我认为 stopservice 正在调用服务本身的 onDestroy 。
它适用于我,服务计时器中的以下代码
是我在 _startService void 中启动的计时器
I think the stopservice is calling onDestroy in the Service itselfs.
It works for me with the following code in the Service
timer ist the timer which i am starting in the _startService void