I have an app that can read SMS messages and notify through a notification
, but I want to do this without starting activity
and just displaying a notification.
This is my BroadcastReceiver
code :
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msg = null ;
String msgStr = "";
if ( bundle != null ){
Object[] pdus = (Object[]) bundle.get ("pdus");
msg = new SmsMessage [pdus.length] ;
for( int i = 0; i<msg.length; i++){
msg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
msgStr = msg[i].getDisplayOriginatingAddress();
}
Intent smsIntent =new Intent(context,MainActivity.class);
smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsIntent.putExtra("msgStr",msgStr);
context.startActivity(smsIntent);
}
}
and this my MainActivity
code:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent sms_intent = getIntent();
Bundle b = sms_intent.getExtras();
if( b != null ){
notificationCall(b.getString("smsStr"),"message");
}
}
public void notificationCall(String title , String message){
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(title+"\n")
.setContentText(message);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,notificationBuilder.build());
}
}