应用程序崩溃的原因尺蠖。prepare()在beginlistendata()函数 [英] App crashed due to looper.prepare() in the beginlistendata() function

查看:226
本文介绍了应用程序崩溃的原因尺蠖。prepare()在beginlistendata()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 公共类BluetoothActivity延伸活动{//创建ACTION_FOUND一个BroadcastReceiver
私人最终广播接收器广播接收器=新的广播接收器(){
    公共无效的onReceive(上下文的背景下,意图意图){
        字符串行动= intent.getAction();
        //每当远程蓝牙设备发现
        如果(BluetoothDevice.ACTION_FOUND.equals(动作)){
            //从意向获取BluetoothDevice类对象
            BluetoothDevice类BluetoothDevice类= intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            //添加名称和地址到一个数组适配器在ListView显示
            adapter.add(bluetoothDevice.getName()+\\ n
                    + bluetoothDevice.getAddress());
        }
    }
};
//宣言
TextView的myLabel;
螺纹的WorkerThread;
字节[] readBuffer;
INT readBufferPosition;
挥发性布尔stopWorker;
私人BluetoothAdapter mBluetoothAdapter;
私人的ListView列表视图;
私人ArrayAdapter适配器;
私人切换按钮切换按钮;
私有静态最终诠释REQUEST_ENABLE_BT = 0;
私有静态最终诠释DISCOVERABLE_DURATION = 0;
私有静态最终诠释DISCOVERABLE_BT_REQUEST_ code = 2;
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.bluetooth_main);
    切换按钮=(切换按钮)findViewById(R.id.toggleButton);
    列表视图=(ListView控件)findViewById(R.id.listView);
    // ListView项点击监听器
    listview.setOnItemClickListener(新AdapterView.OnItemClickListener(){
        @覆盖
        公共无效onItemClick(适配器视图<>母公司,观景,
                                INT位置,长的id){
            // ListView中单击项目价值
            字符串itemValue =(字符串)listview.getItemAtPosition(位置);
            Toast.makeText(getApplicationContext(),点击,Toast.LENGTH_LONG).show();
            字符串MAC = itemValue.substring(itemValue.length() - 17);
            BluetoothDevice类BluetoothDevice类= mBluetoothAdapter.getRemoteDevice(MAC);
            //启动在单独的线程的连接请求            ConnectingThread T =新ConnectingThread(BluetoothDevice类);
            t.start();
        }
    });
    适配器=新ArrayAdapter
            (这一点,android.R.layout.simple_list_item_1);
    listview.setAdapter(适配器);    //验证支持蓝牙设备上
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    //设备不支持蓝牙
    如果(mBluetoothAdapter == NULL){
    }
} //结束的OnCreate公共无效onToggle(查看视图){
    adapter.clear();    如果(toggleButton.isChecked()){
        //启用蓝牙
        如果(!mBluetoothAdapter.isEnabled()){
            意图enableBtIntent =新意图(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
            Toast.makeText(getApplicationContext(),变身的,Toast.LENGTH_LONG).show();
        }
        其他
        {
            Toast.makeText(getApplicationContext(),已在Toast.LENGTH_LONG).show();
            //要发现远程蓝牙设备
            discoverDevices();
            //使本地设备的其他设备发现
            makeDiscoverable();
        }
    } //如果1月底    其他{
        //关闭蓝牙
        mBluetoothAdapter.disable();
        adapter.clear();
        Toast.makeText(getApplicationContext(),已关闭,Toast.LENGTH_LONG).show();
    }
}公共无效的onActivityResult(INT申请code,INT结果code,意图数据){
    如果(要求code == REQUEST_ENABLE_BT){
        //蓝牙成功启用!
        如果(结果code == Activity.RESULT_OK){
            Toast.makeText(getApplicationContext(),蓝牙技术现在已启用,Toast.LENGTH_SHORT).show();            //使本地设备的其他设备发现
            makeDiscoverable();
            //要发现远程蓝牙设备
            Log.e(calldiscover,FUNC);
            discoverDevices();
            Log.e(发现,设备);
            //启动一个线程来创建服务器套接字监听
            //为连接请求
            Log.e(listenthread,listenthread);
            ListeningThread T =新ListeningThread();
            Log.e(呼,t.start);
            t.start();
            Log.e(t.start,过);
        }
        其他{
            // RESULT_CANCELED如用户拒绝
            Toast.makeText(getApplicationContext(),未启用蓝牙。
                    Toast.LENGTH_SHORT).show();            //关闭切换按钮
            toggleButton.setChecked(假);
        }    } //如果1月底
}
保护无效discoverDevices(){
    //要扫描远程蓝牙设备
    如果(mBluetoothAdapter.startDiscovery()){Log.e(盘,打印);
        Toast.makeText(getApplicationContext(),发现其他蓝牙设备......,Toast.LENGTH_SHORT).show();
    }
    其他{
        Log.e(印刷,印刷);
        Toast.makeText(getApplicationContext(),发现无法启动。Toast.LENGTH_SHORT).show();
    }
}保护无效makeDiscoverable(){
    //使本地设备可发现
    意向discoverableIntent =新
            意图(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,DISCOVERABLE_DURATION);
    startActivityForResult(discoverableIntent,DISCOVERABLE_BT_REQUEST_ code);
}@覆盖
保护无效onResume(){
    super.onResume();
    //注册ACTION_FOUND的广播接收器
    IntentFilter的过滤器=新的IntentFilter(BluetoothDevice.ACTION_FOUND);
    this.registerReceiver(广播接收器,过滤器);
}@覆盖
保护无效的onPause(){
    super.onPause();
    this.unregisterReceiver(广播接收器);
}@覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
    //充气菜单;如果是present这增加了项目操作栏。
    。getMenuInflater()膨胀(R.menu.menu_main,菜单);
    返回true;
}@覆盖
公共布尔onOptionsItemSelected(菜单项项){
    //处理动作栏项目点击这里。操作栏会
    //自动处理上点击主页/向上按钮,只要
    //你在AndroidManifest.xml中指定一个父活动。
    INT ID = item.getItemId();    // noinspection SimplifiableIfStatement
    如果(ID == R.id.action_settings){
        返回true;
    }    返回super.onOptionsItemSelected(项目);
}
私有类ListeningThread继承Thread {
    私人最终BluetoothServerSocket bluetoothServerSocket;    公共ListeningThread(){
        BluetoothServerSocket温度= NULL;
        尝试{
            TEMP = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(的getString(R.string.app_name),UUID);        }赶上(IOException异常五){
            e.printStackTrace();
        }
        bluetoothServerSocket =温度;
    }    公共无效的run(){
        的BluetoothSocket的BluetoothSocket;
        //一边听直到返回的BluetoothSocket这将阻止
        //或者发生异常
        而(真){
            尝试{
                Log.e(外衣,过);
                的BluetoothSocket = bluetoothServerSocket.accept();
                Log.e(BT,接受);
            }赶上(IOException异常五){Log.e(错误,抓);
                打破;
            }
            //如果连接被接受
            如果(的BluetoothSocket!= NULL){
                Log.e(连接被接受的,过);
                BluetoothActivity.this.runOnUiThread(新的Runnable(){                    @覆盖
                    公共无效的run(){
                        Toast.makeText(BluetoothActivity.this!连接,Toast.LENGTH_SHORT).show();                    }
                });                //管理在一个单独的线程连接                尝试{Log.e(callserver,关闭);
                    bluetoothServerSocket.close();
                }赶上(IOException异常五){
                    e.printStackTrace();
                }
                打破;
            }
        } //而结束
    }    //取消监听套接字,并终止线程
    公共无效取消(){
        尝试{Log.e(取消,插座);
            bluetoothServerSocket.close();
        }赶上(IOException异常五){
            e.printStackTrace();
        }
    }
} //建立一个客户端连接
        私有类ConnectingThread继承Thread {
             的OutputStream mmOutputStream;
             InputStream的mmInputStream;
            私人最终的BluetoothSocket的BluetoothSocket;
            私人最终BluetoothDevice类BluetoothDevice类;            公共ConnectingThread(BluetoothDevice类设备){                温度的BluetoothSocket = NULL;
                BluetoothDevice类=设备;                //获取的BluetoothSocket与给定的BluetoothDevice类连接
                尝试{Log.e(click6,click6);
                    TEMP = bluetoothDevice.createRfcommSocketToServiceRecord(UUID);
                }赶上(IOException异常五){
                    e.printStackTrace();
                }
                的BluetoothSocket =温度;
            }            公共无效的run(){
                //取消任何发现,因为它会连接放缓
                Log.e(click7,click7);
                mBluetoothAdapter.cancelDiscovery();
                Log.e(click8,click8);                尝试{                    //这将阻止,直到它连接到该设备成功
                    //通过的BluetoothSocket或抛出一个异常
                    bluetoothSocket.connect();
                    mmOutputStream = bluetoothSocket.getOutputStream();
                    mmInputStream = bluetoothSocket.getInputStream();
                    beginListenForData();
                    Log.e(listendata,lsitendata);
                    BluetoothActivity.this.runOnUiThread(新的Runnable(){                        @覆盖
                        公共无效的run(){
                            Toast.makeText(BluetoothActivity.this,跟设备!,Toast.LENGTH_SHORT).show();                        }
                    });
                    Log.e(click9,click9);
                }赶上(IOException异常的ConnectException){
                    connectException.printStackTrace();
                    尝试{
                        bluetoothSocket.close();
                        Log.e(click6,blueclose);
                    }赶上(IOException异常closeException){
                        closeException.printStackTrace();
                    }
                }
            }
     无效beginListenForData()
            {
                最后的处理程序处理程序=新的处理程序();
                最后一个字节的分隔符= 10; //这是ASCII code为一个换行符                stopWorker = FALSE;
                readBufferPosition = 0;
                readBuffer =新字节[1024]; /​​/它采用了1024字节长缓冲器,因为它不具有知道输入数据流的长度的任何方式。
                的WorkerThread =新主题(新的Runnable()
                {
                    公共无效的run()
                    {
                        而(Thread.currentThread()isInterrupted()及!&放大器;!stopWorker)
                        {
                            尝试
                            {
                                INT参考bytesAvailable = mmInputStream.available();
                                如果(参考bytesAvailable大于0)
                                {
                                    字节[] = packetBytes新的字节[方bytesAvailable]
                                    mmInputStream.read(packetBytes);
                                    的for(int i = 0; I<方bytesAvailable;我++)
                                    {
                                        字节B = packetBytes [I]
                                        如果(二==分隔符)
                                        {
                                            字节[] EN codedBytes =新的字节[readBufferPosition]
                                            System.arraycopy(readBuffer,0,EN codedBytes,0,EN codedBytes.length);
                                            最终字符串数据=新的String(EN codedBytes,US-ASCII);
                                            readBufferPosition = 0;                                            handler.post(新的Runnable()
                                            {
                                                公共无效的run()
                                                {                                                    myLabel.setText(数据);
                                                }
                                            });                                        }
                                        其他
                                        {
                                            readBuffer [readBufferPosition ++] = B;
                                        }
                                    }
                                }
                            }
                            赶上(IOException异常前)
                            {
                                stopWorker = TRUE;
                            }
                        }
                    }
                });            workerThread.start();
        }

喜应用程序崩溃时我尝试调用beginListenForData();不能内螺纹创建处理程序中的错误状态已经不叫活套。prepare()

有谁知道自己做错了什么?我是新来的机器人。请帮忙。

Bluetooth.xml

 <?XML版本=1.0编码=UTF-8&GT?;
<的RelativeLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:paddingLeft =@扪/ activity_horizo​​ntal_margin
    机器人:paddingRight =@扪/ activity_horizo​​ntal_margin
    机器人:paddingTop =@扪/ activity_vertical_margin
    机器人:paddingBottom会=@扪/ activity_vertical_margin
    工具:上下文=BluetoothActivity。>    <切换按钮
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:纹元=关闭蓝牙
        机器人:textOff =打开蓝牙
        机器人:ID =@ + ID /切换按钮
        安卓的onClick =onToggle
        机器人:layout_alignParentTop =真
        机器人:layout_alignParentStart =真/>    < ListView控件
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:ID =@ + ID /的ListView
        机器人:layout_alignParentStart =真
        机器人:layout_marginStart =76dp
        机器人:layout_below =@ + ID /切换按钮/>    <的TextView
        机器人:ID =@ + /标记
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文字=请在此处键入
        机器人:layout_below =@ + ID /切换按钮
        机器人:layout_centerHorizo​​ntal =真
        机器人:layout_marginTop =66dp/>
< / RelativeLayout的>


解决方案

试试这个里面的 beginListenForData()

替换

 最后的处理程序处理程序=新的处理程序();

有了这个

 最后的处理程序处理程序=新的处理程序(Looper.getMainLooper());

    public class BluetoothActivity extends Activity {

// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // Whenever a remote Bluetooth device is found
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // Add the name and address to an array adapter to show in a ListView
            adapter.add(bluetoothDevice.getName() + "\n"
                    + bluetoothDevice.getAddress());
        }
    }
};
//declaration
TextView myLabel;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
volatile boolean stopWorker;
private BluetoothAdapter mBluetoothAdapter;
private ListView listview;
private ArrayAdapter adapter;
private ToggleButton toggleButton;
private static final int REQUEST_ENABLE_BT =0;
private static final int DISCOVERABLE_DURATION = 0;
private static final int DISCOVERABLE_BT_REQUEST_CODE = 2;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bluetooth_main);
    toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
    listview = (ListView) findViewById(R.id.listView);
    // ListView Item Click Listener
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            // ListView Clicked item value
            String  itemValue = (String) listview.getItemAtPosition(position);
            Toast.makeText(getApplicationContext(), "clicked", Toast.LENGTH_LONG).show();
            String MAC = itemValue.substring(itemValue.length() - 17);
            BluetoothDevice bluetoothDevice = mBluetoothAdapter.getRemoteDevice(MAC);
            // Initiate a connection request in a separate thread

            ConnectingThread t = new ConnectingThread(bluetoothDevice);
            t.start();
        }
    });


    adapter = new ArrayAdapter
            (this,android.R.layout.simple_list_item_1);
    listview.setAdapter(adapter);



    //verify bluetooth is supported on the device
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    // Device does not support Bluetooth
    if (mBluetoothAdapter == null) {
    }


}//end oncreate

