This question already has answers here:
How to declare global variables in Android?
(17 answers)
Closed 9 years ago.
I went through many pages, but couldn't understand properly how to declare a class to contain global variables and its declaration in manifest file (most important thing, need some extra concentration on that)
The class
global file
/**
*
*/
package com.furniture;
/**
* #author sanketh
*
*/
public class Gloabal extends ap{
public String refer="";
public int set=0;
public String getData(){
return this.refer;
}
public void setData(String d,int i){
this.refer=d;
set=i;
}
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.furniture"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name=".Gloabal">
<activity
android:name="com.furniture.login"
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=".MainActivity"></activity>
<activity android:name=".passforgot"></activity>
<activity android:name=".newuser"></activity>
<activity android:name=".settings"></activity>
<receiver android:name=".smsreciever">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
somefile
package com.furniture;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class smsreciever extends BroadcastReceiver
{
public String value;
#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");
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";
}
//---display the new SMS message---
// Intent i1=new Intent();
//((Gloabal)this.get).setData(str);
// Gloabal g1=new Gloabal();
Global g = (Global)getApplication();
int data=g.getData();
Log.v("sanketh","smsreciver value of str:"+str);
int a=1;
g1.setData(str,a);
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
}
Here i want to set the data to it...
Global g = (Global)getApplication(); // this line gives error for get application
Apart from using Application to create Global Variables, you can create a regular class to hold your variables. Right now, I am using this:
public class GlobalVar {
public String getGlobalVar1() {
return GlobalVar1;
}
public void setGlobalVar1(String GlobalVar1) {
this.GlobalVar1 = GlobalVar1;
}
private String GlobalVar1 = "";
static {
instance = new GlobalVar();
}
private GlobalVar() {
}
public static GlobalVar getInstance() {
return GlobalVar.instance;
}
}
For setting a new value to your GlobalVar1 :
GlobalVar.getInstance().setGlobalVar1(value);
And for getting the value:
GlobalVar.getInstance().getGlobalVar1;
public class GlobalState extends Application {
private int gameScore = 0;
public int getGameScore() {
return gameScore;
}
public void setGameScore(int gameScore) {
this.gameScore = gameScore;
}
public void incrementScore(){
gameScore++;
}
Manifest file
<uses-sdk android:minSdkVersion="14" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:name="GlobalState" >
<!-- component definitions -->
</application>
Usage in Activity
GlobalState state = ((GlobalState) getApplicationContext());
Related
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
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
I created application that if the button is click it will send SMS to the number that came from webservice. Then I use Alarm Manager to send SMS repeatedly in the number that i get from the web service. It is working fine but when I change the number that I want to send an SMS it will not work. I don't know what is wrong with my code. Here is my code.
This is my code that send an SMS.
public class EmergencyAssistance extends ActionBarActivity {
ArrayList<Objects> objectsList = new ArrayList<>();
String url = "http://192.168.254.108:8080/taxisafe3/webService/listcontact";
String urls = "http://192.168.254.108:8080/taxisafe3/webService/plate";
String contact1;
String contact2;
String contact3;
String contact4;
String contact5;
String message;
String message1;
Button send;
LocationService locationService;
double lat;
double lng;
StringBuilder address;
StringBuffer smsBody;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emergency_assistance);
send = (Button) findViewById(R.id.emergency);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setData();
new Task().execute(urls);
new Tasks().execute(url);
}
});
}
public class Task extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content = HttpULRConnect.getData(url);
return content;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ary = new JSONArray(s);
for (int i = 0; i < ary.length(); i++) {
JSONObject jsonobject = ary.getJSONObject(i);
Objects objects = new Objects();
objects.setCon1(jsonobject.getString("con1"));
objects.setCon2(jsonobject.getString("con2"));
objects.setCon3(jsonobject.getString("con3"));
objects.setCon4(jsonobject.getString("con4"));
objects.setCon5(jsonobject.getString("con5"));
objectsList.add(objects);
contact1 = objects.getCon1();
contact2 = objects.getCon2();
contact3 = objects.getCon3();
contact4 = objects.getCon4();
contact5 = objects.getCon5();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class Tasks extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content = HttpULRConnect.getData(urls);
return content;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ary = new JSONArray(s);
for (int i = 0; i < ary.length(); i++) {
JSONObject jsonobject = ary.getJSONObject(i);
Objects objects = new Objects();
objects.setTaxi_plate_no(jsonobject.getString("taxi_plate_no"));
objects.setDriver_operator(jsonobject.getString("driver_operator"));
objectsList.add(objects);
message = objects.getTaxi_plate_no();
message1 = objects.getDriver_operator();
emergency();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void emergency() {
smsBody = new StringBuffer();
smsBody.append("https://maps.google.com/maps?q=");
smsBody.append(lat);
smsBody.append(",");
smsBody.append(lng);
String msgs = "[EMERGENCY!] \nTaxi plate #: " + message + "\nTaxi operator: " + message1 + "\n" + address + smsBody.toString();
try {
if (PatternChecker.isNotNull(contact1)) {
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent(EmergencyAssistance.this, AlarmReceiver.class);
Bundle bundle = new Bundle();
bundle.putCharSequence("num1", contact1);
bundle.putCharSequence("msg1", msgs);
intent.putExtras(bundle);
PendingIntent pendingIntent = PendingIntent.getBroadcast(EmergencyAssistance.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 1000 * 60 * 1, pendingIntent);
Toast.makeText(getApplicationContext(), "SMS Sent", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "No Number", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Catch", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
public void setData() {
locationService = new LocationService(getApplication());
if(locationService.canGetLocation()){
lat = locationService.getLatitude();
lng = locationService.getLongitude();
}else{
locationService.showSettingsAlert();
}
getMyLocationAddress();
}
public void getMyLocationAddress() {
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
if (addresses != null) {
Address fetchedAddress = addresses.get(0);
address = new StringBuilder();
for (int i = 0; i < fetchedAddress.getMaxAddressLineIndex(); i++) {
address.append(fetchedAddress.getAddressLine(i)).append("\n");
}
} else
Toast.makeText(getApplicationContext(),"No Address", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Could not get address..!", Toast.LENGTH_LONG).show();
}
}
}
This is my Alarm Receiver.
public class AlarmReceiver extends BroadcastReceiver
{
String msg;
String num;
#Override
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
num = bundle.getString("num1");
msg = bundle.getString("msg1");
//Toast.makeText(context, num + msg, Toast.LENGTH_SHORT).show();
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(num, null, msg, null, null);
}
}
This is my manifest to allow sending SMS and to register the alarm receiver.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.group.taxisafe" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="19" />
<permission
android:name="com.mapv2.demo.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.mapv2.demo.permission.MAPS_RECEIVE" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#mipmap/taxisafe"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Login"
android:label="TaxiSafe" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Register"
android:label="#string/app_name" >
</activity>
<activity
android:name=".Home"
android:label="#string/title_activity_home" >
</activity>
<activity
android:name=".DriverDetails"
android:label="#string/title_activity_driver_details" >
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
</activity>
<activity
android:name=".Contacts"
android:label="#string/title_activity_contacts" >
</activity>
<activity
android:name=".ReportActivity"
android:label="#string/title_activity_report" >
</activity>
<activity
android:name=".DriversList"
android:label="#string/title_activity_drivers_list" >
</activity>
<activity
android:name=".DriverAdapter"
android:label="#string/title_activity_driver_adapter" >
</activity>
<activity
android:name=".EmergencyAssistance"
android:label="#string/title_activity_emergency_assistance" >
</activity>
<activity
android:name=".DisplayContact"
android:label="#string/title_activity_display_contact" >
</activity>
<activity
android:name=".ContactAdapter"
android:label="#string/title_activity_contact_adapter" >
</activity>
<receiver android:name=".AlarmReceiver" />
</application>
</manifest>
Hello fellow programmers!
I am really new to Android, 2 weeks old.
I am trying to do some programming with NFC. I have Nexus 5 and I am trying to read and display UID of the MIFARE Classic 1k. I know all the protocol compatibilities issues with the Broadcom chip, so we can skip that and go straight to fact that you can read UID with no problem.
I want to catch the intent and show a toast with read UID. So far I made it work by putting performIntent into onCreate method. By making the intent to restart my activity I am able to handle that intent and show its UID via toast and that all works. Here is my humble code:
MainActivity.java
package sanjin.com.nfc;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.app.Activity;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
NfcAdapter mNfcAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
Boolean nfcEnabled = mNfcAdapter.isEnabled();
if (nfcEnabled){
Toast.makeText(MainActivity.this,
R.string.turned_on,
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this,
R.string.turned_off,
Toast.LENGTH_SHORT).show();
}
performIntent(getIntent());
}
private String serialId = "";
#Override
public void onResume() {
super.onResume();
performIntent(getIntent());
}
private void performIntent(Intent intent) {
String action = intent.getAction();
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
try {
byte[] tagId = tag.getId();
serialId = toHexString(tagId);
Log.d("[ReadCardTools]", "Serial Number: " + serialId);
Toast.makeText(this, serialId,Toast.LENGTH_SHORT).show();
} catch (NullPointerException ex) {
ex.printStackTrace();
serialId = "ERROR";
}
}
}
public static String toHexString(byte[] bytes) {
char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] hexChars = new char[bytes.length * 2];
int v;
for ( int j = 0; j < bytes.length; j++ ) {
v = bytes[j] & 0xFF;
hexChars[j*2] = hexArray[v/16];
hexChars[j*2 + 1] = hexArray[v%16];
}
return new String(hexChars);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sanjin.com.nfc">
<uses-permission android:name="android.permission.NFC" />
<uses-feature
android:name="android.hardware.nfc"
android:required="true" />
<application
android:label="#string/app_name"
android:launchMode="singleTask">
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Now, I want this intent to just show the toast without starting the activity again. I realize its working because when the activity restarts, intent gets handled and show me my UID.
I just want the incoming intent to show the toast containing its UID.
Sorry if this was asked before, I tried finding it but no luck.
Thanks!
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
NfcAdapter nfcAdapter;
TextView uidView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uidView = (TextView)findViewById(R.id.mTextView);
nfcAdapter = NfcAdapter.getDefaultAdapter(MainActivity.this);
Boolean nfcEnabled = nfcAdapter.isEnabled();
if (nfcEnabled){
Toast.makeText(MainActivity.this,
R.string.turned_on,
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this,
R.string.turned_off,
Toast.LENGTH_SHORT).show();
}
Intent intent = getIntent();
resolveIntent(intent);
}
protected void resolveIntent(Intent intent) {
Tag nfcTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (nfcTag == null) {
Log.w(LOG_TAG, "Unable to obtain NFC tag from intent!");
} else {
String tagId = bytesToHex(nfcTag.getId());
uidView.setText(tagId);
//Toast.makeText(getApplicationContext(), tagId, Toast.LENGTH_LONG).show();
}
}
public static String bytesToHex(byte[] bytes) {
StringBuilder ret = new StringBuilder();
if (bytes != null) {
for (Byte b : bytes) {
ret.append(String.format("%02X", b.intValue() & 0xFF));
}
}
StringBuilder result = new StringBuilder();
for (int i = 0; i <= ret.length() - 2; i = i + 2) {
result.append(new StringBuilder(ret.substring(i, i + 2)).reverse());
}
String card = result.reverse().toString();
if(card.length() == 8){
card = "0" + Long.parseLong(card, 16) + "\n\n";
}
if(card.length() == 9){
card = Long.parseLong(card, 16) + "\n\n";
}
return card;
}
}
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