Correct way of handling (pending) intents in AppWidgets - android

I have a question regarding AppWidget intent handling. I have a widget which is clickable, and on click I want to send an intent to the AppWidgetProvider itself for further processing.
The problem: I receive the intents initially in onReceive(), but after a while (not sure what causes it), onReceive() is no longer called.
I have the following code, all in MyWidgetProvider extends AppWidgetProvider.
a) register for receiving broadcasts:
in onEnabled(...):
context.getApplicationContext().registerReceiver(this, new IntentFilter(MY_ACTION));
b) set intent to be fired on click:
in onUpdate(...)
Intent intent= new Intent(MY_ACTION);
PendingIntent pendingIntent= PendingIntent.getBroadcast(context, 0/*notusedanyway*/, intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_root, pendingIntent);
c) react to event and do something:
in onReceive(...)
if (MY_ACTION.equals(intent.getAction())
doSomething();
When I deploy + add a widget, it works fine. However, after a while - not sure what exactly causes the problem, but a phone call, for example, seems to affect it - I no longer get any notifications in onReceive().
I am completely stumped why this is the case. Can someone point out to me the correct way of doing this?
Thanks!
Tom

You should use a BroadcastReceiver registered in your AndroidManifest.xml file. When you register it in onEnable it is tied to the process. Whenever Android kills your process (for example, when a phone call is received) then your receiver no longer exists and (as you observed) no longer works.

Related

Android - Not able to start multiple activities from background

I am facing a problem.
This is the code I have in my BroadcastReceiver extender class:
#Override
public void onReceive(Context context, Intent intent) {
// other
Intent myIntent = new Intent(context, ShowMessageActivity.class);
myIntent.putExtra(Utils.SHOW_MESSAGE_OPTION, messageToDisplay);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(lockScreenMessage);
}
which starts a new activity when a broadcast is raised.
When the application is in foreground and receives a broadcast, it starts a new Activity as many times as the code executes, but it is not the case when the app is in background. In that case it starts an Activity only once, and not each time a broadcast is received. Why? Is it possible to fix that?
that very depends on what do you expect in that receiver, is it any system-side call (declared in manifest) or your own? who an when calls it, thats very important
starting Android 10 there are some restrictions for starting Activity from onReceive, check out official DOC. basically you shouldn't start any Activity from there, and when it works for you I bet it works only for few secs after PendingIntent creation. check out exceptions list under link above, possible reasons would be:
The app has an activity in the back stack of an existing task on the Recents screen.
The app has an activity that was started very recently.
The app called finish() on an activity very recently.
you may check out your code on some emulator with Android 9, all your broadcast calls should work "always"

AlarmManager and WakefullBroadcastReceiver how private are the passed Extras?

I am trying to implement some alarm scheduling by using AlarmManager. Since when a alarm is triggered, I want to use a WakefulBroadcastReceiver which starts an IntentService to do some background job.
I have some questions related to security/privacy of the parameters passed for alarm's intents.
When setting a PendingIntent for a alarm I do something like:
Intent myIntent = new Intent(context, MyReceiver.class);
myIntent.putExtra("test", "testValue");
Bundle bundle = new Bundle();
bundle.putParcelable("bundleValue", bundleTestValue2);
myIntent.putExtra("test3", bundle);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 323,
myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
My question is: how private are the values set as Extra for the pendingIntent of the alarm? Is there a chance of them getting read by some other app since is being used by Android Alarm's Manager after it is scheduled?
By having a receiver like
public class MyReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
startWakefulService(context, MyIntentService);
}
And on android manifest
<receiver
android:name=".receivers.MyReceiver"
android:exported="false"/>
<service
android:name=".MyIntentService"
android:exported="false"/>
And the service
public class MyIntentService extends IntentService {
#Override
protected void onHandleIntent(Intent intent) {
try {
//logic here
} catch{
} finaly{
MyReceiver.completeWakefulIntent(intent);
}
}
Call from within my Activity
sendBroadcast(new Intent(context, MyReceiver.class).putExtra(...);
Schedule a pending intent from an alarm
Intent myIntent = new Intent(context, MyReceiver.class);
myIntent.putExtra("test", "testValue");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 323,
myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
how exposed is this receiver to other apps? Can it react to other apps except mine? Does this rise any security possible issues?
Thank you.
Later edit:
Since the WakefullBroadcastReceiver seems the only way that guarantees that my service will get a partial wakelock, how can I make sure 100% that no other apps will be aware of my receiver and that my receiver won't get any other calls except ones made from my activity or from my set Alarm?
How would a WakefullBroadcastReceiver pattern works versus CommonsWare's WakefulIntentService ?
Later Edit:
I've finally managed to finish my implementation.
As stated before, both my WakefulBroadcastReceiver and IntentService are declared as exported="false" in my Android Manifest which from what I understand means that only my app can access them. Since the receiver is not exported, does it receive broadcasts from outside the app?
When setting an alarm I use this PendingIntent:
Intent myIntent = new Intent(context, MyReceiver.class);
myIntent.putExtra("databaseId", "1");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 323,
myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
When calling from my Activity I do:
sendBroadcast(new Intent(context, MyReceiver.class).putExtra("databaseId", "1"));
Is this enough?
Privacy considerations related to Intent extras
In general, I would say that it is an insecure practice to put sensitive data in Intent.
In theory, if Intent can only be consumed by specific application (discussed later) then only that application should be able to see its contents. However, given a vast amount of Android devices and OS versions (incl. rooted devices and custom ROMs), I wouldn't count on it.
You did not specify the kind of sensitive data you'd like to pass in Intent extras, therefore I can only give these general recommendations:
Make sure you understand the "confidentiality level" of the data in question: is it secret, or just restricted? Or, maybe, it is public (in which case no protection needed)?
Try to find another approach that doesn't involve passing sensitive data in Intent (I myself never encountered such a need).
If you absolutely must pass sensitive data in Intent extras - consider encrypting it. The encryption model should be adequate to "confidentiality level" of the data, and to potential harm which could be done if that data is being intercepted (it can go all the way up to "server side" encryption).
Privacy/security considerations related to BroadcastReceiver
In general, BroadcastReceiver is a component which receives "system wide" broadcasts. The fact that the broadcasts are "system wide" should speak by itself about the level of privacy associated with them.
That being said, there is one mechanism by which developers can restrict broadcasts' scopes: custom permissions. Usage of custom permissions allows for two "levels of control" over broadcasts:
If broadcast requires specific permission then only if BroadcastReceiver has that permission will it receive the broadcast.
If BroadcastReceiver filters the incoming broadcasts by specific permissions, then only broadcasts carrying that permission will be delivered to that receiver.
While the above points can seem similar on the first sight, these are distinct schemes that can be used separately, or combined. The first scheme associates a broadcast with a permission (and the sender of that broadcast doesn't necessarily have that permission by himself), while the second scheme filters all broadcasts by specific permission (and the receiver must have that permission).
A better approach in your case
EDIT: this COULD BE a better approach if "wakefullness" wouldn't be part of the requirements. But it is. Since there is no guarantee that Service started by AlarmManager will get a chance to acquire a wake lock - this approach is not suitable for OP's case.
Please note that broadcasts and custom permissions were designed in order to introduce "decoupling" at application level - this scheme allows for sender application to be completely agnostic of the receiving application, as long as they agree on one custom permission (well, the same scheme is employed for pre-installed public permissions as well, but you wouldn't want to guard your sensitive data with a public permission).
In your case, however, sender and receiver are the same application. In such setting you don't really need all the trouble associated with broadcasts - just construct PendingIntent that starts the required Service inside your app, and you get it all at once:
PendingIntent and the associated Intent start a specific Service in your application (by name), therefore no other application can intercept it (theoretically, remember the above discussion).
Target Service can be non-exported, therefore no other application can access it in any way.
You welcome :)

Same instance of pending intent is fired again and again, despite changing the extras manually

I have to do a task multiple times, and task is to broadcast an intent which will be intercepted by a different app. Lets say from App Sender to Receiver.
Receiving the intent in Receiver app is working fine, I have tested and guaranteed:
How I am doing this is,
I created a broadcast receiver in Sender app, with action SENDER_ACTION.
I create an intent with this action, set an extra with key frequency and value 4.
Get a PendingIntent from this and set an alarm of 10 sec, and fires this intent.
Idea is that sender app, will receive this intent, will fire the required intent to RECEIVER app, and then decreases the frequency value by 1, set it again to the intent, creates a pending intent and alarm and fires again.
So, ideally this counter of frequency should reach to 0 and process should terminate.
I can see that while setting the decreased value of frequency, it is happening (in logs), but when I receive its the same unchanged value.
I suspect that pending intent instance is kept on fired again and again.
Can some body please help me why is this happening?
If I had to guess -- which I do, since you provided no source code -- it is because you have not passed the right flags into getBroadcast() (or whatever factory method that you are using on PendingIntent to obtain the PendingIntent instance). Please bear in mind that Android caches PendingIntent objects and will reuse them, with their internal Intent extras unmodified, by default. Consider passing FLAG_UPDATE_CURRENT as the last parameter to getBroadcast().

Android long running service with alarm manager and inner broadcast receiver

I have a Service that uses a custom Connection class (extends thread) to a hardware controller. When the User prefers, I wish to maintain this connection on a permanent basis. I already have the code to handle when the Android device loses its internet connection, switches between wi-fi, etc.
In order to stay connected, the controller requires that you speak to it within every 5 minutes. I currently, within the Connection class start a thread that runs in a while(), and checks the system time and the last time it communicated, and when > 4 minutes it requests a status. For some reason, at different times the communication doesn't occur in time. i.e., occurs after 5 minutes. The Service doesn't die, as far as I can tell but the "Ping" to the controller is late. This doesn't happen when I have the phone plugged into the charger (or debugger). Additionally, the behavior is the same when I move the Service to the foreground.
Does the phone slow down it's processor when it goes to sleep?
Is there a better way?
I'm thinking it's the AlarmManger, but I'm having trouble getting it to work with an inner-class, within the Service. I tried using the API demos as a starting point, but I can't seem to figure out how to get the Broadcast receiver registered. I am trying to register the receiver programmatically, with no changes to the manifest.
public class DeviceConnectionService extends Service {
#Override
public void onCreate() {
Intent intent = new Intent(this, PingConnection.class);
intent.setAction("KEEP_CONNECTION_ALIVE");
PendingIntent sender = PendingIntent.getBroadcast(this,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
firstTime += 15*1000;
// Schedule the alarm!
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, 15*1000, sender);
// register to listen to the Alarm Manager
if (mPingConnectionReceiver == null) {
mPingConnectionReceiver = new PingConnection();
getApplicationContext().registerReceiver(mPingConnectionReceiver,
new IntentFilter("KEEP_CONNECTION_ALIVE"));
}
}
// ...
public class PingConnection extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (dBug) Log.i("PingConnection", "Pinging Controller");
// do real work here
}
}
}
Does the phone slow down it's processor when it goes to sleep?
The phone shuts down its processor when it goes to sleep. That is the definition of "sleep".
I'm thinking it's the AlarmManger, but I'm having trouble getting it to work with an inner-class, within the Service. I tried using the API demos as a starting point, but I can't seem to figure out how to get the Broadcast receiver registered. I am trying to register the receiver programatically, with no changes to the manifest.
That is an unusual approach for AlarmManager. That being said, since you declined to describe "having trouble" in any detail, it is difficult to help you.
Get rid of getApplicationContext() (you don't need it and really don't want it in this case). I would register the receiver before touching AlarmManager. Before you go to production, please choose an action name that has your package name in it (e.g., com.something.myapp.KEEP_CONNECTION_ALIVE).
Beyond that, check LogCat for warnings.
UPDATE
In your LogCat, you should have a warning from AlarmManager complaining about not being able to talk to your BroadcastReceiver.
Replace:
Intent intent = new Intent(this, PingConnection.class);
intent.setAction("KEEP_CONNECTION_ALIVE");
with:
Intent intent = new Intent("KEEP_CONNECTION_ALIVE");
and you may have better luck.
you can't register AlarmManager in a Service.
All you can do is declare it as global in the Manifest.xml.
You can start the alarm from service in this way, by declaring it in Manifest.xml
If you have a remote service and you close the launcher activity, the AlarmManager will still run, but don't forget to stop it on onDestroy() method of the service.
I've tried to register only in the Service the AlarmManager as I didn't used it for the main activity, but no success!
It didn't work as registering as a normal BroadCastReceiver.
that's how the things are, you have to declare it in Manifest.xml as global
I know it's late, but maybe it's useful for someone else.
You can register it, the problem is when the Intent tries to call it.
Instead of calling it like this:
Intent intent = new Intent(this, PingConnection.class);
Create an empty intent and add an action you are going to listen to:
Intent intent = new Intent();
intent.setAction("value you want to register");
Then create the pending intent and send the broadcast like you have it.
Create an attribute for the receiver so you can access it in the whole class and unregister if necessary (if the pendingIntent is also an attribute you can unregister any time):
private PingConnection pingConnection = new PingConnection();
Register it like this:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("the value you used before");
getApplicationContext().registerReceiver(pingConnection, filter);
Now you won't get any errors, and the class is not static, and it's an inner class.

Android - AppWidget's pending intent does not fire

I have an app widget with a Button in it's layout.
When clicking the button, an intent is fired which calls my broadcast receiver.
It works just fine, but occasionally, after using the "Clear memory" button in the Task Manager, the widget gets stuck - clicking on it does nothing. But it can still receive updates from my app, if its running.
I'm not sure if the fact that the pending intent isn't fired is the memory clearing fault, or my fault.
Anyway, here's the code:
Registering the pending intent (onUpdate method of the app widget)
Intent intent = new Intent(context, ServiceControl.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget);
views.setOnClickPendingIntent(R.id.appwidgetbutton, pendingIntent);
and then updating the widgets with the views.
Here is the decleration of the app widget provider:
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="72dp"
android:minHeight="72dp"
android:initialLayout="#layout/appwidget"
android:updatePeriodMillis="0">
</appwidget-provider>
I don't want the system to call widget updates, I only update it from my app itself.
So why does the pending intent stop firing?
Thanks in advance.
#Jong
#CommonsWare
Hi guys, I figured it out. Ofc this is an Android issue, the receiver should ALWAYS receive.
Now how to get around it? Obviously all the widgets are working, so there must have been a simple out there.
I read on SO somewhere (trying to find the guy) reminding us all that the widget class is actually extending a BroadcastReceiver.
So, you could register the widget (in the manifest) to receive the threats itself. Thus the entire system is self-contained in the class instance of AppWidgetProvider.
Now, for communicating back with the app, you can in the onReceive call any static class of your app, and LocalBroadcastManager won't fail you if the app is active. If it's not active, your buttons should be starting activities anyway!
Should you want the code, I can detail it.

Categories

Resources