public void onToggle(View view) {
    adapter.clear();

    if (toggleButton.isChecked()){
        //enable bluetooth
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            Toast.makeText(getApplicationContext(), "Turned on", Toast.LENGTH_LONG).show();
        }
        else
        {
            Toast.makeText(getApplicationContext(),"Already on", Toast.LENGTH_LONG).show();
            //To discover remote Bluetooth devices
            discoverDevices();
            // Make local device discoverable by other devices
            makeDiscoverable();
        }
    }//end of 1st if

    else{
        //turn off bluetooth
        mBluetoothAdapter.disable();
        adapter.clear();
        Toast.makeText(getApplicationContext(),"Turned off" ,Toast.LENGTH_LONG).show();
    }
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_ENABLE_BT) {
        // Bluetooth successfully enabled!
        if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(getApplicationContext(), "Bluetooth is now enabled.",Toast.LENGTH_SHORT).show();

            // Make local device discoverable by other devices
            makeDiscoverable();
            // To discover remote Bluetooth devices
            Log.e("calldiscover", "func");
            discoverDevices();
            Log.e("Discover", "device");
            // Start a thread to create a  server socket to listen
            // for connection request
            Log.e("listenthread", "listenthread");
            ListeningThread t = new ListeningThread();
            Log.e("call", "t.start");
            t.start();
            Log.e("t.start", "over");
        }
        else {
            // RESULT_CANCELED as user refused
            Toast.makeText(getApplicationContext(), "Bluetooth is not enabled.",
                    Toast.LENGTH_SHORT).show();

            // Turn off togglebutton
            toggleButton.setChecked(false);
        }

    }//end of 1st if
}
protected void discoverDevices(){
    // To scan for remote Bluetooth devices
    if (mBluetoothAdapter.startDiscovery()) {Log.e("disc", "print");
        Toast.makeText(getApplicationContext(), "Discovering other bluetooth devices...", Toast.LENGTH_SHORT).show();
    }
    else {
        Log.e("print", "print");
        Toast.makeText(getApplicationContext(), "Discovery failed to start.", Toast.LENGTH_SHORT).show();
    }
}

