注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

姑射道人的博客

博客新地址:nixuchen.com

 
 
 

日志

 
 

使用BluetoothSocket发送文件  

2013-09-04 15:48:30|  分类: android |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
package com.example.testzip;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipException;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

// Name for the SDP record when creating server socket
private static final String NAME_SECURE = "BluetoothSecure";
private static final String NAME_INSECURE = "BluetoothInsecure";
private static final boolean D = true;

// Unique UUID for this application
private static final UUID MY_UUID_SECURE = UUID
.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final UUID MY_UUID_INSECURE = UUID
.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");

private int mState;

// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming
// connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing
// connection
public static final int STATE_CONNECTED = 3; // now connected to a remote
// device

private String TAG = "MainActivity";
Button btn, btn2;
Handler mHandler;
ListView listView;
BluetoothAdapter mAdapter;
BroadcastReceiver mReceiver;
private final static String zipPath = Environment
.getExternalStorageDirectory() + "/test.zip";
private final static String receivedPath = Environment
.getExternalStorageDirectory() + "/received.zip";
List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

private AcceptThread mSecureAcceptThread;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;

/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted (or
* until cancelled).
*/
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
private String mSocketType;

public AcceptThread(boolean secure) {
BluetoothServerSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";

// Create a new listening server socket
try {
if (secure) {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(
NAME_SECURE, MY_UUID_SECURE);
} else {
tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(
NAME_INSECURE, MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + " listen() failed",
e);
}
mmServerSocket = tmp;
}

public void run() {

// setName("AcceptThread" + mSocketType);

BluetoothSocket socket = null;

// Listen to the server socket if we're not connected
while (true) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
// Start the connected thread
connected(socket, mSocketType);
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType
+ " accept() failed", e);
break;
}


}

}

public void cancel() {

try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "Socket Type" + mSocketType
+ "close() of server failed", e);
}
}
}

/**
* This thread runs while attempting to make an outgoing connection with a
* device. It runs straight through; the connection either succeeds or
* fails.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private String mSocketType;

public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";

// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
if (secure) {
tmp = device
.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} else {
tmp = device
.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
}

public void run() {
Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
setName("ConnectThread" + mSocketType);

// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();

// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception

mmSocket.connect();

} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + mSocketType
+ " socket during connection failure", e2);
}
connectionFailed();
return;
}

if(mmSocket!=null){
// Start the connected thread
connected(mmSocket, mSocketType);
}
// Reset the ConnectThread because we're done
synchronized (MainActivity.this) {
mConnectThread = null;
}

}

public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect " + mSocketType
+ " socket failed", e);
}
}
}

/**
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private void connectionFailed() {
// Send a failure message back to the Activity
// Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
// Bundle bundle = new Bundle();
// bundle.putString(BluetoothChat.TOAST, "Unable to connect device");
// msg.setData(bundle);
// mHandler.sendMessage(msg);
//
// // Start the service over to restart listening mode
// BluetoothChatService.this.start();
Log.i(TAG, "connection Failed");
}

/**
* This thread runs during a connection with a remote device. It handles all
* incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;

public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, "create ConnectedThread: " + socketType);
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;

// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
         
mmInStream = tmpIn;
mmOutStream = tmpOut;
}

public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
           while (true) {
               
               
                     File file=new File(receivedPath);
                     if(file.exists())file.delete();
                     Log.i(TAG, "Remote device:"+mmSocket.getRemoteDevice().getName());
                    
                    StreamTool.inputstreamtofile(mmInStream, file);
                     
                     
                    break;
           }

}


private void connectionLost() {
// TODO Auto-generated method stub

}
  public void sendFile(File file){
        try {
       
       
           File f = new File(zipPath);
           byte [] buffer = new byte[(int)f.length()];
           FileInputStream fis = new FileInputStream(f);
           BufferedInputStream bis = new BufferedInputStream(fis);
           bis.read(buffer,0,buffer.length);
           mmOutStream.write(buffer,0,buffer.length);
           mmOutStream.flush();
                    bis.close();
 
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e(TAG ,"file not found:"+e
);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG,"IOException:"+e
);
e.printStackTrace();
}
       
       }
       

public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
btn2 = (Button) findViewById(R.id.btn2);
listView = (ListView) findViewById(R.id.listView);

btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

doZip();
}
});

openBlueTooth();
btn2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
list.clear();
listView.setVisibility(View.INVISIBLE);
if (mAdapter.isDiscovering())
mAdapter.cancelDiscovery();
mAdapter.startDiscovery();

}
});

listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String address = list.get(arg2).get("address");
Log.i(TAG, "selected address:" + address);

doPairAndSendFile(address);

}
});

}

/**
* Stop all threads
*/
public synchronized void stop() {

if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}

