使用蓝牙通信Android到PC发送文本文件

时间:2013-10-04 06:26:03

标签: java android bluetooth

您好我是Android新手。我想与PC通信android发送文本文件。 我正在尝试使用以下代码进行通信。 我正在使用蓝牙加密狗到电脑。 当我运行应用程序时,它会崩溃而没有任何错误。请帮我沟通。

    enter code here

         package com.exam.bluetooth2;

         import java.io.IOException;
         import java.io.OutputStream;
         import java.util.Set;
         import java.util.UUID;


         import android.R;
         import android.annotation.SuppressLint;
         import android.app.Activity;
         import android.app.ProgressDialog;
         import android.bluetooth.BluetoothAdapter;
         import android.bluetooth.BluetoothDevice;
         import android.bluetooth.BluetoothSocket;
         import android.content.Intent;
         import android.os.Bundle;
         import android.os.Handler;

         import android.os.Message;
         import android.util.Log;
         import android.view.View;
         import android.view.Window;
         import android.view.WindowManager;
         import android.widget.Button;
         import android.widget.EditText;
         import android.widget.Toast;


      public class Main extends Activity implements Runnable 
      {
    protected static final String TAG = "TAG";
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    Button mScan;

    BluetoothAdapter mBluetoothAdapter;
    private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private ProgressDialog mBluetoothConnectProgressDialog;
    private BluetoothSocket mBluetoothSocket;
    BluetoothDevice mBluetoothDevice;

    @Override
    public void onCreate(Bundle mSavedInstanceState) 
    {
        super.onCreate(mSavedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_list_item);
        mScan = (Button) findViewById(R.id.button1);

        mScan.setOnClickListener(new View.OnClickListener() 
        {

            public void onClick(View mView) 
            {
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (mBluetoothAdapter == null) 
                {
                    Toast.makeText(Main.this, "Message1", 2000).show();
                } 
                else 
                {
                    if (!mBluetoothAdapter.isEnabled()) 
                    {
                        Intent enableBtIntent = new                                     Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    } 
                    else 
                    {
                        ListPairedDevices();
                        Intent connectIntent = new Intent(Main.this,        DeviceListActivity.class);
                        startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
                    }
                }
            }
        });

    }


    public void onActivityResult(int mRequestCode, int mResultCode, Intent mDataIntent) 
    {
        super.onActivityResult(mRequestCode, mResultCode, mDataIntent);

        switch (mRequestCode) 
        {
            case REQUEST_CONNECT_DEVICE:
                if (mResultCode == Activity.RESULT_OK) 
                {
                    Bundle mExtra = mDataIntent.getExtras();
                    String mDeviceAddress = mExtra.getString("DeviceAddress");
                    Log.v(TAG, "Coming incoming address " + mDeviceAddress);
                    mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
                    mBluetoothConnectProgressDialog = ProgressDialog.show(this,  "Connecting...", mBluetoothDevice.getName() + " : " + mBluetoothDevice.getAddress(), true,   false);
                    Thread mBlutoothConnectThread = new Thread(this);
                    mBlutoothConnectThread.start();

                    Toast.makeText(getBaseContext(), mBluetoothDevice.getAddress(),  10000).show();
                    //pairToDevice(mBluetoothDevice); This method is replaced by progress       dialog with thread
                }
                break;

            case REQUEST_ENABLE_BT:
                if (mResultCode == Activity.RESULT_OK) 
                {
                    ListPairedDevices();
                    Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
                    startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
                } 
                else 
                {
                    Toast.makeText(Main.this, "Message", 2000).show();
                }
                break;
        }
    }


    private void ListPairedDevices() 
    {
        Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
        if (mPairedDevices.size() > 0) 
        {
            for (BluetoothDevice mDevice : mPairedDevices) 
            {
                Log.v(TAG, "PairedDevices: " + mDevice.getName() + " " +      mDevice.getAddress());
            }
        }

    //  Object device = null;
    //  String dv = device.toString();
    //    if(dv.contains("00:1B:EE:82:31:1E"))
     //   {
     //   mBluetoothDevice = (BluetoothDevice) device;
     //   }
    }

    public void run() 
    {
        try 
        {
            mBluetoothSocket =        mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
            mBluetoothAdapter.cancelDiscovery();
            mBluetoothSocket.connect();
            mHandler.sendEmptyMessage(0);
            String messsage = "Welcome to SmarTec";
            byte[] tosend=messsage.getBytes();
            OutputStream out=mBluetoothSocket.getOutputStream();
            out.write(tosend);
        }
        catch (IOException eConnectException) 
        {
            Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
             closeSocket(mBluetoothSocket);
             return;
        }
    }

    private void closeSocket(BluetoothSocket nOpenSocket) 
    {
        try 
        {
            nOpenSocket.close();
            Log.d(TAG, "SocketClosed");
        } 
        catch (IOException ex) 
        {
            Log.d(TAG, "CouldNotCloseSocket");
        }
    }

    private Handler mHandler = new Handler() 
    {

        @Override
        public void handleMessage(Message msg) 
        {
            mBluetoothConnectProgressDialog.dismiss();
            Toast.makeText(Main.this, "Device Connected", 5000).show();

        //    Intent in = new Intent(getBaseContext(), Option.class);
        //    startActivity(in);

        }
    };


      /*    public void sendtext(View v) {//button click

        Set<BluetoothDevice> bd = mBluetoothAdapter.getBondedDevices();
        sendDataToPairedDevice("message1");
        }

        private void sendDataToPairedDevice(String message ){       
            byte[] toSend = message.getBytes();
            try {
             UUID applicationUUID = UUID.fromString("8ce255c0-200a-11e0-ac64- 0800200c9a66");
             BluetoothSocket socket =       mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(applicationUUID);
             OutputStream mmOutStream = socket.getOutputStream();
             mmOutStream.write(toSend);
         } catch (IOException e) {
             Log.e( "Exception during write", e.toString());
         }
        }
        */
}

    enter code here

      package com.exam.bluetooth2;

      import java.util.Set;

        import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class DeviceListActivity extends Activity 
{
    protected static final String TAG = "TAG";
    private BluetoothAdapter mBluetoothAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;

    @Override
    protected void onCreate(Bundle mSavedInstanceState) 
    {
        super.onCreate(mSavedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.device_list);

        setResult(Activity.RESULT_CANCELED);
        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);

        ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
        mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
        mPairedListView.setOnItemClickListener(mDeviceClickListener);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();

        if (mPairedDevices.size() > 0) 
        {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
            for (BluetoothDevice mDevice : mPairedDevices) 
            {
                mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
            }
        } 
        else 
        {
            String mNoDevices = getResources().getText(R.string.none_paired).toString();
            mPairedDevicesArrayAdapter.add(mNoDevices);
        }
    }

    @Override
    protected void onDestroy() 
    {
        super.onDestroy();
        if (mBluetoothAdapter != null) 
        {
            mBluetoothAdapter.cancelDiscovery();
        }
    }

    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() 
    {
        public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong) 
        {
            mBluetoothAdapter.cancelDiscovery();
            String mDeviceInfo = ((TextView) mView).getText().toString();
            String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
            Log.v(TAG, "Device_Address " + mDeviceAddress);

            Bundle mBundle = new Bundle();
            mBundle.putString("DeviceAddress", mDeviceAddress);
            Intent mBackIntent = new Intent();
            mBackIntent.putExtras(mBundle);
            setResult(Activity.RESULT_OK, mBackIntent);
            finish();
        }
    };

}

1 个答案:

答案 0 :(得分:0)

维杰,

你需要检查以下几点思考:

  1. 在清单文件中添加蓝牙权限。
  2. 如果设备不支持蓝牙,那么您将获得蓝牙适配器值null。所以也需要检查一下。
  3. 使用蓝牙操作创建广播接收器也更好。