The following code works well, but I think it is too complex.
SmsBroadcastReceiver.java
public class SmsBroadcastReceiver extends BroadcastReceiver{
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
public SmsBroadcastReceiver(){
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null && ACTION.compareToIgnoreCase(intent.getAction()) == 0) {
PublicPar.myContext=context;
Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] messages = new SmsMessage[pduArray.length];
for (int i = 0; i < pduArray.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]);
MSms myMSms=new MSms();
Intent msgIntent = new Intent(context,SmsInternetServer.class);
HandleSMS.SetIntentOrGetFromIntent(msgIntent, myMSms, true);
context.startService(msgIntent);
}
}
}
}
SmsInternetServer.java
public class SmsInternetServer extends IntentService {
public SmsInternetServer() {
super("SmsInternetServer");
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
HandleSMS.HandleReceivedSMS(intent);
}
}
so I merge the two class in two java file into one, is it OK? and is there more simple way to simplify code? such as anonymous class.
SmsBroadcastReceiver.java
public class SmsBroadcastReceiver extends BroadcastReceiver{
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
public SmsBroadcastReceiver(){
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null && ACTION.compareToIgnoreCase(intent.getAction()) == 0) {
PublicPar.myContext=context;
Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] messages = new SmsMessage[pduArray.length];
for (int i = 0; i < pduArray.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]);
MSms myMSms=new MSms();
Intent msgIntent = new Intent(context,SmsInternetServer.class);
HandleSMS.SetIntentOrGetFromIntent(msgIntent, myMSms, true);
context.startService(msgIntent);
}
}
}
//inner class
class SmsInternetServer extends IntentService {
public SmsInternetServer() {
super("SmsInternetServer");
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
HandleSMS.HandleReceivedSMS(intent);
}
}
}
You can define as many class as you want in one java file .only restriction is you can have a single public class per file.
In your case also you could have defined SMSInternet server outside the SmsBroadcastReceiver . There is no need to define it as inner class
Related
I've got a BroadcastReceiver which checks if Internet connection is available then it starts a service which retrieves an ArrayList from the DB:
public class NetworkWatcher extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
Intent retrieveVehicleList = new Intent(context, RetrieveVehicleListService.class);
if (info != null)
{
if (info.isConnected())
{
context.startService(retrieveVehicleList);
}
else
{
context.stopService(retrieveVehicleList);
}
}
}
}
public class RetrieveVehicleListService extends IntentService
{
private static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder builder;
private ArrayList<Vehicle> vehicles;
private void parseVehiclesFromMap(ArrayList vehicles)
{
for (int i = 0; i < vehicles.size(); i++)
{
final Vehicle v = new Vehicle();
HashMap vehicleMap = (HashMap) vehicles.get(i);
v.setPlate(vehicleMap.get("plate").toString());
v.setKm(vehicleMap.get("km") == null ? null : Integer.parseInt(vehicleMap.get("km").toString()));
v.setFuelQuantity(Double.parseDouble(vehicleMap.get("fuel_quantity").toString()));
v.setEffectiveFuelEconomy(Double.parseDouble(vehicleMap.get("fuel_economy").toString()));
v.setInsuranceDate(vehicleMap.get("insurance_date") == null ? null : new LocalDate(vehicleMap.get("insurance_date").toString()));
v.setMatriculationDate(new LocalDate(vehicleMap.get("matriculation_date").toString()));
v.setLatitude(vehicleMap.get("latitude") == null ? null : Double.parseDouble(vehicleMap.get("latitude").toString()));
v.setLongitude(vehicleMap.get("longitude") == null ? null : Double.parseDouble(vehicleMap.get("longitude").toString()));
v.setFuelType(FuelType.fromInt(Integer.parseInt(vehicleMap.get("id_fuel").toString())));
this.vehicles.add(v);
}
}
private void sendRequest(int userID)
{
Response.Listener<String> listener = new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
HashMap json = new ObjectMapper().readValue(response, HashMap.class);
String errorCode = json.get("error_code").toString();
switch (errorCode)
{
case "0":
parseVehiclesFromMap((ArrayList) json.get("vehicles"));
break;
default:
// TODO gestire
break;
}
}
catch (IOException e)
{
// TODO gestire
e.printStackTrace();
}
}
};
VehicleListRequest request = new VehicleListRequest(String.valueOf(userID), listener, null);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
#Override
protected void onHandleIntent(Intent intent)
{
SharedPreferences sp = getSharedPreferences(getString(clyky.cartracker.R.string.sharedPreferencesName), Context.MODE_PRIVATE);
int userID = sp.getInt("id_user", SplashActivity.DEFAULT_USER_ID);
if (userID != SplashActivity.DEFAULT_USER_ID)
{
sendRequest(userID);
}
}
public RetrieveVehicleListService()
{
super("RetrieveVehicleList");
vehicles = new ArrayList<>();
}
}
I want my MainActivity gets that ArrayList from RetrieveVehicleListService when the activity is started. How could I do that?
Thanks in advance.
Use LocalBroadcast reciever to send data from service to activity. Add following code to your activty
private BroadcastReceiver BReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
//put here whaterver you want your activity to do with the intent received
ArrayList<String> arrayList=intent.getStringArrayListExtra("arrayList");
}
};
protected void onResume(){
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(bReceiver, new IntentFilter("message"));
}
protected void onPause (){
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(bReceiver);
}
and use following method to send broadcast from service
private void sendBroadcast (boolean success){
Intent intent = new Intent ("message"); //put the same message as in the filter you used in the activity when registering the receiver
intent.putExtra("success", success);
intent.putStringArrayListExtra("arrayList", arrayList);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
Use Local Broadcast Receiver :
send broadcast using below code
Intent intent = new Intent("YourAction");
Bundle bundle = new Bundle();
bundle .putSerializable("ARRAYLIST",(Serializable)vehicles);
intent.putExtra("BUNDLE",bundle);
intent.putExtras(intent)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
And receive broadcast in your activity:
private MyBroadcastReceiver myReceiver;
#Override
public void onResume(){
myReceiver = new MyReceiver();
final IntentFilter intentFilter = new IntentFilter("YourAction");
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
}
#Override
public void onPause(){
if(myReceiver != null)
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
myReceiver = null;
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Here you have the received broadcast
// And if you added extras to the intent get them here too
// this needs some null checks
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Object> object = (ArrayList<Object>)args.getSerializable("ARRAYLIST");
}
}
i m trying to read OTP from message, but i cant auto read it.please tell me what i did wrong, here is my code.i m using marshmallow. thank you.
here is my SmsReceiver class:
public class SmsReceiver extends BroadcastReceiver {
private static SmsListener mListener;
#Override
public void onReceive(Context context, Intent intent) {
Bundle data = intent.getExtras();
Object[] pdus = (Object[]) data.get("pdus");
for(int i=0;i<pdus.length;i++){
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = smsMessage.getDisplayOriginatingAddress();
//You must check here if the sender is your provider and not another one with same text.
String messageBody = smsMessage.getMessageBody();
//Pass on the text to our listener.
mListener.messageReceived(messageBody);
}
}
public static void bindListener(SmsListener listener) {
mListener = listener;
}}
here is interface
public interface SmsListener {
public void messageReceived(String messageText);
}
and this is my activity
public class MyOTP extends BaseActivity implements View.OnClickListener {
EditText txtotp;
Button btnSubmitOtp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_otp);
txtotp = (EditText) findViewById(R.id.txtOtp);
btnSubmitOtp = (Button) findViewById(R.id.btnSubmit);
btnSubmitOtp.setOnClickListener(this);
SmsReceiver.bindListener(new SmsListener() {
#Override
public void messageReceived(String messageText) {
Log.d("Text",messageText);
Toast.makeText(MyOTP.this,"Message: "+messageText,Toast.LENGTH_LONG).show();
}
});
}
}
Here is my working Broadcast receiver class which will read digits from message body & broadcast with OTP code to related class
You need to add these permissions in menifest file
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission-sdk-23 android:name="android.permission.READ_SMS" />
<uses-permission-sdk-23 android:name="android.permission.RECEIVE_SMS" />
Here is my receiver class
public class SmsListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null) {
//---retrieve the SMS message received---
try {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
if (Build.VERSION.SDK_INT <= 22) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
} else {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i], bundle.getString("format"));
}
msg_from = msgs[i].getOriginatingAddress();
if (msg_from.contains("PINSMS")) {
String msgBody = msgs[i].getMessageBody();
//String pinNo = msgBody.substring(msgBody.indexOf('"') + 1, msgBody.indexOf('"', msgBody.indexOf('"') + 2));
String pinNo = msgBody.replaceAll("[^0-9]", "");
Log.d("SMS", "From -" + msg_from + " : Body- " + msgBody);
//CodeVerification.insertCode(pinNo);
// Broadcast to Auto read Code sms
final String DISPLAY_MESSAGE_ACTION = context.getPackageName() + ".CodeSmsReceived";
Intent intentCodeSms = new Intent(DISPLAY_MESSAGE_ACTION);
intentCodeSms.putExtra("varificationCode", pinNo);
context.sendBroadcast(intentCodeSms);
}
}
} catch (Exception e) {
Log.d("Exception caught", e.getMessage());
}
}
}
}
}
I have registered this receiver in my class programmatic because i know OTP sms will come after my submit button click & i unregister it after OTP read as i dont want to trigger this receiver for every SMS by registering it in menifest.
SmsListener smsListener = new SmsListener();
try {
unregisterReceiver(smsListener);
} catch (Exception e) {
}
registerReceiver(smsListener, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
EDIT
Put below receiver in your activity to get OTP code
final String DISPLAY_MESSAGE_ACTION = activity.getPackageName() + ".CodeSmsReceived";
try {
activity.unregisterReceiver(mHandleMessageReceiver);
} catch (Exception e) {
}
activity.registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
On receiving code below method will be called
/**
* Receiving Call Log Changed broadcast
*/
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.hasExtra("varificationCode")) {
String youtOTPcode = intent.getStringExtra("varificationCode"));
}
}
};
For Marshmallow you have to ask users to give permissions. It's not given by default even if you declare it in manifest. You need to add code to get runtime permission for marshmallow devices.
For now just for checking you can go to settings --> Apps --> go to your in the list --> click on permissions --> Enable SMS permission. Then restart your app and check is it working.
Hope it will help you.
Change MyOtpActivity to
public class MyOTP extends BaseActivity{
EditText txtotp;
Button btnSubmitOtp;
private UpdateOTPReceiver mUpdateOtpReceiver;
private SMSReceiver mSmsReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_otp);
txtotp = (EditText) findViewById(R.id.txtOtp);
btnSubmitOtp = (Button) findViewById(R.id.btnSubmit);
btnSubmitOtp.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
mUpdateOtpReceiver = new UpdateOTPReceiver();
registerReceiver(mUpdateOtpReceiver, new IntentFilter("UPDATE_OTP"));
registerSMSReceiver();
}
private void registerSMSReceiver() {
mSmsReceiver = new SMSReceiver();
registerReceiver(mSmsReceiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}
private class UpdateOTPReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
String msg = intent.getStringExtra("msg");
Toast.makeText(MyOTP.this,"Message: "+msg,Toast.LENGTH_LONG).show();
}
}
}
}
}
In SmsReceiver
Public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle data = intent.getExtras();
Object[] pdus = (Object[]) data.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = smsMessage.getDisplayOriginatingAddress();
//ToDo check your sender
String messageBody = smsMessage.getDisplayMessageBody();
Intent updateTokenIntent = new Intent("UPDATE_OTP");
updateTokenIntent.putExtra("msg", getVerificationCode(messageBody));
context.sendBroadcast(updateTokenIntent);
}
}
private String getVerificationCode(String message) {
if (message == null) {
return null;
}
int index = message.indexOf("is");
int index_last_length = message.indexOf(".");
if (index != -1) {
int start = index + 3;
return message.substring(start, index_last_length);
}
return null;
}
}
You Cannot Read a SMS having OTP word in it through broadcast receiver because of google policy.
You Cannot Read a SMS having OTP word in it through broadcast receiver because of google policy is well said by Ridhika....
OTP messages can only be read by app that has its HashCode in the message body.
I want to pass data from the onReceive() in my BroadcastReceiverListener class to the onNewIntent() emthod in the MainActivity by using of Parcelable interface. How can I get that to work? And how can I get the data in the onNewIntent()?
I appreciate any help.
BroadcastReceiverListener class:
public class BroadcastReceiverListener extends BroadcastReceiver implements
Parcelable {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
final List<ScanResult> results = wifiManager.getScanResults();
if (results != null) {
ArrayList<ScanResult> updatedResults = new ArrayList<ScanResult>();
for (int i = 0; i < results.size(); i++) {
String ssid = results.get(i).SSID;
if (ssid.startsWith("KD")) {
updatedResults.add(results.get(i));
}
}
Intent updateIntenet = new Intent(context, MainActivity.class);
updateIntenet.putParcelableArrayListExtra("broadcast_event",
updatedResults);
context.startActivity(updateIntenet);
}
}
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
}
This method is in the MainActiity:
#Override
protected void onNewIntent(Intent intent) {
String intentResult = intent.getStringExtra("broadcast_event");
if (intentResult != null) {
List<ScanResult> results = getParcelableArrayList(intentResult);
String a = deliverBestAccessPoint(results);
textWifi.setText(a.toString());
} else {
textWifi.setText("No route is available.");
}
}
You should call getParcelableArrayListExtra on the intent you receive:
List<ScanResult> results = intent.getParcelableArrayListExtra("broadcast_event");
I want to receive sms and show Dialog.
How can i do that?
SmsReceiver:
public class SMSReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
String num = "";
if (bundle != null)
{
//---retrieve the SMS message received---
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]);
if (i==0) {
//---get the sender address/phone number---
num += msgs[i].getOriginatingAddress();
}
//---get the message body---
str += msgs[i].getMessageBody().toString();
}
//---display the new SMS message---
if (num.equals("+XXXXXXXXX")){
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
//What to do here?
}
//---prevent this SMS message from being broadcasted---
abortBroadcast();
Log.d("SMSReceiver", str);
}
}
}
My Main:
public class MainActivity extends FragmentActivity implements YesNoDialogListener {
GoogleMap googleMap;
Marker marker = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}
else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// get my actual position and display a blue dot
googleMap.setMyLocationEnabled(true);
Location myLocation = googleMap.getMyLocation();
if( myLocation != null ){
Toast.makeText(this, "Latitude: " + myLocation.getLatitude() + "\nLongitude: " + myLocation.getLongitude(), Toast.LENGTH_SHORT).show();
}
if( myLocation == null ){
Toast.makeText(this, "Chujnia", Toast.LENGTH_SHORT).show();
}
}
}
//==Dialog yes/no
public void btnShowYesNoDialog(View view) {
showYesNoDialog();
}
public void showYesNoDialog() {
FragmentManager fragmentManager = getSupportFragmentManager();
YesNoDialogFragment yesnoDialog = new YesNoDialogFragment();
yesnoDialog.setCancelable(false);
yesnoDialog.setDialogTitle("New accident");
yesnoDialog.show(fragmentManager, "yes/no dialog");
}
#Override
public void onFinishYesNoDialog(boolean state) {
Toast.makeText(this, "Returned from dialog: " + state,
Toast.LENGTH_SHORT).show();
SmsManager sms = SmsManager.getDefault();
if (state == true){
sms.sendTextMessage("+XXXXXX", null, "OK", null, null);
}
else{
sms.sendTextMessage("+XXXXXXX", null, "No", null, null);
}
}
}
How to execute btnShowYesNoDialog from SmsReceive?
Now it works only when I press the button which is connected to btnShowYesNoDialog?
If you need to receive sms during application opened (not as service), you can put Receiver in Main activity as mentioned in hewwcn answer.
For example:
public class MainActivity extends Activity {
/*
* Variables for BroadcastReceiver
*/
boolean isRegistered = false; // check if BroadcastReceiver registered
private IntentFilter filterSmsReceived = new IntentFilter(
"android.provider.Telephony.SMS_RECEIVED");
/**
* Create BroadcastReceiver
*/
private BroadcastReceiver smsReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
"android.provider.Telephony.SMS_RECEIVED")) {
/* get the SMS message passed in */
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String msgFrom = null;
String msgBody = null;
if (bundle != null) {
/* retrieve the SMS message received */
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]);
msgFrom = msgs[i].getOriginatingAddress();
msgBody = msgs[i].getMessageBody();
}
/*
* TODO Show dialog
*/
} catch (Exception e) {
// Log.d("Exception caught",e.getMessage());
}
}
}
}
};
/**
* Button - register BroadcastReceiver when clicked (or put it to onCreate)
*/
public void onButtonClicked(View v) {
this.registerReceiver(smsReceiver, filterSmsReceived);
isRegistered = true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onPause() {
/*
* Unregister BroadcastReceiver
*/
if (isRegistered) {
this.unregisterReceiver(smsReceiver);
isRegistered = false;
}
super.onPause();
}
#Override
protected void onDestroy() {
/*
* Unregister BroadcastReceiver
*/
if (isRegistered) {
this.unregisterReceiver(smsReceiver);
isRegistered = false;
}
super.onDestroy();
}
}
you can put SMSReceiver into MainActivity :
public class MainActivity extends FragmentActivity implements YesNoDialogListener {
private BroadcastReceiver SMSReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//TODO
}
};
}
Remember to register the broadcast receiver
update.
sorry.I didnt read your code carefully.I think you need android application.
public class MyApplication extends Application{
private static MyApplication instance;
public static MyApplication getInstance(){
return instance;
}
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
androidmanifest:
<application
android:name="xx.xx.MyApplication">
then you can show Toast or dialog in onReceive method:
Toast.makeText(MyApplication.getInstance(), "ok", Toast.LENGTH_LONG).show();
I want to delete the messages from a specific mobile no. in android phone.
For this,I am using the following code..
The Problem in this code is that it is deleting all the conversations from the phone..
So help me please to resolve this problem.
THANX IN ADVANCE...
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
// String specificPhoneNumber = "+91" ;
super.onCreate(savedInstanceState);
long V;
MainActivity thr = new MainActivity();
V =thr.getThreadId(thr);
Uri thread = Uri.parse("content://sms/inbox/8767564523" + V);
getContentResolver().delete(thread, null, null);
}
private long getThreadId(Context context)
{
long threadId = 0;
String SMS_READ_COLUMN = "read";
String WHERE_CONDITION = SMS_READ_COLUMN + " = 0";
String SORT_ORDER = "date DESC";
int count = 0;
Uri uri1 = Uri.parse("content://sms/inbox/");
Cursor cursor = context.getContentResolver().query(uri1,new String[] { "_id", "thread_id", "address", "person", "date", "body" },WHERE_CONDITION,null,SORT_ORDER);
if (cursor != null) {
try {
count = cursor.getCount();
if (count > 0) {
cursor.moveToFirst();
threadId = cursor.getLong(1);
}
} finally {
cursor.close();
}
}
return threadId;
}
}
Oh...Got it ..It is Working 100%,
public void onReceive(Context context, Intent intent) {
//Bundle bundle = intent.getExtras();
// if(null == bundle)
// return;
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
try {
// Java reflection to gain access to TelephonyManager's
// ITelephony getter
tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
Log.v("1","BYE BYE BYE" );
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
// com.android.internal.telephony.ITelephony
telephonyService = (ITelephony) m.invoke(tm);
Bundle b = intent.getExtras();
incommingNumber = b.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Toast.makeText(context, incommingNumber, Toast.LENGTH_LONG).show();
Log.v("2","BYE BYE BYE" );
for(int i=0;i<1;i++)
{
if ( incommingNumber.equals(BINO[i]) )
{
}
else{
Toast.makeText(context,incommingNumber, Toast.LENGTH_LONG).show();
telephonyService = (ITelephony) m.invoke(tm);
//telephonyService.silenceRinger();
telephonyService.endCall();
Log.v("3","BYE BYE BYE" );
//telephonyService.answerRingingCall();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};//BroadcastReceiver
/**
* Broadcast receiver to detect the outgoing calls.
*/
public class OutgoingReceiver extends BroadcastReceiver
{
public OutgoingReceiver() {
}
#Override
public void onReceive(Context context, Intent intent)
{
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
// setResultData(null);
int c = (number).indexOf("YOUR NO...");
Toast.makeText(context, String.valueOf(c), Toast.LENGTH_LONG).show();
for(int i =0;i<2;i++)
{
if ((number).indexOf(BONO[i])!= -1)//||number.contentEquals("+917204302689")||number.contentEquals("07204302689"))
{
setResultData(null);
Toast.makeText(context, "This call is not allowed!", Toast.LENGTH_LONG).show();
}
}
}
}
public class MessageReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
//Bundle bundle = intent.getExtras();
if ( bundle != null )
{
// do you manipulation on String then if you can abort.
}
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n <messages.length; n++)
{
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
for(int i=0;i<1;i++)
{
if(MINO[i].equalsIgnoreCase(smsMessage[0].getOriginatingAddress()))
{
//abortBroadcast();
String Body=smsMessage[0].getMessageBody();
if (Body.startsWith("START"))
{
Toast toast4 = Toast.makeText(context,"There is START ", Toast.LENGTH_LONG);toast4.show();
abortBroadcast();
}
}
else
{
abortBroadcast();
}
}
// show first message
Toast toast1 = Toast.makeText(context,"Received SMS: " + smsMessage[0].getOriginatingAddress()+ "\nBody: "+smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
toast1.show();
}
};//BroadcastReceiver
String incommingNumber;
private Context ctx;
private TelephonyManager tm;
//private CallStateListener callStateListener;
ITelephony telephonyService;
private OutgoingReceiver outgoingReceiver;
private IncomingReceiver incomingReceiver;
private MessageReceiver messageReceiver;
public CallHelper(Context ctx)
{
this.ctx = ctx;
//callStateListener = new CallStateListener();
outgoingReceiver = new OutgoingReceiver();
incomingReceiver = new IncomingReceiver();
messageReceiver = new MessageReceiver();
}
/**
* Start calls detection.
*/
public void start() {
//tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
//tm.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
ctx.registerReceiver(outgoingReceiver, intentFilter);
IntentFilter filter= new IntentFilter("android.intent.action.PHONE_STATE");
ctx.registerReceiver(incomingReceiver, filter);
IntentFilter filter1= new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
ctx.registerReceiver(messageReceiver, filter1);
}
/**
* Stop calls detection.
*/
public void stop()
{
//tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE);
ctx.unregisterReceiver(outgoingReceiver);
ctx.unregisterReceiver(incomingReceiver);
ctx.unregisterReceiver(messageReceiver);
}
}