if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}

if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}

if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread = null;
}
setState(STATE_NONE);

}

/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume()
*/
public synchronized void start() {

// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}

// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
setState(STATE_LISTEN);

// Start the thread to listen on a BluetoothServerSocket
if (mSecureAcceptThread == null) {
mSecureAcceptThread = new AcceptThread(true);
mSecureAcceptThread.start();
}
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = new AcceptThread(false);
mInsecureAcceptThread.start();
}
}

/**
* Start the ConnectedThread to begin managing a Bluetooth connection
* @param socket
*            The BluetoothSocket on which the connection was made
* @param device
*            The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket,
final String socketType) {

Log.i(TAG, "start connected");
// // Cancel the thread that completed the connection
// if (mConnectThread != null) {
// mConnectThread.cancel();
// mConnectThread = null;
// }
//
// // Cancel any thread currently running a connection
// if (mConnectedThread != null) {
// mConnectedThread.cancel();
// mConnectedThread = null;
// }
//
// // Cancel the accept thread because we only want to connect to one
// // device
// if (mSecureAcceptThread != null) {
// mSecureAcceptThread.cancel();
// mSecureAcceptThread = null;
// }
// if (mInsecureAcceptThread != null) {
// mInsecureAcceptThread.cancel();
// mInsecureAcceptThread = null;
// }

// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket, socketType);
mConnectedThread.start();

// // Send the name of the connected device back to the UI Activity
// Message msg =
// mHandler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME);
// Bundle bundle = new Bundle();
// bundle.putString(MainActivity.DEVICE_NAME, device.getName());
// msg.setData(bundle);
// mHandler.sendMessage(msg);
//
setState(STATE_CONNECTED);
}

public void doPairAndSendFile(String address) {
// Get the BLuetoothDevice object
        Log.i(TAG, "myState:"+mState);
if (mState != STATE_CONNECTED) {
BluetoothDevice device = mAdapter.getRemoteDevice(address);
connect(device, true);
} else {
sendFile(MainActivity.this);
}

}

private void sendFile(MainActivity mainActivity) {
         File file=new File(zipPath);
mConnectedThread.sendFile(file);
}

/**
* Start the ConnectThread to initiate a connection to a remote device.
* @param device
*            The BluetoothDevice to connect
* @param secure
*            Socket Security type - Secure (true) , Insecure (false)
*/
public synchronized void connect(BluetoothDevice device, boolean secure) {
if (D)
Log.d(TAG, "connect to: " + device);

// // Cancel any thread attempting to make a connection
// if (mState == STATE_CONNECTING) {
// if (mConnectThread != null) {
// mConnectThread.cancel();
// mConnectThread = null;
// }
// }
//
// // Cancel any thread currently running a connection
// if (mConnectedThread != null) {
// mConnectedThread.cancel();
// mConnectedThread = null;
// }

// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device, secure);
mConnectThread.start();
setState(STATE_CONNECTING);

}

