Perfom an action on getting specific text in SMS in Android - android

I am trying to figure out how do I read incoming SMS messages in Android and perform a specific task, say ring an alarm, when a SMS with the text 'RingAlarm' comes in.
I figure out using the BroadcastReciever class to read the SMS, but how do I perform specific action when a message with a pre-defined text arrives. Can anyone guide me which class and/or method do I need to use for that and how?
public class IncomingSms extends BroadcastReceiver {
String key = MainActivity.keyword; //Keyword is a variable in MainActivity.
//I guess, my mistake is in accessing this variable in the IncomingSms class.
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String sms = null;
String str = "";
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]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
sms = msgs[i].getMessageBody().toString();
}
//---display the new SMS message---
//Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
//---compare received message with keyword
if(sms==key)
{
Toast toast = Toast.makeText(context, "Keyword Recieved", Toast.LENGTH_LONG);
toast.show();
}
}
}
Thanks in advance!

This is my simple module to solve your problem.
Let's assume that keyword is "RING".
MyReceiver : is a class file which is used to detect the keyword "RING" and going to start RingActivity.
RingActivity : is going to ring your device no matter if it is in Silent Mode or Vibrate Mode.
MyReceiver
public class MyReceiver extends BroadcastReceiver
{
final SmsManager sms = SmsManager.getDefault();
#Override
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
{
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
try
{
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]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
String replyPhone = msgs[0].getOriginatingAddress();
String request = msgs[0].getMessageBody().toString();
if(request.equals("RING"))
{
this.abortBroadcast();
Intent i = new Intent(context, RingActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("num", replyPhone);
i.putExtra("msg", request);
context.startActivity(i);
}
}
}
catch (Exception e)
{
Log.e("MyReceiver", "Exception smsReceiver" +e);
}
}//close if
}//close onReceive();
}
RingActivity
public class RingActivity extends Activity {
final Context context = this;
MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
String num = extras.getString("num");
String msg = extras.getString("msg");
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "I AM At Reciver\nsenderNum: "+num+", message: " + msg, duration);
toast.show();
SmsManager smsManager = SmsManager.getDefault();
if(IsRingerSilent() || IsVibrate())
{
smsManager.sendTextMessage(num, null, "Device turned to ringing mode.. && It's Ringing..", null, null);
AudioManager audioManager= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
mp.setLooping(true);
try
{
AssetFileDescriptor afd;
afd = getAssets().openFd("fire_siren.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
smsManager.sendTextMessage(num, null, "Device Ringing...", null, null);
AudioManager audioManager= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
mp.setLooping(true);
try
{
AssetFileDescriptor afd;
afd = getAssets().openFd("fire_siren.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// Setting Dialog Title
alertDialogBuilder.setTitle("Device Ringing");
// Setting Dialog Message
alertDialogBuilder.setMessage("Sender : "+num+"\n"+"Message : "+msg);
alertDialogBuilder.setNegativeButton("Dialog Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
if(mp.isPlaying())
{
mp.setLooping(false);
mp.stop();
}
dialog.cancel();
finish();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
//show dialog
alertDialog.show();
}
private boolean IsVibrate()
{
AudioManager audioManager = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
if(audioManager.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE )
{
return true;
}
else
{
return false;
}
}
private boolean IsRingerSilent()
{
AudioManager audioManager = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
if(audioManager.getRingerMode()==AudioManager.RINGER_MODE_SILENT )
{
return true;
}
else
{
return false;
}
}
public boolean onKeyDown(int keycode, KeyEvent ke)
{
if(keycode==KeyEvent.KEYCODE_BACK)
{
if(mp.isPlaying())
{
mp.setLooping(false);
mp.stop();
}
finish();
}
return true;
}
}

Related

How to send my location as reply when I receive a message through Broadcast Receiver?

I need to send my current Latitude and Longitude as reply to a message received through broadcast receiver.
So far i have completed the broadcast receiver and a plain text reply.Now I need to add my location to it.
Please help me with this.
This is my BroadcastReceiver class
public class SmsBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "SmsBroadcastReceiver";
private Listener listener;
public SmsBroadcastReceiver() {
}
#SuppressLint("MissingPermission")
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
String smsSender = "";
String smsBody = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
smsSender = smsMessage.getDisplayOriginatingAddress();
smsBody += smsMessage.getMessageBody();
}
} else {
Bundle smsBundle = intent.getExtras();
if (smsBundle != null) {
Object[] pdus = (Object[]) smsBundle.get("pdus");
if (pdus == null) {
// Display some error to the user
Log.e(TAG, "SmsBundle had no pdus key");
return;
}
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
smsBody += messages[i].getMessageBody();
}
smsSender = messages[0].getOriginatingAddress();
}
}
if (smsBody.startsWith("Lost")) {
if (listener != null) {
listener.onTextReceived(smsBody);
Log.e(TAG, "SMS RECEIVED");
}
Toast.makeText(context, smsBody, Toast.LENGTH_SHORT).show();
SmsManager.getDefault().sendTextMessage(smsSender, null, "Your Phone is at latitude,longitude ", null, null);
}
}
}
void setListener(Listener listener) {
this.listener = listener;
}
interface Listener {
void onTextReceived(String text);
}
}
I have tried implementing LocationListener as an inner class but I got null value for the latitude and longitude
This happen because you don not have Permission .
get these permissions
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.BROADCAST_SMS"
tools:ignore="ProtectedPermissions" />
and for api>21
ActivityCompat.requestPermissions(LoginActivity.this,
new String[]{Manifest.permission.BROADCAST_SMS,Manifest.permission.READ_SMS},
1);

