我正在开发一个Android应用程序,它接收来自Arduino MEGA 2560的rfid读取。这是我的Android应用程序的代码
package com.example.halfway;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
public class Violation extends Activity implements Runnable {
private static final String ACTION_USB_PERMISSION = "com.google.android.DemoKit.action.USB_PERMISSION";
private UsbManager mUsbManager;
private PendingIntent mPermissionIntent;
private boolean mPermissionRequestPending;
private UsbAccessory mAccessory;
private ParcelFileDescriptor mFileDescriptor;
private FileInputStream mInputStream;
private FileOutputStream mOutputStream;
EditText name,add,vnum,lnum;
Button one;
CheckBox a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,t,u,v,w,x,y,z;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_violation);
setupAccessory();
name =(EditText) findViewById(R.id.fullname);
add =(EditText) findViewById(R.id.add);
vnum =(EditText) findViewById(R.id.plate_no);
lnum =(EditText) findViewById(R.id.license_no);
a=(CheckBox) findViewById(R.id.sec1_a);
b=(CheckBox)findViewById(R.id.sec1_b);
c=(CheckBox)findViewById(R.id.sec1_c);
d=(CheckBox)findViewById(R.id.sec1_d);
e=(CheckBox)findViewById(R.id.sec1_e);
f=(CheckBox)findViewById(R.id.sec1_f);
g=(CheckBox)findViewById(R.id.sec1_g);
h=(CheckBox)findViewById(R.id.sec1_h);
i=(CheckBox)findViewById(R.id.sec1_i);
j=(CheckBox)findViewById(R.id.sec1_j);
k=(CheckBox)findViewById(R.id.sec1_k);
l=(CheckBox)findViewById(R.id.sec1_l);
m=(CheckBox)findViewById(R.id.sec1_m);
n=(CheckBox)findViewById(R.id.sec1_n);
o=(CheckBox)findViewById(R.id.sec1_o);
p=(CheckBox)findViewById(R.id.sec1_p);
q=(CheckBox)findViewById(R.id.sec1_q);
r=(CheckBox)findViewById(R.id.sec1_r);
t=(CheckBox)findViewById(R.id.sec1_t);
u=(CheckBox)findViewById(R.id.sec1_u);
v=(CheckBox)findViewById(R.id.sec1_v);
w=(CheckBox)findViewById(R.id.sec1_w);
x=(CheckBox)findViewById(R.id.sec1_x);
y=(CheckBox)findViewById(R.id.sec1_y);
z=(CheckBox)findViewById(R.id.sec1_z);
one =(Button) findViewById(R.id.next);
one.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
if(view==one){
if(TextUtils.isEmpty(name.getText().toString())) {
name.setError("Text field is empty");
return;
}
if(TextUtils.isEmpty(add.getText().toString())) {
add.setError("Text field is empty");
return;
}
if(TextUtils.isEmpty(vnum.getText().toString())) {
vnum.setError("Text field is empty");
return;
}
if(TextUtils.isEmpty(lnum.getText().toString())) {
lnum.setError("Text field is empty");
return;
}
StringBuilder violations= new StringBuilder(40);
violations.append("Sec1 ");
if(a.isChecked()){
violations.append("a");
}
if(b.isChecked()){
violations.append(",b");
}
if(c.isChecked()){
violations.append(",c");
}
if(d.isChecked()){
violations.append(",d");
}
if(e.isChecked()){
violations.append(",e");
}
if(f.isChecked()){
violations.append(",f");
}
if(g.isChecked()){
violations.append(",g");
}
if(h.isChecked()){
violations.append(",h");
}
if(i.isChecked()){
violations.append(",i");
}
if(j.isChecked()){
violations.append(",j");
}
if(k.isChecked()){
violations.append(",k");
}
if(l.isChecked()){
violations.append(",l");
}
if(m.isChecked()){
violations.append(",m");
}
if(n.isChecked()){
violations.append(",n");
}
if(o.isChecked()){
violations.append(",o");
}
if(p.isChecked()){
violations.append(",p");
}
if(q.isChecked()){
violations.append(",q");
}
if(r.isChecked()){
violations.append(",r");
}
if(t.isChecked()){
violations.append(",t");
}
if(u.isChecked()){
violations.append(",u");
}
if(v.isChecked()){
violations.append(",v");
}
if(w.isChecked()){
violations.append(",w");
}
if(x.isChecked()){
violations.append(",x");
}
if(y.isChecked()){
violations.append(",y");
}
if(z.isChecked()){
violations.append(",z");
}
Intent intent = new Intent(Violation.this, VerifyActivity.class);
intent.putExtra("fname", name.getText().toString());
intent.putExtra("address", add.getText().toString());
intent.putExtra("vnumber", vnum.getText().toString());
intent.putExtra("violation", violations.toString());
intent.putExtra("lnumber", lnum.getText().toString());
startActivity(intent);
}}
});
}
@SuppressWarnings("deprecation")
@Override
public Object onRetainNonConfigurationInstance() {
if (mAccessory != null) {
return mAccessory;
} else {
return super.onRetainNonConfigurationInstance();
}
}
@Override
public void onResume() {
super.onResume();
if (mInputStream != null && mOutputStream != null) {
//streams were not null");
return;
}
//streams were null");
UsbAccessory[] accessories = mUsbManager.getAccessoryList();
UsbAccessory accessory = (accessories == null ? null : accessories[0]);
if (accessory != null) {
if (mUsbManager.hasPermission(accessory)) {
openAccessory(accessory);
} else {
synchronized (mUsbReceiver) {
if (!mPermissionRequestPending) {
mUsbManager.requestPermission(accessory, mPermissionIntent);
mPermissionRequestPending = true;
}
}
}
} else {
// null accessory
}
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onDestroy() {
unregisterReceiver(mUsbReceiver);
super.onDestroy();
}
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
ValueMsg t = (ValueMsg) msg.obj;
// this is where you handle the data you sent. You get it by calling the getReading() function
EditText editText = (EditText)findViewById(R.id.add);
editText.setText(""+t.getReading(), TextView.BufferType.EDITABLE);
}
};
private void setupAccessory() {
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent =PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
registerReceiver(mUsbReceiver, filter);
if (getLastNonConfigurationInstance() != null) {
mAccessory = (UsbAccessory) getLastNonConfigurationInstance();
openAccessory(mAccessory);
}
}
private void openAccessory(UsbAccessory accessory) {
mFileDescriptor = mUsbManager.openAccessory(accessory);
if (mFileDescriptor != null) {
mAccessory = accessory;
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
Thread thread = new Thread(null, this, "OpenAccessoryTest");
thread.start();
//Accessory opened
} else {
// failed to open accessory
}
}
private void closeAccessory() {
try {
if (mFileDescriptor != null) {
mFileDescriptor.close();
}
} catch (IOException e) {
} finally {
mFileDescriptor = null;
mAccessory = null;
}
}
public void run() {
int ret = 0;
byte[] buffer = new byte[16384];
int i;
while (true) { // read data
try {
ret = mInputStream.read(buffer);
} catch (IOException e) {
break;
}
i = 0;
while (i < ret) {
int len = ret - i;
if (len >= 1) {
Message m = Message.obtain(mHandler);
int TagSerialNumber = (int)buffer[i];
// 'f' is the flag, use for your own logic
// value is the value from the arduino
m.obj = new ValueMsg('f', TagSerialNumber);
mHandler.sendMessage(m);
}
i += 4; // number of bytes sent from arduino
}
}
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
openAccessory(accessory);
} else {
// USB permission denied
}
}
} else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
if (accessory != null && accessory.equals(mAccessory)) {
//accessory detached
closeAccessory();
}
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.violation, 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);
}
}
这是我的arduino的代码
#include <SoftwareSerial.h>
#include <MFRC522.h> // Include of the RC522 Library
#include <SPI.h> // Used for communication via SPI with the Module
#include <Usb.h>
#include <AndroidAccessory.h>
#define SDAPIN 53 // RFID Module SDA Pin is connected to the UNO 10 Pin
#define RESETPIN 5 // RFID Module RST Pin is connected to the UNO 8 Pin
AndroidAccessory acc("Manufacturer",
"Model",
"Description",
"1.0",
"http://yoursite.com",
"0000000012345678");
byte FoundTag; // Variable used to check if Tag was found
byte ReadTag; // Variable used to store anti-collision value to read Tag information
byte TagData[MAX_LEN]; // Variable used to store Full Tag Data
byte TagSerialNumber[5]; // Variable used to store only Tag Serial Number
byte GoodTag1SerialNumber[5] = {0x7D, 0x60, 0x9B, 0xC}; // The Tag Serial number we are looking for
byte GoodTag2SerialNumber[5] = {0x39, 0xC, 0x56, 0x84}; // The Tag Serial number we are looking for
MFRC522 nfc(SDAPIN, RESETPIN); // Init of the library using the UNO pins declared above
void setup() {
SPI.begin();
Serial.begin(9600);
acc.powerOn();
// Start to find an RFID Module
Serial.println("Looking for RFID Reader");
nfc.begin();
byte version = nfc.getFirmwareVersion(); // Variable to store Firmware version of the Module
// If can't find an RFID Module
if (! version) {
Serial.print("Didn't find RC522 board.");
while(1); //Wait until a RFID Module is found
}
// If found, print the information about the RFID Module
Serial.print("Found chip RC522 ");
Serial.print("Firmware version: 0x");
Serial.println(version, HEX);
Serial.println();
}
void loop() {
String GoodTag1="False"; // Variable used to confirm good Tag Detected
String GoodTag2="False"; // Variable used to confirm good Tag Detected
// Check to see if a Tag was detected
// If yes, then the variable FoundTag will contain "MI_OK"
FoundTag = nfc.requestTag(MF1_REQIDL, TagData);
if (FoundTag == MI_OK) {
delay(200);
// Get anti-collision value to properly read information from the Tag
ReadTag = nfc.antiCollision(TagData);
memcpy(TagSerialNumber, TagData, 4); // Write the Tag information in the TagSerialNumber variable
if (acc.isConnected())
{
acc.write(TagSerialNumber, 4);
}
Serial.println("Tag detected.");
Serial.print("Serial Number: ");
for (int i = 0; i < 4; i++) { // Loop to print serial number to serial monitor
Serial.print(TagSerialNumber[i], HEX);
Serial.print(", ");
}
Serial.println("");
Serial.println();
// Check if detected Tag has the right Serial number we are looking for
for(int i=0; i < 4; i++){
if (GoodTag1SerialNumber[i] != TagSerialNumber[i]) {
break; // if not equal, then break out of the "for" loop
}
if (i == 3) { // if we made it to 4 loops then the Tag Serial numbers are matching
GoodTag1="TRUE";
}
}
for(int i=0; i < 4; i++){
if (GoodTag2SerialNumber[i] != TagSerialNumber[i]) {
break; // if not equal, then break out of the "for" loop
}
if (i == 3) { // if we made it to 4 loops then the Tag Serial numbers are matching
GoodTag2="TRUE";
}
}
}
}
请告诉我我的代码有什么问题,我应该编辑什么才能使用它。
任何帮助将不胜感激
答案 0 :(得分:2)
您永远不会正确实例化mUsbManager。您正在创建局部变量,而不是初始化类变量。
private void setupAccessory() {
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); // <--- This should not be local!
// Your other code....
}