开发者

Android - App widget can not use pending intents when the application restarts

My application has, apart from its activities, a service and an app widget.

I wanted that clicking the widgets results in a piece of code executing, a piece which will enable/disable the app's service. So, Clicking on the app widget launches a pending intent, built up this way:

Intent intent = new Intent(ACTION_ENABLE_DISABLE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

(ACTION_ENABLE_DISABLE is defined by me, of course.)

And in the manifest, I specify this action in the intent filter.

Then, I overrided the onReceive method, and if the intent's action is ACTION_ENABLE_DISABLE, I execute that piece of code which enables/disables the service. If its not, I call the super.onReceive, so normal app widgets broadcasts will get done.

So far so good! the widget works fine.

But, lets say I created it when my app's PID was X. Then, the user left my activities and they are destroyed; So as the service - lets say the user closed it. So my process hosts no activities nor services - it is destroyed / being exited from the task manager, both cases are relevant. The next time it is created, it has a different PID, and now, clicking on the app widget DOES NOTHING.

The app widget can still be updated manually, for example, from the activity. But clicking on it doesn't lead to:

    开发者_JAVA技巧
  1. The ACTION_ENABLE_DISABLE broadcast being sent. OR
  2. My app widget receiving this broadcast.

One of the following above happens - as when I look in the logcat, and the messages I log with Log.d in the 'onReceive' methods of the widget DOES NOT appear.

Why is that? Do I need to specify anything special when sending the broadcast, or anything in the receiver declaration in the manifest?

And speaking of which, is there any better that can be used to execute your own code when a view in an app widget is being click (Rather than my method).

Thank you very much!


I met the same problem these days. I tested my app on several devices, some devices had this problem and some didn't. Then I found that if you kill the widget's process (the first one, X) in task manager, then next time you create the widget and it works normally. So here is my solution. Add the following code in your onDisable() function.

int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);

This will kill itself when you delete the widget. So the next time you create it, it will works normally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