I know this is a similar question to mine. https://stackoverflow.com/a/22511290/2208342 but i have read that the solution to that question will become obsolete as Android are taking away that code.
qoute below taken from https://stackoverflow.com/a/5921190/2208342
I'd discourage the use of this solution. For
Android L
they're removingActivityManager.getRecentTasks()
and it had the same note in the documentation. So be warned!
I have also heard that this solution does not work on android kitkat.
BroadCastReceiver Class
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
public IncomingSms(){}
@Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
Intent intent1 = new Intent(context, CallDetectService.class);
if (context.stopService(intent1)) {
Toast.makeText(context,"if context",Toast.LENGTH_LONG).show();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
String sms = "TEST";
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(senderNum, null, sms, null, null);
Toast.makeText(context, "Sms sent Succesfully", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Sms Failed", Toast.LENGTH_LONG).show();
}
Log.i("SmsReciver", "senderNum: " + senderNum + "; message: " + message);
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "senderNum: " + senderNum + ", message: " + message, duration);
toast.show();
} // End For loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReciever", "Exeption smsReceiver" + e);
}
}
else{
Toast.makeText(context,"else context",Toast.LENGTH_LONG).show();
}
}
}
Service Class
public class CallDetectService extends Service {
private CallHelper callHelper;
public CallDetectService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
callHelper = new CallHelper(this);
int res = super.onStartCommand(intent, flags, startId);
callHelper.start();
Toast.makeText(getApplicationContext(), "Starting Service", Toast.LENGTH_LONG).show();
return res;
}
@Override
public void onDestroy(){
super.onDestroy();
callHelper.stop();
//Toast.makeText(getApplicationContext(),"Stop Service",Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind (Intent intent) {
return null;
}
}
in my MainActivity i have this piece of code which is exactly what i want to in my broadcast receiver.
Intent intent = new Intent(this,CallDetectService.class);
if (stopService(intent)){