Limiting broadcasts to your app using private permissions
Now, use your permission by defining a corresponding constant in code and then passing it into your
sendBroadcast(...) call.
Listing 29.10 Sending with a permission (PollService.java)
public class PollService extends IntentService {
...
public static final String ACTION_SHOW_NOTIFICATION =
"com.bignerdranch.android.photogallery.SHOW_NOTIFICATION";
public static final String PERM_PRIVATE =
"com.bignerdranch.android.photogallery.PRIVATE";
public static Intent newIntent(Context context) {
return new Intent(context, PollService.class);
}
...
@Override
protected void onHandleIntent(Intent intent) {
...
String resultId = items.get(0).getId();
if (resultId.equals(lastResultId)) {
Log.i(TAG, "Got an old result: " + resultId);
} else {
...
notificationManager.notify(0, notification);
sendBroadcast(new Intent(ACTION_SHOW_NOTIFICATION), PERM_PRIVATE);
}
QueryPreferences.setLastResultId(this, resultId);
}
...
}
To use your permission, you pass it as a parameter to sendBroadcast(...). Using the permission here
ensures that any application must use that same permission to receive the intent you are sending.
What about your broadcast receiver? Someone could create a broadcast intent to trigger it. You can fix
that by passing in your permission in registerReceiver(...), too.
Listing 29.11 Setting permissions on a broadcast receiver
(VisibleFragment.java)
public abstract class VisibleFragment extends Fragment {
...
@Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(PollService.ACTION_SHOW_NOTIFICATION);
getActivity().registerReceiver(mOnShowNotification, filter,
PollService.PERM_PRIVATE, null);
}
...
}
Now, your app is the only app that can trigger that receiver.