SMS activity won't send

I coding an application which when a button is pressed and a timer reaches zero, an SMS and email sends to saved contacts and the message contain information saved in preferences. I have the email sending fine and SMS seems to be working with no crashes but i don't receive any SMS at all:
#Override
public void onFinish() {
final String[] personalInfo = db.getPersonalDetails();
final Cursor contacts = db.getContacts();
if (match == false) {
sendSms();
if (db.hasGmail()) {
Thread s = new Thread(new Runnable() {
public void run() {
String args[] = db.getGmail();
GmailSender sender = new GmailSender(args[0],args[1], getApplicationContext());
Cursor c = db.getEmailContacts();
while (c.moveToNext()) {
try {
Log.e(args[0], args[1]);
sender.sendMail(
args[0],
c.getString(c
.getColumnIndex("emailAddress")));
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
}
});
s.start();
}
Toast.makeText(getApplicationContext(), "Information sent",
5000).show();
}
}
}.start();
}
private void sendSms() {
sms = new Intent(this, SMS.class);
this.startService(sms);
}
SMS Class:
public class SMS extends Service {
String BankAccount, BankNameAddress, SortCode;
String message;
SharedPreferences prefs;
public void initilizePrefs() {
prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
BankAccount = prefs.getString("BankAccount", null);
BankNameAddress = prefs.getString("BankNameAddress", null);
SortCode = prefs.getString("SortCode", null);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onStart(Intent intent, int startid) {
super.onStart(intent, startid);
initilizePrefs();
String mes = "my account info is: " + BankNameAddress + " "
+ " account number: " + BankAccount + " Sort Code is: "
+ SortCode + " " + "Thank you so much!!";
try {
if (BankNameAddress != null && BankAccount != null
&& SortCode != null) {
sendSMS("Help!! I've completely run out of money and need you to send some via bank transfer please. "
+ mes);
}
else
Toast.makeText(getBaseContext(),
"Please ensure all sections of preferences are filled",
Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void sendSMS(String message) {
Database db = new Database(this);
Cursor cursor = db.getNumbers();
db.onStop();
if (cursor != null) {
while (cursor.moveToNext()) {
String phoneNumber = cursor.getString(cursor
.getColumnIndex("number"));
Log.e("number", phoneNumber);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
you need to have a broadcast receiver which will receive your sms . the code is as follows :
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 = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");//it must be given as it is only
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); //Create an SmsMessage from a raw PDU.
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
//---display the new SMS message---
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("message", str);
context.startActivity(i);
Toast.makeText(context, "mmmm"+str, Toast.LENGTH_SHORT).show();
}
}
}
In your activity class , receive the intent :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tx=(TextView) findViewById(R.id.textView1);
Bundle bun=getIntent().getExtras();
String stuff=bun.getString("message");
tx.setText("Welcome,"+stuff);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Add permisions :

Show dialog after sms receive

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();

Want to delete the messages of a specific number from the INBOX of android

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);
}
}

Is simultaneuos reading, writing and then again reading back NFC tags possible in android?

Is it possible to read then write and then again read back the same data earlier we wrote on a NFC tag without removing it from the field(mobile) in Android? If Anybody has done this then please share over here....
public class MainActivity extends Activity
{
NfcAdapter adapter;
PendingIntent pendingIntent;
IntentFilter writeTagFilters[];
Tag mytag;
private TextView mTextViewData;
Context ctx;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ctx=this;
mTextViewData = (TextView)findViewById(R.id.mtextView);
Button btnWrite = (Button) findViewById(R.id.write_button);
final EditText mEditText = (EditText)findViewById(R.id.edit_message);
adapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected1 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try
{
tagDetected1.addDataType("text/nfc-service-tag");
}
catch (MalformedMimeTypeException e)
{
throw new RuntimeException("Could not add MIME type.", e);
}
writeTagFilters = new IntentFilter[] { tagDetected1 };
btnWrite.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(mytag==null)
{
Toast.makeText(ctx, ctx.getString(R.string.error_detected), Toast.LENGTH_LONG ).show();
}
else
{
writeTag(mEditText.getText().toString(),mytag);
}
}
});
}
private void writeTag(String text,Tag tag)
{
// record to launch Play Store if app is not installed
// record that contains our custom "retro console" game data, using custom MIME_TYPE
String mimeType = "text/nfc-service-tag";
byte[] payload = text.getBytes(Charset.forName("US-ASCII"));
byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
NdefMessage message = new NdefMessage(new NdefRecord[] { record });
try
{
// see if tag is already NDEF formatted
Ndef ndef = Ndef.get(tag);
if (ndef != null)
{
ndef.connect();
if (!ndef.isWritable())
{
Toast.makeText(ctx, "Read-only tag.", Toast.LENGTH_LONG ).show();
}
// work out how much space we need for the data
int size = message.toByteArray().length;
if (ndef.getMaxSize() < size)
{
Toast.makeText(ctx, "Tag doesn't have enough free space.", Toast.LENGTH_LONG).show();
}
ndef.writeNdefMessage(message);
Toast.makeText(ctx, ctx.getString(R.string.ok_writing), Toast.LENGTH_LONG ).show();
ndef.close();
}
else
{
// attempt to format tag
NdefFormatable format = NdefFormatable.get(tag);
if (format != null)
{
try
{
format.connect();
format.format(message);
Toast.makeText(ctx, ctx.getString(R.string.ok_writing), Toast.LENGTH_LONG ).show();
}
catch (IOException e)
{
Toast.makeText(ctx,"Unable to format tag to NDEF.", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(ctx,"Tag doesn't appear to support NDEF format.", Toast.LENGTH_LONG).show();
}
}
}
catch(Exception e)
{
}
}
#Override
protected void onNewIntent(Intent intent)
{
String action = intent.getAction();
if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
{
NdefMessage[] msgs = getNdefMessagesFromIntent(intent);
final NdefMessage msg = (NdefMessage)msgs[0];
String payload = new String(msg.getRecords()[0].getPayload());
mTextViewData.setText(payload);
mytag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Toast.makeText(this, "In onNewIntent()", Toast.LENGTH_LONG ).show();
}
else if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))
{
Toast.makeText(this, "This NFC tag has no NDEF data.", Toast.LENGTH_LONG).show();
}
}
#Override
public void onResume()
{
super.onResume();
if (getIntent().getAction() != null)
{
// tag received when app is not running and not in the foreground:
if (getIntent().getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
{
NdefMessage[] msgs = getNdefMessagesFromIntent(getIntent());
NdefRecord record = msgs[0].getRecords()[0];
byte[] payload = record.getPayload();
String payloadString = new String(payload);
mTextViewData.setText(payloadString);
Toast.makeText(this, "In onResume()", Toast.LENGTH_LONG ).show();
}
}
adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
}
#Override
public void onPause()
{
super.onPause();
adapter.disableForegroundDispatch(this);
}
NdefMessage[] getNdefMessagesFromIntent(Intent intent)
{
// Parse the intent
NdefMessage[] msgs = null;
String action = intent.getAction();
if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
{
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null){
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++)
{
msgs[i] = (NdefMessage) rawMsgs[i];
}
}
else
{
// Unknown tag type
byte[] empty = new byte[] {};
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
msgs = new NdefMessage[] { msg };
}
}
else
{
//Log.e(TAG, "Unknown intent.");
finish();
}
return msgs;
}
}
You can call ndef.getNdefMessage() right after you do ndef.writeNdefMessage(message) to check the result. It will actually read the NDEF message back from the tag. However, in general, when ndef.writeNdefMessage(message) does not throw an exception, it is safe to assume the message was written successfully.

Categories

Resources