Android蓝牙聊天应用

时间:2012-04-24 15:06:19

标签: android bluetooth chat

我试图在eclipse中制作一个基本的蓝牙聊天应用程序,我已经完成了代码并且没有用红色加下划线来提示错误,但当我尝试运行代码时,应用程序意外停止,当我调试代码时它说未找到来源。 我已经为清单添加了蓝牙权限,所以我不这么认为。 任何帮助将不胜感激。 这是代码:

package com.blue;

import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BlueActivity extends Activity {
/** Called when the activity is first created. */
public Button btn_Search, btn_Send, btn_Next;
UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public BluetoothAdapter my_BT_Adapter=BluetoothAdapter.getDefaultAdapter();
public ArrayList<String>BT_Names=new ArrayList<String>();
public ArrayList<String>BT_Addresses=new ArrayList<String>();
public ArrayAdapter<String>aa;
public ArrayAdapter<String>bb;
public TextView txt_Display;
public EditText txt_Message;
public ListView lv_Devices;
public static String address;
public static String right_address;
public BluetoothDevice BT_Device;
public BluetoothSocket BT_Socket;
protected Context context;
Intent intent1 = new Intent();
public int selectedPosition;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    btn_Search = (Button)findViewById(R.id.btn_search);
    txt_Display = (TextView)findViewById(R.id.txt_display);
    lv_Devices = (ListView)findViewById(R.id.lw_Bluetooth_names);
    btn_Send = (Button)findViewById(R.id.btn_send);
    btn_Next = (Button)findViewById(R.id.btn_next);
    txt_Message = (EditText)findViewById(R.id.txt_message);
    aa = new ArrayAdapter<String>(this,android.R.layout.simple_gallery_item, BT_Names);
    bb = new ArrayAdapter<String>(this,android.R.layout.simple_gallery_item, BT_Addresses);
    btn_Send.setFocusable(true);
    btn_Next.setEnabled(false);
    btn_Search.setOnClickListener(SearchClickHandler);
    btn_Next.setOnClickListener(NextClickHandler);
    btn_Send.setOnClickListener(SendClickHandler);



    BT_Enable();

    BroadcastReceiver discoveryResult = new BroadcastReceiver(){



        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)){
            String remoteDeviceName=intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
            BluetoothDevice remoteDevice;
            remoteDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            BT_Names.add(0, remoteDeviceName);
            BT_Addresses.add(0, remoteDevice.getAddress());
            aa.notifyDataSetChanged();
            bb.notifyDataSetChanged();
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
            txt_Display.setText("");
            lv_Devices.setAdapter(aa);
            if(BT_Names.size()>0){
                btn_Search.setClickable(true);
                address=BT_Addresses.get(0);
                txt_Display.setText(BT_Names.get(0));
                btn_Next.setEnabled(true);
                lv_Devices.setItemChecked(0, true);

            }
            else
                btn_Search.setClickable(true);

            }

        }





        };
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(discoveryResult, filter);


        filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(discoveryResult, filter);
        BT_Device=intent1.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    }
    public void BT_Enable(){
        if(!my_BT_Adapter.isEnabled()){
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, CONTEXT_RESTRICTED);
        }
    }

    View.OnClickListener SearchClickHandler=new View.OnClickListener() {



        public void onClick(View v) {
            // TODO Auto-generated method stub
            btn_Search.setClickable(true);
                BT_Names.clear();
                aa.notifyDataSetChanged();
                BT_Addresses.clear();
                bb.notifyDataSetChanged();
                selectedPosition=0;
                txt_Display.setText("Searching...");
                btn_Next.setEnabled(true);

                if(!my_BT_Adapter.isEnabled()){
                    try{

                        my_BT_Adapter.enable();
                        Toast.makeText(BlueActivity.this, "BT Adapter Enabled", Toast.LENGTH_SHORT).show();
                }
                    catch(Exception e)
                    {
                        Toast.makeText(BlueActivity.this, "BT Adapter Unavailable", Toast.LENGTH_SHORT).show();
                    }
                }

                if(!my_BT_Adapter.isDiscovering())
                my_BT_Adapter.startDiscovery();

        }
    };
    View.OnClickListener NextClickHandler=new View.OnClickListener() {


        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(BT_Names.size()>0){
            if(selectedPosition<BT_Names.size()){
                lv_Devices.setItemChecked(selectedPosition, true);
            right_address=BT_Addresses.get(selectedPosition);
            selectedPosition++;
            }
            else
            {
            selectedPosition=0;
            right_address=BT_Addresses.get(selectedPosition);
            lv_Devices.setItemChecked(selectedPosition, true);
            }
            }
            txt_Display.setText(BT_Names.get(lv_Devices.getCheckedItemPosition()));


        }
    };
    View.OnClickListener SendClickHandler=new View.OnClickListener() {


        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(my_BT_Adapter.isEnabled()&& right_address !="")
            {
                        Thread ConnectThread = new Thread(new Runnable(){
                                public void run(){
                                        BT_Device=my_BT_Adapter.getRemoteDevice(right_address);
                                        String TAG = null;
                                        Log.e(TAG, BT_Device.getName()+"connected");
                                try{
                                BT_Socket=BT_Device.createRfcommSocketToServiceRecord(MY_UUID);
                }
            catch(IOException e)
            {
                Log.e(TAG, "ON RESUME: Socket creation failed.", e);

            }
            Log.e(TAG, "TRYING TO CONNECT");
                    try{
                        btn_Send.setClickable(false);
                        btn_Search.setClickable(false);
                        btn_Next.setClickable(false);
                        BT_Socket.connect();
                        Log .e(TAG, "ON RESUME: BT connection established, data transfer link open.");
                    }
                    catch(IOException e)
                            {
                btn_Send.setClickable(true);
                        btn_Search.setClickable(true);
                        btn_Next.setClickable(true);
                            }
                        try{
                                Thread.sleep(1000);
                                OutputStream outStream;
                                outStream = BT_Socket.getOutputStream();
            byte[]byteArray=(txt_Message.getText().toString()).getBytes();
            outStream.write(byteArray);
            outStream.flush();
            Thread.sleep(1500);
            BT_Socket.close();
                btn_Send.setClickable(true);
                        btn_Search.setClickable(true);

        }
                    catch(Exception e)
        {
                txt_Display.setText("Unsuccessful");
        }
                }
                });


                ConnectThread.start();

    }
            else
            {
                Toast.makeText(BlueActivity.this, "Adapter off or bluetooth not selected", Toast.LENGTH_SHORT).show();
            }
        }
        };
}

先谢谢Chris,

1 个答案:

答案 0 :(得分:0)

您的一个findViewById调用可能返回null。我建议你在findViewById之后检查空值。