当前位置: 首页 > 知识库问答 >
问题:

使用输出流Android Studio时崩溃

勾渝
2023-03-14

每次更改位置时,我都尝试通过蓝牙将计算出的轴承从 android 设备发送到 Arduino。当尝试使用 outPutStream 时,应用程序总是崩溃。这是代码:

public class Location_Informaion extends MainActivity implements LocationListener {

private static final String TAG = "bluetooth1";
TextView desiredDest, currentLatitude, currentLongitude, Distance, Bearing, txtArduino;
private LocationManager locationManager;
String provider, message;
private Location location;
double desLatVal, desLonVal, pi;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String macAddress = "30:14:12:02:16:78";
private ConnectedThread mConnectedThread;
Handler h;
final int RECIEVE_MESSAGE = 1;        // Status  for Handler
private StringBuilder sb = new StringBuilder();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    pi = 3.14159265359;
    setContentView(R.layout.activity_location__informaion);
    Bundle extras = getIntent().getExtras();
    String desLat = extras.getString("desLat");
    String desLon = extras.getString("desLon");
    desLatVal = Double.parseDouble(desLat);
    desLonVal = Double.parseDouble(desLon);
    desiredDest = (TextView) findViewById(R.id.desiredDestination);
    desiredDest.setText(desLat + "Lat, " + desLon + "Long.");
    message = "180";

    currentLatitude = (TextView) findViewById(R.id.currentLat);
    currentLongitude = (TextView) findViewById(R.id.currentLon);
    txtArduino = (TextView) findViewById(R.id.txtArduino);

    Distance = (TextView) findViewById(R.id.Distance);
    Bearing = (TextView) findViewById(R.id.Bearing);

    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (!enabled) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null) {
        System.out.println("Provider" + provider + "has been selected");
        currentLatitude.setText("Searching for lock");
        currentLongitude.setText("Searching for lock");
        onLocationChanged(location);
    } else {
        currentLatitude.setText("Location is not available");
        currentLongitude.setText("Location is not available");
    }
    h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case RECIEVE_MESSAGE:                                                   // if receive massage
                    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
                    }
                    //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                    break;
            }
        }
    };

    btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
    checkBTState();

}


private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
    if(Build.VERSION.SDK_INT >= 10){
        try {
            final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
            return (BluetoothSocket) m.invoke(device, MY_UUID);
        } catch (Exception e) {
            Log.e(TAG, "Could not create Insecure RFComm Connection",e);
        }
    }
    return  device.createRfcommSocketToServiceRecord(MY_UUID);
}



public void onResume() {
    super.onResume();

    locationManager.requestLocationUpdates(provider, 0, 0, this);

    Log.d(TAG, "...onResume - try connect...");

    BluetoothDevice device = btAdapter.getRemoteDevice(macAddress);

    try {
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }

    btAdapter.cancelDiscovery();

    Log.d(TAG, "...Connecting...");
    try {
        btSocket.connect();
        Log.d(TAG, "....Connection ok...");
    } catch (IOException e) {
        try {
            btSocket.close();
        } catch (IOException e2) {
            errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
        }
    }

    Log.d(TAG, "...Create Socket...");

    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.start();


}

protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);

    Log.d(TAG, "...In onPause()...");

    try     {
        btSocket.close();
    } catch (IOException e2) {
        errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
    }

}

private void checkBTState() {

    if(btAdapter==null) {
        errorExit("Fatal Error", "Bluetooth not support");
    } else {
        if (btAdapter.isEnabled()) {
            Log.d(TAG, "...Bluetooth ON...");
        } else {
            //Prompt user to turn on Bluetooth
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }
    }
}