protected void makeDiscoverable(){
    // Make local device discoverable
    Intent discoverableIntent = new
            Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION);
    startActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
}

@Override
protected void onResume() {
    super.onResume();
    // Register the BroadcastReceiver for ACTION_FOUND
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    this.registerReceiver(broadcastReceiver, filter);
}

@Override
protected void onPause() {
    super.onPause();
    this.unregisterReceiver(broadcastReceiver);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}




private class ListeningThread extends Thread {
    private final BluetoothServerSocket bluetoothServerSocket;

    public ListeningThread() {
        BluetoothServerSocket temp = null;
        try {
            temp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(getString(R.string.app_name), uuid);

        } catch (IOException e) {
            e.printStackTrace();
        }
        bluetoothServerSocket = temp;
    }

    public void run() {
        BluetoothSocket bluetoothSocket;
        // This will block while listening until a BluetoothSocket is returned
        // or an exception occurs
        while (true) {
            try {
                Log.e("while", "over");
                bluetoothSocket = bluetoothServerSocket.accept();
                Log.e("bt", "accept");
            } catch (IOException e) {Log.e("error", "catch");
                break;
            }
            // If a connection is accepted
            if (bluetoothSocket != null) {
                Log.e("connection is accepted", "over");
                BluetoothActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(BluetoothActivity.this, "Connected!", Toast.LENGTH_SHORT).show();

                    }
                });