/**
* Set the curret state of the chat connection
* @param state
*            An integer defining the current connection state
*/
private synchronized void setState(int state) {
if (D)
Log.d(TAG, "setState() " + mState + " -> " + state);
mState = state;

}

// public static void sendFile(Context con) {
//
// Intent intent = new Intent();
// intent.setAction(Intent.ACTION_SEND);
//
// intent.setType("*/*");
// intent.setClassName("com.android.bluetooth" ,
// "com.android.bluetooth.opp.BluetoothOppLauncherActivity");
//
// try {
// intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(zipPath)));
// } catch (Exception e) {
// e.printStackTrace();
// }
// con.startActivity(intent);
// }

public void openBlueTooth() {
mAdapter = BluetoothAdapter.getDefaultAdapter();
// //直接打开系统的蓝牙设置面板
// Intent intent = new Intent(BluetoothmAdapter.ACTION_REQUEST_ENABLE);
// startActivityForResult(intent, 0x1);
// 直接打开蓝牙
if (!mAdapter.isEnabled())
{
mAdapter.enable();
// Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//    startActivityForResult(enableBtIntent, 0);
}
Intent discoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);

// 打开本机的蓝牙发现功能(默认打开120秒,可以将时间最多延长至300秒)
// 创建一个接收ACTION_FOUND广播的BroadcastReceiver
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {

String action = intent.getAction();

// 发现设备
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 从Intent中获取设备对象
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 将设备名称和地址放入array mAdapter,以便在ListView中显示
HashMap<String, String> map = new HashMap<String, String>();
map.put("device", device.getName());
map.put("address", device.getAddress());
map.put("paird","state:"+ device.getBondState());
if (!list.contains(map))
list.add(map);

Log.i(TAG, map.toString());
listView.setVisibility(View.VISIBLE);
listView.setAdapter(new SimpleAdapter(
getApplicationContext(), list,
R.layout.listitem_bluetooth, new String[] {
"device", "address","paird" }, new int[] {
R.id.device, R.id.address,R.id.paird }));

}
}
};
// 注册BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

registerReceiver(mReceiver, filter); // 不要忘了之后解除绑定
if (mAdapter.isDiscovering())
mAdapter.cancelDiscovery();
mAdapter.startDiscovery();
start();
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(mReceiver);
// stop();
}

private void doZip() {
String path = Environment.getExternalStorageDirectory() + "/.brisc/"
+ "/";

try {

FileCompressionUtil.ZipFolder(path,
Environment.getExternalStorageDirectory() + "/test.zip");
} catch (ZipException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.w("MainActivity", e.toString());
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

附:

public class StreamTool {

final static String TAG="StreamTool"; 
public static final byte[] input2byte(InputStream inStream)  
            throws IOException {  
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
        byte[] buff = new byte[1024*4];  
        int rc = 0;  
        while ((rc = inStream.read(buff, 0, 100)) > 0) {  
            swapStream.write(buff, 0, rc);  
        }  
        byte[] in2b = swapStream.toByteArray();  
        return in2b;  
    }  
public   static   String   inputStream2String(InputStream   is)   throws   IOException{ 
        ByteArrayOutputStream   baos   =   new   ByteArrayOutputStream(); 
        int   i=-1; 
        while((i=is.read())!=-1){ 
        baos.write(i); 
        } 
       return   baos.toString(); 
}
/**
 * 根据byte数组,生成文件
 */
public static void getFile(byte[] bfile, String filePath,String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath+"/"+fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
public static void inputstreamtofile(InputStream ins,File file) {
 try {
   OutputStream os = new FileOutputStream(file);
   int bytesRead = 0;
   byte[] buffer = new byte[8192];
   while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
    os.write(buffer, 0, bytesRead);
   }
   os.close();
   ins.close();
   Log.i(TAG, "file saved");
  } catch (Exception e) {
   e.printStackTrace();
  }
}

}
  评论这张
 
阅读(1970)| 评论(4)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017