How to send Intent to SMS Receiver? - android

I would like a send an intent to this receiver from another application, which handles SMS. I am quite new to this SMS handling. Can someone kindly guide me on what intent,I mean, how and what and intent should have to execute this piece of receiver code. Thanks.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
try {
Object[] objArr = (Object[]) extras.get("pdus");
for (Object obj : objArr) {
SmsMessage createFromPdu = SmsMessage.createFromPdu((byte[]) obj);
String displayOriginatingAddress = createFromPdu.getDisplayOriginatingAddress();
String displayMessageBody = createFromPdu.getDisplayMessageBody();
try {
if (displayOriginatingAddress.contains("MADAPP")) {
if (displayMessageBody.contains("The PIN is")) {
Toast.makeText(context, displayMessageBody, 1).show();
}
if (displayMessageBody.contains("successfully validated")) {
displayMessageBody.contains("activating Pockets");
}
}
} catch (Exception e) {
}
}
} catch (Exception e2) {
}
}
}
}

Try this code
write this in your manifest
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<receiver android:name=".SMSReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
For more description
http://androidexample.com/Incomming_SMS_Broadcast_Receiver_-_Android_Example/index.php?view=article_discription&aid=62&aaid=87

Related

My app doesn't asks for Accessibility Permission

I create a app which uses accessibility. I passed intent for android accessibility settings but its not executed.
Here is code of android manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.new_app">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<application
android:allowBackup="true"
android:label="#string/app_name"
android:icon="#mipmap/safety"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Service_Running" />
<activity android:name=".MainActivity" />
<activity android:name=".injured_activity" />
<activity android:name=".splash_Activity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".Whatsapp_Accessibility"
android:label="Accessibility Service"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<meta-data
android:name="android.accessibilityservice"
android:resource="#xml/whatsapp_service"/>
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService"/>
</intent-filter>
</service>
<service
android:name=".Background_Service"
android:enabled="true"
android:exported="true" />
</application>
</manifest>
Here is code of accessiblity service xml file
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeWindowContentChanged"
android:packageNames="com.whatsapp"
android:accessibilityFeedbackType="feedbackSpoken"
android:notificationTimeout="100"
android:canRetrieveWindowContent="true"/>
Here is the code of activity in which intent is passed
package com.example.new_app;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActivityManager;
import android.app.UiAutomation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;
public class splash_Activity extends AppCompatActivity {
SharedPreferences sharedPreferences;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_);
sharedPreferences= getSharedPreferences("MySharedPreferences",MODE_PRIVATE);
String phone=sharedPreferences.getString("Phone_Number","");
String message=sharedPreferences.getString("Message","");
if (!isAccessibilitySettingsOn(getApplicationContext())) {
startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
}
if(phone!="" && message!="")
{
if(!isMyServiceRunning(Background_Service.class))
{
startForegroundService(new Intent(this,Background_Service.class));
}
Intent intent1=new Intent(this,Service_Running.class);
startActivity(intent1);
}
else
{
Intent intent1=new Intent(this,MainActivity.class);
startActivity(intent1);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
private boolean isAccessibilitySettingsOn(Context mContext) {
int accessibilityEnabled = 0;
final String service = getPackageName() + "/" + Whatsapp_Accessibility.class.getCanonicalName();
try {
accessibilityEnabled = Settings.Secure.getInt(
mContext.getApplicationContext().getContentResolver(),
android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
Log.v("this", "accessibilityEnabled = " + accessibilityEnabled);
} catch (Settings.SettingNotFoundException e) {
Log.e("this", "Error finding setting, default accessibility to not found: "
+ e.getMessage());
}
TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
if (accessibilityEnabled == 1) {
Log.v("this", "***ACCESSIBILITY IS ENABLED*** -----------------");
String settingValue = Settings.Secure.getString(
mContext.getApplicationContext().getContentResolver(),
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
if (settingValue != null) {
mStringColonSplitter.setString(settingValue);
while (mStringColonSplitter.hasNext()) {
String accessibilityService = mStringColonSplitter.next();
Log.v("this", "-------------- > accessibilityService :: " + accessibilityService + " " + service);
if (accessibilityService.equalsIgnoreCase(service)) {
Log.v("this", "We've found the correct setting - accessibility is switched on!");
return true;
}
}
}
} else {
Log.v("this", "***ACCESSIBILITY IS DISABLED***");
}
return false;
}
}
Here is the code of Accessiblity Service
package com.example.new_app;
import android.accessibilityservice.AccessibilityService;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import java.util.List;
public class Whatsapp_Accessibility extends AccessibilityService {
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if(getRootInActiveWindow() == null){
return;
}
AccessibilityNodeInfoCompat rootNodeInfo = AccessibilityNodeInfoCompat.wrap(getRootInActiveWindow());
//get edit text if message from whats app
List<AccessibilityNodeInfoCompat> messageNodeList = rootNodeInfo.findAccessibilityNodeInfosByViewId("com.whatsapp:id/entry");
if(messageNodeList == null || messageNodeList.isEmpty())
return;
//checking if message field if filled with text and ending with our suffix
AccessibilityNodeInfoCompat messageField = messageNodeList.get(0);
if(messageField == null || messageField.getText().length() == 0 || !messageField.getText().toString().endsWith(" Send by Safety App"))
return;
// get whatsapp send message button node list
List<AccessibilityNodeInfoCompat> sendMessageNodeList = rootNodeInfo.findAccessibilityNodeInfosByViewId("com.whatsapp:id/send");
if(sendMessageNodeList == null || sendMessageNodeList.isEmpty())
return;
AccessibilityNodeInfoCompat sendMessage = sendMessageNodeList.get(0);
if(!sendMessage.isVisibleToUser())
return;
//fire send button
sendMessage.performAction(AccessibilityNodeInfo.ACTION_CLICK);
try{
Thread.sleep(2000);
performGlobalAction(GLOBAL_ACTION_BACK);
Thread.sleep(2000);
performGlobalAction(GLOBAL_ACTION_BACK);
}catch (InterruptedException ignored) {}
}
#Override
public void onInterrupt() {
}
}
I tested all this code on android 10

Cordova Plugin to identify incoming call number in android?

I am trying to get the incoming call number from my cordova android plugin. Able to get the Phone State using TELEPHONYMANGER.PHONE_STATE_CHANGED. But unable to get the incoming call number. BroadcastReceiver's Intent provides the option to get the incoming call number. But BroadcastReceiver's onReceive function is not triggered. Please help.
package io.infonion.calldetail;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import android.support.v4.content.LocalBroadcastManager;
import org.apache.cordova.PluginResult;
import android.content.Context;
import android.widget.Toast;
import android.telephony.PhoneStateListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.TelephonyManager;
import android.content.BroadcastReceiver;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class CallDetail extends CordovaPlugin {
CallStateListener listener;
IntentFilter intentFilter;
Context maincontext;
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
Toast.makeText(cordova.getActivity().getApplicationContext(), "first", Toast.LENGTH_LONG).show();
if (listener == null) {
listener = new CallStateListener();
listener.setCordovaContext(cordova.getActivity().getApplicationContext());
listener.setCallbackContext(callbackContext);
Toast.makeText(cordova.getActivity().getApplicationContext(), "fourth", Toast.LENGTH_LONG).show();
intentFilter = new IntentFilter() ;
intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
LocalBroadcastManager.getInstance(super.webView.getContext()).registerReceiver(listener,intentFilter);
//registerReceiver(listener, intentFilter);
Toast.makeText(cordova.getActivity().getApplicationContext(), "fifth", Toast.LENGTH_LONG).show();
}
return true;
}
}
class CallStateListener extends BroadcastReceiver {
private CallbackContext callbackContext;
private Context cordovaContext;
public void setCallbackContext(CallbackContext callbackContext) {
Toast.makeText(cordovaContext, "third", Toast.LENGTH_LONG).show();
this.callbackContext = callbackContext;
}
public void setCordovaContext(Context cordovaContext) {
Toast.makeText(cordovaContext, "second", Toast.LENGTH_LONG).show();
this.cordovaContext = cordovaContext;
}
#Override
public void onReceive(final Context context, Intent intent) {
String act=intent.getAction();
String number="";
Toast.makeText(cordovaContext, "Sixth", Toast.LENGTH_LONG).show();
if(intent.getAction().equals("TelephonyManager.ACTION_PHONE_STATE_CHANGED")){
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Toast.makeText(cordovaContext, state, Toast.LENGTH_LONG).show();
if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
// Log.d(TAG, "Inside Extra state off hook");
number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(cordovaContext, "EXTRA_STATE_OFFHOOK", Toast.LENGTH_LONG).show();
// Log.e(TAG, "outgoing number : " + number);
}
else if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
// Log.e(TAG, "Inside EXTRA_STATE_RINGING");
number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Toast.makeText(cordovaContext, "RINGING", Toast.LENGTH_LONG).show();
// Log.e(TAG, "incoming number : " + number);
}
else if(state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
Toast.makeText(cordovaContext, "EXTRA_STATE_IDLE", Toast.LENGTH_LONG).show();
// Log.d(TAG, "Inside EXTRA_STATE_IDLE");
}
PluginResult result = new PluginResult(PluginResult.Status.OK, number);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
}
}
}
Maybe it's late to answer but may this help other people :
Creating instance "new CallStateListener()" for the receiver will not trigger the onReceive method.
Your receiver is not working, it should be declared at AndroidManifest.xml inside the tag application .
So you should first make static the class CallStateListener :
public static CallStateListener extends BrodcastReceiver {}
and add these lines on your plugin.xml file inside :
<config-file target="AndroidManifest.xml" parent="/manifest/application">
<receiver android:name="io.infonion.calldetail.CallDetail$CallStateListener"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</config-file>

