I plan to have a heads up notification that has two Actions: one to Approve a login request and one to Decline a login request. By clicking on either of these actions I wish to fire off a HTTP request to my server and most importantly do not want to start a new Activity or have the user redirected to my app at all.
Context context = getBaseContext();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.notificationicon)
.setContentTitle(notificationTitle)
.setContentText("Access Request for " + appName + " : " + otp)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.addAction(R.drawable.ic_tick, "Approve", someApproveIntent? );
Here is my notification builder and after looking around it seems that the addAction method is looking for a new/pendingIntent, which is confusing me as I cannot find any examples online where Intents do not lead to new Activities being fired off.
How would I implement some code (a method maybe) rather then starting a new Activity on each of my Actions?
Android PendingIntent In other words, PendingIntent lets us pass a future Intent to another application and allow that application to execute that Intent as if it had the same permissions as our application, whether or not our application is still around when the Intent is eventually invoked.
If you don't want to start an activity you can also wrap a BroadcastReceiver
or a Service
directly in a PendingIntent
.
Your notification actions will start a service directly.
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)...
Intent iAction1 = new Intent(context, MyService.class);
iAction1.setAction(MyService.ACTION1);
PendingIntent piAction1 = PendingIntent.getService(context, 0, iAction1, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(iconAction1, titleAction1, piAction1);
// Similar for action 2.
IntentServices run in a row one after another. They do the work on a worker thread.
public class MyService extends IntentService {
public static final String ACTION1 = "ACTION1";
public static final String ACTION2 = "ACTION2";
@Override
public void onHandleIntent(Intent intent) {
final String action = intent.getAction();
if (ACTION1.equals(action)) {
// do stuff...
} else if (ACTION2.equals(action)) {
// do some other stuff...
} else {
throw new IllegalArgumentException("Unsupported action: " + action);
}
}
}
Don't forget to register the service in manifest.
<manifest>
<application>
<service
android:name="path.to.MyService"
android:exported="false"/>
</application>
</manifest>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With