You can Create a service and let it run on the foreground to avoid the random killing by the system
private void startServiceAsForeground() {
Intent intent = new Intent(MyServiceService.this, targetActivity.class);
startForeground(ONGOING_NITIFICATION_ID, creatOngoingNotificationObject(getString(R.string.ongoing_message_ok), intent));
}
private void updateServiceForegroundMessage(String message, Intent intent) {
startForeground(ONGOING_NITIFICATION_ID, creatAntiDistractionOngoingNotificationObject(message, intent));
}
private android.app.Notification creatOngoingNotificationObject(String messageBody, Intent intent) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MyServiceService.this).setSmallIcon(R.drawable.ic_launcher_gray)
.setContentTitle(getString(R.string.app_name)).setAutoCancel(false).setOngoing(true).setContentText(messageBody);
// Intent intent = new Intent(MainService.this, intentClass );
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pIntent = PendingIntent.getActivity(MyServiceService.this, 0, intent, 0);
mBuilder.setContentIntent(pIntent);
return mBuilder.build();
}
And insert your code to the service and then you are guaranteed to intercept any incomming/outgoing message even if your application is not on the foreground because your service will be running all the time and the user will be aware of it .