我目前正在通过蓝牙开发arduino的led控制器。该应用程序将首先启用蓝牙,并连接蓝牙模块,然后才能使用开关按钮来控制LED。我的问题是一切顺利,除非我点击ON或OFF按钮。该应用程序将停止并自动退出。
我仍然是创建Android应用程序的初学者,我真的很难用它编码。我尝试了很多教程,但仍然没有发生任何事情,截止日期已接近尾声。救命。 Pleaaaassssssseeeee。
我在MainActivity.java中有以下代码
package com.example.javac101;
.
.
.
.
public class MainActivity extends Activity {plements OnClickListener {
//BLUETOOTH
BluetoothAdapter BTAdapter;
BluetoothDevice BTDevice;
//Layout view daw
private TextView title;
//Intent
private static final int REQUEST_DEVICE_CONNECT = 1;
private static final int REQUEST_ENABLE_BLUETOOTH = 2;
//object for bluetooth command service
private BluetoothCommandService commandService = null;
private String connectedDeviceName = null;
//Message types sent from the Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final int RECIEVE_MESSAGE = 6;
//Will be used in BluetoothCommandSrvice jave file
public static final String TOAST = "toast";
public static final String DEVICENAME = "device name";
//@@@@@@@for the controller
public static final String tagStateCTRL = "Controller";
private OutputStream outStream = null;
private static final UUID myUUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static String address = "00:00:00:00:00:00"; // Insert your bluetooth devices MAC address
private StringBuilder sb = new StringBuilder();
Button btn_d1_on, btn_d1_off;
//@@@@@@@@for changing the device_1 name
TextView device1;
Button change;
EditText renameDevice;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main); gi move sa ubos sa request window
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
title = (TextView) findViewById(R.id.title_left_text); // Set up the custom title
title.setText(R.string.app_name); // Set up the custom title
title = (TextView) findViewById(R.id.title_right_text); // Set up the custom title
//Button openButton = (Button)findViewById(R.id.open);
//@@@@@@@@@@for the controller
btn_d1_on = (Button) findViewById(R.id.device1_on);
btn_d1_off = (Button) findViewById(R.id.device1_off);
//@@@@@@@@for changing the device_1 name
device1 = (TextView)findViewById(R.id.device1);
change = (Button)findViewById(R.id.buttonTest);
renameDevice = (EditText)findViewById(R.id.editTest);
change.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String change_device1 = renameDevice.getText().toString();
device1.setText(change_device1);
}
});
// AUTO REQUEST OF ENABLING THE BLUETOOTH
BTAdapter = BluetoothAdapter.getDefaultAdapter();
//A code that will detect if BT is enabled otherwise will require it.
if (BTAdapter == null)
{
//Toast.makeText(context, text, duration)
Toast.makeText(this, "No Bluetooth adapter is available.", Toast.LENGTH_LONG).show();
finish();
return;
}
//@@@@@@@@@@for the controller
btn_d1_on.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//sendData("1");
//Toast msg = Toast.makeText(getBaseContext(), "The device is now On", Toast.LENGTH_SHORT);
//msg.show()
btn_d1_on.setEnabled(false);
sendData("1");
}
});
//@@@@@@@@@@for the controller
btn_d1_off.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//sendData("0");
//Toast msg = Toast.makeText(getBaseContext(), "The device is now On", Toast.LENGTH_SHORT);
//msg.show();
btn_d1_off.setEnabled(false);
sendData("0");
}
});
}
@Override
protected void onStart() {
super.onStart();
//Requesting Bluetooth automatically when its not yet enabled.
if (!BTAdapter.isEnabled())
{
Intent enableIntent = new Intent (BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivityForResult(enableIntent, 0);
startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
}
else
{
if (commandService == null)
setupCommand();
}
}
//Will automatically enable and request to be discoverable for 500 sec.gi comment since dili pa sure kung needed pa ba nga ma discoverable
//if (BTAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)
//{
//Intent discoverableIntent = new Intent (BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);
//startActivity(discoverableIntent);
//}
@Override
protected void onResume() {
super.onResume();
if (commandService != null)
{
if (commandService.getState() == BluetoothCommandService.stateNothing)
{
commandService.start();
}
}
}
private void setupCommand()
{
commandService = new BluetoothCommandService(this, bluetoothHandler);
}
@Override
protected void onDestroy()
{
super.onDestroy();
if (commandService != null)
commandService.stop();
}
private void ensureDiscoverable()
{
//Get the current Bluetooth scan mode of the local Bluetooth adapter. The Bluetooth scan mode determines if the local adapter is connectable and/or discoverable from remote Bluetooth devices.
if (BTAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)
{
Intent ensureDiscoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
ensureDiscoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(ensureDiscoverableIntent);
}
}
//This gets information back from the "BluetoothChatService"/"BluetoothCommandService"
//@SuppressLint("HandlerLeak")
//private final Handler bluetoothHandler = new Handler(new Handler.Callback()
public final Handler bluetoothHandler = new Handler()
{
@Override
public void handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case MESSAGE_STATE_CHANGE:
switch (msg.arg1)
{
case BluetoothCommandService.stateConnected:
title.setText(R.string.title_connectedTo);
title.append(connectedDeviceName);
break;
case BluetoothCommandService.stateConnecting:
title.setText(R.string.title_connecting);
break;
case BluetoothCommandService.stateListen:
case BluetoothCommandService.stateNothing:
title.setText(getString(R.string.title_notConnected));
break;
}
break;
case MESSAGE_DEVICE_NAME:
connectedDeviceName = msg.getData().getString(DEVICENAME);
Toast.makeText(getApplicationContext(), "Connected to " + connectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
break;
case RECIEVE_MESSAGE: // if receive message
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
//String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
//txtArduino.setText("Data from Arduino: " + sbprint); // update TextView
//1/4/14
btn_d1_on.setEnabled(true);
btn_d1_off.setEnabled(true);
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
//return false;
}
};
//});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_DEVICE_CONNECT:
// When DeviceList Activity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = BTAdapter.getRemoteDevice(address);
// Attempt to connect to the device
commandService.connect(device);
}
break;
case REQUEST_ENABLE_BLUETOOTH:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupCommand();
} else {
// User did not enable Bluetooth or an error occured
Toast.makeText(this, R.string.notEnabledBluetooth, Toast.LENGTH_SHORT).show();
finish();
}
}
}
@Override
//Creating an Option Menu for connectivity and discoverability of a BT device
public boolean onCreateOptionsMenu(Menu menu)
{
//MenuInflater is a class
MenuInflater OptionMenu = getMenuInflater();
//OptionMenu.inflate(menuRes, menu)
OptionMenu.inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.connect:
Intent serverIntent = new Intent(this, DeviceList.class);
//this.startActivityForResult(serverIntent, REQUEST_DEVICE_CONNECT);
startActivityForResult(serverIntent, REQUEST_DEVICE_CONNECT);
return true;
case R.id.discoverable:
ensureDiscoverable();
return true;
//case R.id.abouts:
//Intent intentabouts = new Intent(this,abouts.class);
//return true;
//default:
//return super.onOptionsItemSelected(item);
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
commandService.write(BluetoothCommandService.VOL_UP);
return true;
}
else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
commandService.write(BluetoothCommandService.VOL_DOWN);
return true;
}
return super.onKeyDown(keyCode, event);
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
private void sendData(String message)
//public void sendData(String message)
{
byte[] msgBuffer = message.getBytes();
Log.d(tagStateCTRL, "...Sending data: " + message + "...");
try {
outStream.write(msgBuffer);
}
catch (IOException e){
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + myUUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
private void errorExit(String title, String message){
Toast msg = Toast.makeText(getBaseContext(),
title + " - " + message, Toast.LENGTH_SHORT);
msg.show();
finish();
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
}
这就是LogCat显示的内容:
01-04 19:20:48.786: E/BluetoothCommandService(9663): accept() failed
01-04 19:20:48.786: E/BluetoothCommandService(9663): java.io.IOException: [JSR82] accept: Connection is not created (failed or aborted).
01-04 19:20:48.786: E/BluetoothCommandService(9663): at android.bluetooth.BluetoothSocket.accept(BluetoothSocket.java:604)
01-04 19:20:48.786: E/BluetoothCommandService(9663): at android.bluetooth.BluetoothServerSocket.accept(BluetoothServerSocket.java:113)
01-04 19:20:48.786: E/BluetoothCommandService(9663): at android.bluetooth.BluetoothServerSocket.accept(BluetoothServerSocket.java:99)
01-04 19:20:48.786: E/BluetoothCommandService(9663): at com.example.javac101.BluetoothCommandService$AcceptThread.run(BluetoothCommandService.java:455)
01-04 19:20:53.819: E/AndroidRuntime(9663): FATAL EXCEPTION: main
01-04 19:20:53.819: E/AndroidRuntime(9663): java.lang.NullPointerException
01-04 19:20:53.819: E/AndroidRuntime(9663): at com.example.javac101.MainActivity.sendData(MainActivity.java:377)
01-04 19:20:53.819: E/AndroidRuntime(9663): at com.example.javac101.MainActivity.access$4(MainActivity.java:369)
01-04 19:20:53.819: E/AndroidRuntime(9663): at com.example.javac101.MainActivity$3.onClick(MainActivity.java:142)
01-04 19:20:53.819: E/AndroidRuntime(9663): at android.view.View.performClick(View.java:4212)
01-04 19:20:53.819: E/AndroidRuntime(9663): at android.view.View$PerformClick.run(View.java:17476)
01-04 19:20:53.819: E/AndroidRuntime(9663): at android.os.Handler.handleCallback(Handler.java:800)
01-04 19:20:53.819: E/AndroidRuntime(9663): at android.os.Handler.dispatchMessage(Handler.java:100)
01-04 19:20:53.819: E/AndroidRuntime(9663): at android.os.Looper.loop(Looper.java:194)
01-04 19:20:53.819: E/AndroidRuntime(9663): at android.app.ActivityThread.main(ActivityThread.java:5371)
01-04 19:20:53.819: E/AndroidRuntime(9663): at java.lang.reflect.Method.invokeNative(Native Method)
01-04 19:20:53.819: E/AndroidRuntime(9663): at java.lang.reflect.Method.invoke(Method.java:525)
01-04 19:20:53.819: E/AndroidRuntime(9663): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
01-04 19:20:53.819: E/AndroidRuntime(9663): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
01-04 19:20:53.819: E/AndroidRuntime(9663): at dalvik.system.NativeStart.main(Native Method)
希望你能帮助我。请。