通过蓝牙发送SD卡文件时经常断开连接

时间:2015-10-14 18:36:52

标签: android file bluetooth

我正在制作一个应用程序,通过蓝牙发送文件,而不使用android os默认蓝牙应用程序。
但是当发送文件连接到设备时,每次我发送文件时都会自动断开连接
这是执行此任务的整个活动请帮助..

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

import android.app.Activity; 
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.net.Uri;
import android.os.Bundle;
import android.os.Handler;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;  
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener,
    OnItemClickListener {

private BluetoothAdapter ba;
private Set<BluetoothDevice> pairedD;;
private ListView lv;
ArrayList<String> list;
ArrayAdapter<String> adap;
private Button browse;
private EditText filePath;
private ImageView image;
private final UUID MY_UUID = UUID
        .fromString("00001101-0000-1000-8000-00805F9B34FB");
private String previous = null;
boolean shown = false;
private Handler mHandler;
private ConnectThread mConnect;
private SendingThread mSend;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button b1 = (Button) findViewById(R.id.butTurnOn);
    Button b2 = (Button) findViewById(R.id.butTurnOff);
    Button b3 = (Button) findViewById(R.id.butDiscoverable);
    Button b4 = (Button) findViewById(R.id.butPairedDevices);
    browse = (Button) findViewById(R.id.butBrowse);
    filePath = (EditText) findViewById(R.id.etFile);
    lv = (ListView) findViewById(R.id.lvDevices);
    image = (ImageView) findViewById(R.id.imageButton1);
    ba = BluetoothAdapter.getDefaultAdapter();
    if (ba == null) {
        Toast.makeText(this, "Your device does not support bluetooth",
                Toast.LENGTH_LONG).show();
    }
    b1.setOnClickListener(this);
    b2.setOnClickListener(this);
    b3.setOnClickListener(this);
    b4.setOnClickListener(this);
    browse.setOnClickListener(this);
    mHandler = new Handler();
    list = new ArrayList<String>();
    adap = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, list);
    lv.setAdapter(adap);
    lv.setOnItemClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.butTurnOn:
        if (setOn()) {
            Toast.makeText(this, "Bluetooth Turned On", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(this, "Already On..", Toast.LENGTH_SHORT).show();
        }
        break;
    case R.id.butTurnOff:
        if (setOff()) {
            Toast.makeText(this, "Turned Off", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Already Turned Off", Toast.LENGTH_SHORT)
                    .show();
        }
        break;
    case R.id.butDiscoverable:
        setDiscoverable();
        break;
    case R.id.butPairedDevices:
        getPairedDeviceList();
        break;
    case R.id.butBrowse:
//Activity for file explorer 
        Intent i = new Intent(this, ListFiles.class);
        startActivityForResult(i, 1);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent   data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 && resultCode == RESULT_OK) {
        // String cont=data.getDataString();
        Bundle getBox = data.getExtras();
        filePath.setText(getBox.getString("path"));
        File file = new File(getBox.getString("path"));

        image.setImageURI(Uri.parse(getBox.getString("path")));
    }
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

    if (myReceiver == null) {
        registerReceiver(myReceiver, new IntentFilter(
                BluetoothDevice.ACTION_FOUND));
    }
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    ba.cancelDiscovery();
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    if (myReceiver != null) {
        unregisterReceiver(myReceiver);
        myReceiver = null;
    }
    ba.disable();
    finish();
}

/*---------------BroadcastReceiver To Show Other devices and handle----------------*/

private BroadcastReceiver myReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (!(device.getAddress().equals(previous))) {
                adap.add(device.getName() + "\n" + device.getAddress());
                previous = device.getAddress();
            }
        }
        if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            if (myReceiver != null) {
                unregisterReceiver(myReceiver);
                myReceiver = null;
            }
        }
        if (BluetoothAdapter.ACTION_STATE_CHANGED
                .equals(BluetoothAdapter.STATE_OFF)) {
            if (myReceiver != null) {
                unregisterReceiver(myReceiver);
                myReceiver = null;
            }
            if (ba.isEnabled()) {
                ba.disable();
            }
        }
    }
};

/*---------------End BroadcastReceiver To Show Other devices and handle----------------*/

