Reputation: 1
I have some logic that I need to execute when the user is getting any SMS. My Broadcast receiver is working fine when the app is running but if I am killing my then it is not working as expected.
Can someone help me with this? I have tried all the possible approaches which are present on the Internet but still nothing is working.
Thank you so much in advance.
My broadcast receiver class:
public class EveryDay_SMSListener extends BroadcastReceiver {
private SharedPreferences preferences;
String msgBody ="";
String msg_from;
EveryDay_DataBase mydb;
@Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, EveryDay_Service.class);
context.startService(background);
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
enter code here
if (bundle != null){
try{
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]);
msgBody = msgBody+(msgs[i].getMessageBody()).toString();
msg_from = msgs[i].getOriginatingAddress();
}
}catch(Exception e){
}
}
}
}
}
Upvotes: 0
Views: 644
Reputation: 3987
You said registering receiver in manifest did not work for you thus the only remaining option is:
onCreate
of
it (do NOT register sms receiver in manifest).jobscheduler
that starts your service every (n) secondsit is the last solution but if you wont be lucky between app kill and next jobscheduler work you may lost sms so you may want to make (n) small enough.
Better solution is to have read sms permission and every time your activity starts read all sms from android inbox and see if you lost any sms.
Upvotes: 0
Reputation: 376
In recent versions of Android, system does not launch app when app is dead and broadcast gets emitted (for most of broadcast flags).
An approach for making this work you should use Foreground Services, some links that may help you implement it:
Take care, some manufacturers even close these services for battery optimizations like Huawei, Samsung,... . So you should add brand specific codes to make user disallow battery optimization and automatic close of services for your app.
Upvotes: 1