Intent Service not called

Here is my service class
package com.example.com.listener;
import android.app.DownloadManager;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.example.com.R;
import com.example.com.listener.GCMRegistrationListener;
import com.example.com.util.Constants;
import com.example.com.web.RawRequest;
import com.example.com.web.WebRequest;
public class GCMRegistrationService extends IntentService{
private static final String TAG = "GCMRegistrationService";
private static final String[] TOPICS = {"global"};
public GCMRegistrationService() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
sendRegistrationToServer(token,sharedPreferences.getString(Constants.EMAIL_SHARED_PREF,""));
Toast.makeText(this,"This is your token " + token,Toast.LENGTH_LONG).show();
Log.i("token", token);
// You should store a boolean that indicates whether the generated token has been
// sent to your server. If the boolean is false, send the token to your server,
// otherwise your server should have already received the token.
sharedPreferences.edit().putBoolean(Constants.GCM_TOKEN_TO_SERVER, true).apply();
// [END register_for_gcm]
} catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
// If an exception happens while fetching the new token or updating our registration data
// on a third-party server, this ensures that we'll attempt the update at a later time.
sharedPreferences.edit().putBoolean(Constants.GCM_TOKEN_TO_SERVER, false).apply();
}
}
/**
* Persist registration to third-party servers.
*
* Modify this method to associate the user's GCM registration token with any server-side account
*
* #param token The new token.
*/
private void sendRegistrationToServer(String token,String email) {
WebRequest request= new RawRequest(this,Constants.SEND_GCM_TOKEN, Request.Method.POST);
Map<String,String> requestParams= new HashMap<>();
requestParams.put(Constants.GCM_TOKEN_LABEL,token);
requestParams.put(Constants.EMAIL_SHARED_PREF,email);
request.sendRequest(new GCMRegistrationListener(), requestParams, null);
}
}
Here is the code I used to start the service:
Intent gcmRegister= new Intent(context,GCMRegistrationService.class);
context.startService(gcmRegister);
Manifest file entry is:
Manifest package is com.example.com
and service entry is
<service android:name=".listener.GCMRegistrationService" android:exported="false" />
Unfortunately my service is not running. Please help.
GCM register() has been deprecated. Use InstanceID to perform general GCM registration management. as shown below , use google play lib to get it.
Log.i(TAG, "GCM Registration event is received");
String token;
try {
token = InstanceID.getInstance(context).getToken(context.getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.i(TAG, "GCM Registration Token retrieved from google cloud: " + token);
//
} catch (IOException e) {
// exponential back off
Log.e(TAG, "IO error occurred, going to back off. backoffIndexGCM:" + backoffIndexGCM);
exponentialBackOff.postDelayed(exponentialBackOffGCMRegisterRun, 1000 * backoffIndexGCM);
backoffIndexGCM *= 2;
// should not wait more than 1000 sec in any circumstance.
backoffIndexGCM %= 1000;
}
Change your data according to your requirement ,Allow this service tag outside the closing activity tag in manifest file :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.twitter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".TwitterTwoActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="tfe.rma.ciss.be.Server"/>
</application>
</manifest>
Adding superclass to onCreate super.onCreate() and change onStart by onStartCommand (plus its superclass super.onStartCommand().
package tfe.rma.ciss.be;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlrpc.android.MethodCall;
import org.xmlrpc.android.XMLRPCServer;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class Server extends IntentService {
public String myData="";
public String streamTitle = "",path="";
public void onCreate() {
super.onCreate();
Log.d("Server", ">>>onCreate()");
}
public Server() {
super("Server");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, startId, startId);
Log.i("LocalService", "Received start id " + startId + ": " + intent);
return START_STICKY;
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d("Server", ">>>handlingIntent()");
try {
ServerSocket socket = new ServerSocket(8214);
XMLRPCServer server = new XMLRPCServer();
Log.d("Server", ">>>opening on port" + socket);
while (true) {
Socket client = socket.accept();
MethodCall call = server.readMethodCall(client);
String name = call.getMethodName();
if (name.equals("newImage")) {
ArrayList<Object> params = call.getParams();
// assume "add" method has two Integer params, so no checks done
myData = (String)( params.get(0));
//int i1 = (Integer) params.get(1);
server.respond(client, new Object[] {200});
/*intent = new Intent (this, ParseFunction.class);
startService (intent); */
Toast.makeText(this, myData, Toast.LENGTH_SHORT).show();
Log.d("ParseFunction", ">>>Started()");
Intent i = new Intent( this, B.class );
i.putExtra( "Azo", myData);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity( i );
} else {
server.respond(client, null);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}

Reading incoming SMS but not able to update EditText in android

I am getting the message from BroadcastReceiver but I am unable to update the EditText in my Activity. Message displayed in logcat using Log.i() but EditText is not updating.
my receiver class is as follows:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
public class IncomingSms extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
final Bundle bundle = intent.getExtras();
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();
try
{
if (senderNum .equals("TA-DOCOMO"))
{
Otp Sms = new Otp();
Sms.recivedSms(message );
}
}
catch(Exception e){}
}
}
} catch (Exception e)
{
}
}
}
My Activity class
public class Otp extends Activity
{
static EditText OtpNumber;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.otp);
OtpNumber= (EditText) findViewById(R.id.txtName);
}
public void recivedSms(String message)
{
try
{
OtpNumber.setText(message);
}
catch (Exception e)
{
}
}
}
in mainfest file
<uses-permission android:name="android.permission.RECEIVE_SMS" >
</uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" >
</uses-permission>
<receiver android:name=".IncomingSms">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
i have followed this link
bro if your edit text is in another activity then you need to transfer the data (otp) to another activity using intent
here is the reference