                // Manage the connection in a separate thread

                try {Log.e("callserver", "close");
                    bluetoothServerSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }//end of while
    }

    // Cancel the listening socket and terminate the thread
    public void cancel() {
        try {Log.e("cancel", "socket");
            bluetoothServerSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 //Setting Up a Connecting Client
        private class ConnectingThread extends Thread {
             OutputStream mmOutputStream;
             InputStream mmInputStream;
            private final BluetoothSocket bluetoothSocket;
            private final BluetoothDevice bluetoothDevice;

            public ConnectingThread(BluetoothDevice device) {

                BluetoothSocket temp = null;
                bluetoothDevice = device;

                // Get a BluetoothSocket to connect with the given BluetoothDevice
                try { Log.e("click6", "click6");
                    temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                bluetoothSocket = temp;
            }

            public void run() {
                // Cancel any discovery as it will slow down the connection
                Log.e("click7", "click7");
                mBluetoothAdapter.cancelDiscovery();
                Log.e("click8", "click8");

                try {

                    // This will block until it succeeds in connecting to the device
                    // through the bluetoothSocket or throws an exception
                    bluetoothSocket.connect();
                    mmOutputStream = bluetoothSocket.getOutputStream();
                    mmInputStream = bluetoothSocket.getInputStream();
                    beginListenForData();
                    Log.e("listendata", "lsitendata");
                    BluetoothActivity.this.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(BluetoothActivity.this, "Connected with Device!", Toast.LENGTH_SHORT).show();

                        }
                    });
                    Log.e("click9", "click9");
                } catch (IOException connectException) {
                    connectException.printStackTrace();
                    try {
                        bluetoothSocket.close();
                        Log.e("click6", "blueclose");
                    } catch (IOException closeException) {
                        closeException.printStackTrace();
                    }
                }


            }


     void beginListenForData()
            {
                final Handler handler = new Handler();
                final byte delimiter = 10; //This is the ASCII code for a newline character

                stopWorker = false;
                readBufferPosition = 0;
                readBuffer = new byte[1024];//It uses a 1024 bytes long buffer because it doesn't have any way of knowing the length of the input stream.
                workerThread = new Thread(new Runnable()
                {
                    public void run()
                    {
                        while(!Thread.currentThread().isInterrupted() && !stopWorker)
                        {
                            try
                            {
                                int bytesAvailable = mmInputStream.available();
                                if(bytesAvailable > 0)
                                {
                                    byte[] packetBytes = new byte[bytesAvailable];
                                    mmInputStream.read(packetBytes);
                                    for(int i=0;i<bytesAvailable;i++)
                                    {
                                        byte b = packetBytes[i];
                                        if(b == delimiter)
                                        {
                                            byte[] encodedBytes = new byte[readBufferPosition];
                                            System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                            final String data = new String(encodedBytes, "US-ASCII");
                                            readBufferPosition = 0;

                                            handler.post(new Runnable()
                                            {
                                                public void run()
                                                {

                                                    myLabel.setText(data);
                                                }
                                            });

                                        }
                                        else
                                        {
                                            readBuffer[readBufferPosition++] = b;
                                        }
                                    }
                                }
                            }
                            catch (IOException ex)
                            {
                                stopWorker = true;
                            }
                        }
                    }
                });

            workerThread.start();
        }

Hi the app crashed when I try to call beginListenForData(); The error state that Can't create handler inside thread that has not called Looper.prepare()

Does anyone know what wrong? I am new to android. Please help.

Bluetooth.xml below

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".BluetoothActivity">

    <ToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Turn off Bluetooth"
        android:textOff="Turn on Bluetooth"
        android:id="@+id/toggleButton"
        android:onClick="onToggle"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentStart="true"
        android:layout_marginStart="76dp"
        android:layout_below="@+id/toggleButton" />

    <TextView
        android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Type here:"
        android:layout_below="@+id/toggleButton"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="66dp" />


</RelativeLayout>

解决方案

Try this inside beginListenForData()

Replace

    final Handler handler = new Handler();

With this

    final Handler handler = new Handler(Looper.getMainLooper());

这篇关于应用程序崩溃的原因尺蠖。prepare()在beginlistendata()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