private void errorExit(String title, String message){
    Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
    finish();
}
private class ConnectedThread extends Thread {
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;


    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;


        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {

        byte[] buffer = new byte[256];
        int bytes;


        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    public void write(String message) {
        Log.d(TAG, "...Data to send: " + message + "...");
        byte[] msgBuffer = message.getBytes();
        try {
            mmOutStream.write(msgBuffer, 0, msgBuffer.length);
        } catch (IOException e) {
            Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
        }
    }
}

@Override
public void onLocationChanged(Location location) {
    double lat = (location.getLatitude());
    double lon = (location.getLongitude());
    currentLatitude.setText(String.valueOf(lat));
    currentLongitude.setText(String.valueOf(lon));

    float R = 6371000;
    double latRad = lat / (180 / pi);
    double desLatRad = desLatVal / (180 * pi);
    double changeLat = (desLatVal - lat) / (180 * pi);
    double changeLon = (desLonVal - lon) / (180 / pi);

    double a = Math.sin(changeLat / 2) * Math.sin(changeLat / 2) +
            Math.cos(latRad) * Math.cos(desLatRad) *
                    Math.sin(changeLon / 2) * Math.sin(changeLon / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    double d = R * c / 1000;

    String distance = String.valueOf(d);

    Distance.setText(distance + "km");

    double y = Math.sin(desLonVal - lon) * Math.cos(desLatVal);
    double x = Math.cos(lat) * Math.sin(desLatVal) -
            Math.sin(lat) * Math.cos(desLatVal) * Math.cos(desLonVal - lon);
    double brng = (Math.atan2(y, x)) * 180 / pi;

    String bearing = String.valueOf(brng);

    Bearing.setText(bearing);

    mConnectedThread.write(bearing);

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {
    Toast.makeText(this, "Enable new provider " + provider, Toast.LENGTH_SHORT).show();
}

@Override
public void onProviderDisabled(String provider) {
    Toast.makeText(this, "Disabled provider " + provider, Toast.LENGTH_SHORT).show();
}

}

任何帮助都将不胜感激。

06-17 16:34:35.930 1180-11818/com.example.biggus.system_4 I/OpenGLRenderer﹕ 已初始化EGL,版本1.4 06-17 16:34:35.950 1180-11818/com.example.biggus.system_4 I/OpenGLRenderer﹕ 为上下文启用HWUI保护,

共有2个答案

太叔永新
2023-03-14

错误位于txtArduino.setText(“来自Arduino的数据:”sbprint);

您尚未使用各自的textview初始化txtArduino对象。请执行findviewByid并将相应的textview放入txtArduino对象中。

东方琪
2023-03-14

在处理程序中使用 txtArduino 之前,您没有对其进行初始化:

txtArduino.setText("Data from Arduino: " + sbprint);  
 类似资料:
  • Android应用程序经常崩溃,以下是logcat的日志。

  • 我试图在WSO2 ESB 4.9.0中创建一个API来返回JPEG类型的图像。 那么,是否可以在WSO2 ESB中为图像/JPEG消息类型关闭GZIP压缩?

  • 问题内容: 我正在尝试为命令行程序(svnadmin verify)编写包装脚本,该脚本将显示该操作的良好进度指示器。这要求我一看到包装程序的输出,就能够看到它的每一行。 我认为我只是使用, 来执行程序,然后读取其中的每一行并相应地对其进行操作。但是,当我运行以下代码时,输​​出似乎被缓冲在某处,导致它出现在两个块中,第1到332行,然后是333到439行(输出的最后一行) 在稍微了解一下子流程的

  • 本文向大家介绍java IO流 之 输出流 OutputString()的使用,包括了java IO流 之 输出流 OutputString()的使用的使用技巧和注意事项,需要的朋友参考一下 FileOutPutStream:子类,写出数据的通道   步骤:     1.获取目标文件     2.创建通道(如果原来没有目标文件,则会自动创建一个)     3.写入数据 write()     4.

  • 我在一个Kafka主题“原始数据”中获取CSV,目标是通过在另一个主题“数据”中发送具有正确时间戳(每行不同)的每行来转换它们。 null 我想通过直接设置时间戳来删除这个“内部”主题的使用,但我找不到一个方法(时间戳提取器只在消耗时间使用)。 我在文档中偶然发现了这一行: 请注意,通过调用#forward()时显式地为输出记录分配时间戳,可以在处理器API中更改description默认行为。

  • 我有一个输入流,其中包含XML数据,我想在返回输入流之前对其进行解析。 当然,我可以将流保存为字节数组,并从中返回一个新的InputStream,或者 在“myObj”上创建第二个InputStream。 但是有什么方法可以“即时”解析流吗? 编辑: 基本上,我正在寻找一种在解析后重用流的方法。在不消耗流的情况下解析流,分别在解析后重置流。 解决方案: 我找到的解决方案是使用BufferedInp

  • 问题内容: 我正在使用Jersey来实现RESTful API,该API主要是检索和提供JSON编码的数据。但是在某些情况下,我需要完成以下任务: 导出可下载的文档,例如PDF,XLS,ZIP或其他二进制文件。 检索多部分数据,例如一些JSON以及上载的XLS文件 我有一个基于页面的基于JQuery的Web客户端,该客户端创建对此Web服务的AJAX调用。目前,它不进行表单提交,而是使用GET和P

  • 我使用getStringArrayListExtra()搜索将列表从一个活动传输到另一个活动。这在第一次(从MainActivity到Diag2Activity)时运行良好,但在第二次(从Diag2Activity到SSToActivity)时应用程序崩溃。 每次我使用相同的方法:第一次活动: 第二项活动: 谁能告诉我错误可能来自哪里?提前谢谢 请在下面找到完整的代码: 主要活动。JAVA } 主