/*------------------------ Start Get Paired Device List-------------------------------*/
private void getPairedDeviceList() {
    // TODO Auto-generated method stub
    if (!setOn()) {
        adap.clear();
        pairedD = ba.getBondedDevices();
        for (BluetoothDevice bt : pairedD) {
            adap.add(bt.getName() + "\n" + bt.getAddress());
        }
        registerReceiver(myReceiver, new IntentFilter(
                BluetoothDevice.ACTION_FOUND));
        if (ba.isDiscovering()) {
            ba.cancelDiscovery();
        }
        ba.startDiscovery();
    }

    else {
        Toast.makeText(this, "Set Bluetooth On", Toast.LENGTH_SHORT).show();
    }
}

/*------------------------ End Get Paired Device List-------------------------------*/

/*-------------------------Start Set BluetoothAdapter Discoverable-------------------*/

private void setDiscoverable() {
    // TODO Auto-generated method stub
    if (!setOn()) {
        if (ba.isDiscovering()) {
            Toast.makeText(this, "Already Discovering", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Intent i = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            i.putExtra(
                    "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION",
                    100);
            startActivityForResult(i, 0);
            Toast.makeText(this, "Discovery Started", Toast.LENGTH_SHORT)
                    .show();
        }
    } else {
        Toast.makeText(this, "Set Bluetooth On", Toast.LENGTH_SHORT).show();
    }
}

/*-------------------------End Set BluetoothAdapter Discoverable-------------------*/

/*-------------------------Start Set BluetoothAdapter Off---------------------------*/

private boolean setOff() {
    // TODO Auto-generated method stub
    if (ba.isEnabled()) {
        ba.disable();
        return true;
    } else {
        return false;
    }
}

/*-------------------------End Set BluetoothAdapter Off---------------------------*/

/*-------------------------Start Set BluetoothAdapter On---------------------------*/

private boolean setOn() {
    // TODO Auto-generated method stub
    if (ba.isEnabled()) {
        return false;
    } else {
        Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(i, 0);
        return true;
    }
}

/*-------------------------End Set BluetoothAdapter On---------------------------*/

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    // TODO Auto-generated method stub
    String cont = adap.getItem(position);
    if (cont.contains("\n")) {
        cont = cont.substring(cont.indexOf("\n") + 1);
    }
    BluetoothDevice bd = null;
    if (BluetoothAdapter.checkBluetoothAddress(cont)) {
        bd = ba.getRemoteDevice(cont);
    }
    new ConnectThread(bd).start();
    Toast.makeText(this, cont, Toast.LENGTH_LONG).show();
}

/*------------------------Start Connect to Other Bluetooth Device---------------------*/

public class ConnectThread extends Thread {
    private BluetoothSocket mySocket;
    private BluetoothDevice myDevice;

    public ConnectThread(BluetoothDevice device) {
        BluetoothSocket tmp = null;
        myDevice = device;
        try {
            tmp = myDevice.createRfcommSocketToServiceRecord(MY_UUID);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mySocket = tmp;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        ba.cancelDiscovery();
        try {
            mySocket.connect();
            new SendingThread(mySocket).start();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            try {
                mySocket.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    public void cancel() {
        try {
            Log.d("Disconnect", "Yes");
            mySocket.close();
        } catch (IOException e) {
        }
    }
}

/*------------------------End Connect to Other Bluetooth Device---------------------*/

/*------------------------Start Data Transfer B/w two Device------------------------*/

public class SendingThread extends Thread {

    private BluetoothSocket sSocket;
    private InputStream inStream;
    private OutputStream outStream;

    public SendingThread(BluetoothSocket socket) {
        sSocket = socket;
        InputStream myIn = null;
        OutputStream myOut = null;

        try {
            myIn = sSocket.getInputStream();
            myOut = sSocket.getOutputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        inStream = myIn;
        outStream = myOut;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        if (!filePath.getText().toString().equals("")) {
            File f=new File(filePath.getText().toString());
            byte[] buffer = f.getAbsoluteFile().getClass().getName().getBytes();// buffer store for the stream
            Log.d("Sending",f.getAbsoluteFile().getClass().getName());
            write(buffer);
        }
         byte[] buffer = new byte[1024];
            int bytes;

            while(true)
            {
                try
                {
                    bytes = inStream.read(buffer);
                    Log.d("Received : ",String.valueOf(bytes));
                }
                catch(IOException e) { break; }
            }
    }

    public void write(byte[] bytes) {
        try {
            Log.d("writing", "Yes");
            outStream.write(bytes);
            outStream.flush();
            outStream.close();
        } catch (IOException e) {
        }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            Log.d("Disconnect", "Yes");
            sSocket.close();
        } catch (IOException e) {
        }
    }
}

/*------------------------End Data Transfer B/w two Device------------------------*/
}

0 个答案:

没有答案