NFC Intent Filter - Sending Message Non-Main Activity

I am sure this is simple but I cannot figure it out. All I am trying to do is send a message via NFC. The code I have work perfectly if I am sending it to the main activity, but I don't know how to send it to a different activity. I have looked over both the NFC and Intent Filter articles on the Android Developer pages but am still not sure exactly how to do this. I am trying to send it to a NFC activity, I will post my manifest and NFC class below.
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.justbaumdev.tagsense"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo" >
<activity
android:name=".TagSense"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.justbaumdev.tagsense.NFC" android:exported="false">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/com.justbaumdev.tagsense" />
</intent-filter>
</activity>
</application>
</manifest>
NFC Class:
package com.justbaumdev.tagsense;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.widget.Toast;
public class NFC extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
private NfcAdapter mNfcAdapter;
private static final int MESSAGE_SENT = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nfc);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this); // Check for available NFC Adapter
if (mNfcAdapter == null)
{
Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
else
{
mNfcAdapter.setNdefPushMessageCallback(this, this); // Register callback to set NDEF message
mNfcAdapter.setOnNdefPushCompleteCallback(this, this); // Register callback to listen for message-sent success
}
}
#Override
public void onResume() {
super.onResume();
// Check to see that the Activity started due to an Android Beam
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
processIntent(getIntent());
}
}
#Override
public void onNewIntent(Intent intent) {
// onResume gets called after this to handle the intent
setIntent(intent);
}
#Override
public NdefMessage createNdefMessage(NfcEvent event) {
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String mac = wm.getConnectionInfo().getMacAddress();
String newMac = mac.substring(0, 2);
mac = mac.substring(2);
int hex = Integer.parseInt(newMac, 16) + 0x2;
newMac = Integer.toHexString(hex);
String text = newMac + mac;
NdefMessage msg = new NdefMessage(NdefRecord.createMime(
"application/com.justbaumdev.tagsense", text.getBytes()));
return msg;
}
/**
* Implementation for the OnNdefPushCompleteCallback interface
*/
#Override
public void onNdefPushComplete(NfcEvent arg0) {
// A handler is needed to send messages to the activity when this
// callback occurs, because it happens from a binder thread
mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
}
/** This handler receives a message from onNdefPushComplete */
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_SENT:
Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_LONG).show();
break;
}
}
};
/**
* Parses the NDEF Message from the intent and prints to the TextView
*/
//TODO Currently overwrites any previously saved mac addresses. Get FB ID as value. Auto end activity.
void processIntent(Intent intent) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
// only one message sent during the beam
NdefMessage msg = (NdefMessage) rawMsgs[0];
// record 0 contains the MIME type, record 1 is the AAR, if present
//textView.setText(new String(msg.getRecords()[0].getPayload()));
String payload = new String(msg.getRecords()[0].getPayload());
Toast.makeText(this, new String(msg.getRecords()[0].getPayload()), Toast.LENGTH_LONG).show();
SharedPreferences appData = getSharedPreferences("appData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = appData.edit();
String addresses = appData.getString("mac_address", null);
if(addresses==null)
{
JSONArray addressArray = new JSONArray();
addressArray.put(payload);
addresses = addressArray.toString();
}
else
{
try {
if(!addresses.contains(payload))
{
JSONArray addressArray = new JSONArray(addresses);
addressArray.put(payload);
addresses = addressArray.toString();
}
} catch (JSONException e) {
Toast.makeText(this, "Error adding new friend. Please try again.", Toast.LENGTH_SHORT).show();
}
}
editor.putString("mac_address", addresses);
editor.commit();
}
}
Thanks for your help.
Remove the attribute android:exported="false". See also https://stackoverflow.com/a/12719621/1202968

Categories

Resources