You need to detect whether your app is currently in background or foreground.
Approach :
- Add a
BroadcastReceiver
to listen the incoming message
- Check whether your app is in foreground or not
- If it is in background, show the dialog box
Code Snippet :
Implement custom Application class which changes the application status
public class MyApplication extends Application {
public static boolean isActivityVisible() {
return activityVisible;
}
public static void activityResumed() {
activityVisible = true;
}
public static void activityPaused() {
activityVisible = false;
}
private static boolean activityVisible;
}
Add onPause
and onResume
to every Activity in the project to change the application status :
@Override
protected void onResume() {
super.onResume();
MyApplication.activityResumed();
}
@Override
protected void onPause() {
super.onPause();
MyApplication.activityPaused();
}
Add the permission and register the receiver in manifest :
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<receiver android:name=".SMSBroadcastReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
SMSBroadcastReceiver :
public class SMSBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "no message received";
if(bundle != null){
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length;i++){
msgs[i]= SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from Phone No: " +msgs[i].getOriginatingAddress();
str +="\n"+"Message is: ";
str += msgs[i].getMessageBody().toString();
str +="\n";
}
Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); //contact number and the message
// Now as soon as you get the message check whether your application is running or not and show the dialog
if(!MyAppliction.isActivityVisible())
{
// code to show a dialog box
}
}
}}