在 android 应用中调用 Onclick 侦听器方法之外的方法
calling a method outside Onclick listener method in android app
我正在使用以下教程通过蓝牙向 arduino 发送消息。 (参见 LEDOnOff.java 代码)
http://digitalhacksblog.blogspot.in/2012/05/arduino-to-android-turning-led-on-and.html
我想更改此代码,以便在应用程序启动后立即调用 sendData()
方法,但是当我在按钮的 onClick 侦听器外部调用 sendData()
方法时,应用程序崩溃以下错误。(我在 onCreate
方法中调用了 sendData("1")
;在按钮的 onClick 侦听器之外)。
我使用的代码是:
package com.example.ledonoff;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
public class LEDOnOff extends Activity {
private static final String TAG = "LEDOnOff";
Button btnOn, btnOff;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your bluetooth devices MAC address
private static String address = "20:13:10:16:09:19";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "In onCreate()");
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
sendData("1"); //this line is added by me and i have removed onclick method
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "...In onResume - Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting to Remote...");
try {
btSocket.connect();
Log.d(TAG, "...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Creating Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
private void errorExit(String title, String message){
Toast msg = Toast.makeText(getBaseContext(),
title + " - " + message, Toast.LENGTH_SHORT);
msg.show();
finish();
}
public void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...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 on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
}
**Log-cat :**
02-14 10:30:36.002: I/SELinux(1886): Function: selinux_android_load_priority [0], There is no sepolicy file.
02-14 10:30:36.002: I/SELinux(1886):
02-14 10:30:36.002: I/SELinux(1886): Function: selinux_android_load_priority [1], There is no sepolicy version file.
02-14 10:30:36.002: I/SELinux(1886):
02-14 10:30:36.002: I/SELinux(1886): Function: selinux_android_load_priority , priority version is VE=SEPF_SM-G7102_4.4.2_0033
02-14 10:30:36.002: I/SELinux(1886):
02-14 10:30:36.002: I/SELinux(1886):
02-14 10:30:36.002: I/SELinux(1886): selinux_android_seapp_context_reload: seapp_contexts file is loaded from /seapp_contexts
02-14 10:30:36.002: E/SELinux(1886): [DEBUG] seapp_context_lookup: seinfoCategory = default
02-14 10:30:36.002: E/dalvikvm(1886): >>>>> Normal User
02-14 10:30:36.002: E/dalvikvm(1886): >>>>> com.example.ledonoff [ userId:0 | appId:10288 ]
02-14 10:30:36.002: E/SELinux(1886): [DEBUG] seapp_context_lookup: seinfoCategory = default
02-14 10:30:36.002: D/dalvikvm(1886): Late-enabling CheckJNI
02-14 10:30:36.162: D/LEDOnOff(1886): In onCreate()
02-14 10:30:36.292: D/LEDOnOff(1886): ...Bluetooth is enabled...
02-14 10:30:36.292: D/LEDOnOff(1886): ...Sending data: 1...
02-14 10:30:36.292: D/AndroidRuntime(1886): Shutting down VM
02-14 10:30:36.292: W/dalvikvm(1886): threadid=1: thread exiting with uncaught exception (group=0x4181eda0)
02-14 10:30:36.292: E/AndroidRuntime(1886): FATAL EXCEPTION: main
02-14 10:30:36.292: E/AndroidRuntime(1886): Process: com.example.ledonoff, PID: 1886
02-14 10:30:36.292: E/AndroidRuntime(1886): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ledonoff/com.example.ledonoff.LEDOnOff}: java.lang.NullPointerException
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.ActivityThread.access0(ActivityThread.java:172)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.os.Handler.dispatchMessage(Handler.java:102)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.os.Looper.loop(Looper.java:146)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.ActivityThread.main(ActivityThread.java:5653)
02-14 10:30:36.292: E/AndroidRuntime(1886): at java.lang.reflect.Method.invokeNative(Native Method)
02-14 10:30:36.292: E/AndroidRuntime(1886): at java.lang.reflect.Method.invoke(Method.java:515)
02-14 10:30:36.292: E/AndroidRuntime(1886): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
02-14 10:30:36.292: E/AndroidRuntime(1886): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
02-14 10:30:36.292: E/AndroidRuntime(1886): at dalvik.system.NativeStart.main(Native Method)
02-14 10:30:36.292: E/AndroidRuntime(1886): Caused by: java.lang.NullPointerException
02-14 10:30:36.292: E/AndroidRuntime(1886): at com.example.ledonoff.LEDOnOff.sendData(LEDOnOff.java:180)
02-14 10:30:36.292: E/AndroidRuntime(1886): at com.example.ledonoff.LEDOnOff.onCreate(LEDOnOff.java:52)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.Activity.performCreate(Activity.java:5541)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
02-14 10:30:36.292: E/AndroidRuntime(1886): ... 11 more
任何人都可以帮助我这样做吗?告诉我是否有任何其他方法可以实现我的想法。
onCreate() 在 onResume() 之前调用。当前您的外流编码方式为空。查看 Android 生命周期。
我正在使用以下教程通过蓝牙向 arduino 发送消息。 (参见 LEDOnOff.java 代码)
http://digitalhacksblog.blogspot.in/2012/05/arduino-to-android-turning-led-on-and.html
我想更改此代码,以便在应用程序启动后立即调用 sendData()
方法,但是当我在按钮的 onClick 侦听器外部调用 sendData()
方法时,应用程序崩溃以下错误。(我在 onCreate
方法中调用了 sendData("1")
;在按钮的 onClick 侦听器之外)。
我使用的代码是:
package com.example.ledonoff;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
public class LEDOnOff extends Activity {
private static final String TAG = "LEDOnOff";
Button btnOn, btnOff;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your bluetooth devices MAC address
private static String address = "20:13:10:16:09:19";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "In onCreate()");
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
sendData("1"); //this line is added by me and i have removed onclick method
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "...In onResume - Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting to Remote...");
try {
btSocket.connect();
Log.d(TAG, "...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Creating Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
private void errorExit(String title, String message){
Toast msg = Toast.makeText(getBaseContext(),
title + " - " + message, Toast.LENGTH_SHORT);
msg.show();
finish();
}
public void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...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 on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
}
**Log-cat :**
02-14 10:30:36.002: I/SELinux(1886): Function: selinux_android_load_priority [0], There is no sepolicy file.
02-14 10:30:36.002: I/SELinux(1886):
02-14 10:30:36.002: I/SELinux(1886): Function: selinux_android_load_priority [1], There is no sepolicy version file.
02-14 10:30:36.002: I/SELinux(1886):
02-14 10:30:36.002: I/SELinux(1886): Function: selinux_android_load_priority , priority version is VE=SEPF_SM-G7102_4.4.2_0033
02-14 10:30:36.002: I/SELinux(1886):
02-14 10:30:36.002: I/SELinux(1886):
02-14 10:30:36.002: I/SELinux(1886): selinux_android_seapp_context_reload: seapp_contexts file is loaded from /seapp_contexts
02-14 10:30:36.002: E/SELinux(1886): [DEBUG] seapp_context_lookup: seinfoCategory = default
02-14 10:30:36.002: E/dalvikvm(1886): >>>>> Normal User
02-14 10:30:36.002: E/dalvikvm(1886): >>>>> com.example.ledonoff [ userId:0 | appId:10288 ]
02-14 10:30:36.002: E/SELinux(1886): [DEBUG] seapp_context_lookup: seinfoCategory = default
02-14 10:30:36.002: D/dalvikvm(1886): Late-enabling CheckJNI
02-14 10:30:36.162: D/LEDOnOff(1886): In onCreate()
02-14 10:30:36.292: D/LEDOnOff(1886): ...Bluetooth is enabled...
02-14 10:30:36.292: D/LEDOnOff(1886): ...Sending data: 1...
02-14 10:30:36.292: D/AndroidRuntime(1886): Shutting down VM
02-14 10:30:36.292: W/dalvikvm(1886): threadid=1: thread exiting with uncaught exception (group=0x4181eda0)
02-14 10:30:36.292: E/AndroidRuntime(1886): FATAL EXCEPTION: main
02-14 10:30:36.292: E/AndroidRuntime(1886): Process: com.example.ledonoff, PID: 1886
02-14 10:30:36.292: E/AndroidRuntime(1886): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ledonoff/com.example.ledonoff.LEDOnOff}: java.lang.NullPointerException
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.ActivityThread.access0(ActivityThread.java:172)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.os.Handler.dispatchMessage(Handler.java:102)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.os.Looper.loop(Looper.java:146)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.ActivityThread.main(ActivityThread.java:5653)
02-14 10:30:36.292: E/AndroidRuntime(1886): at java.lang.reflect.Method.invokeNative(Native Method)
02-14 10:30:36.292: E/AndroidRuntime(1886): at java.lang.reflect.Method.invoke(Method.java:515)
02-14 10:30:36.292: E/AndroidRuntime(1886): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
02-14 10:30:36.292: E/AndroidRuntime(1886): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
02-14 10:30:36.292: E/AndroidRuntime(1886): at dalvik.system.NativeStart.main(Native Method)
02-14 10:30:36.292: E/AndroidRuntime(1886): Caused by: java.lang.NullPointerException
02-14 10:30:36.292: E/AndroidRuntime(1886): at com.example.ledonoff.LEDOnOff.sendData(LEDOnOff.java:180)
02-14 10:30:36.292: E/AndroidRuntime(1886): at com.example.ledonoff.LEDOnOff.onCreate(LEDOnOff.java:52)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.Activity.performCreate(Activity.java:5541)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
02-14 10:30:36.292: E/AndroidRuntime(1886): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
02-14 10:30:36.292: E/AndroidRuntime(1886): ... 11 more
任何人都可以帮助我这样做吗?告诉我是否有任何其他方法可以实现我的想法。
onCreate() 在 onResume() 之前调用。当前您的外流编码方式为空。查看 Android 生命周期。