Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/178.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何传送图像&;通过蓝牙编程在android设备之间传输文本数据_Android - Fatal编程技术网

如何传送图像&;通过蓝牙编程在android设备之间传输文本数据

如何传送图像&;通过蓝牙编程在android设备之间传输文本数据,android,Android,我已经创建了一个android应用程序,其中列出了我设备附近的蓝牙设备。我如何将列表中的任何一个配对并将数据传输到该设备。我使用的代码来自: 用于列出蓝牙设备。我怎样才能从那里向任何人发送图像或文本 谢谢。对于图像传输: 对于文本:在同一示例中,只需将字符串转换为字节,而不是图像,而且“示例”中还有蓝牙聊天应用程序。以下是完整代码 BluetoothTexting.java: import java.io.IOException; 导入java.io.InputStream; 导入java.io

我已经创建了一个android应用程序,其中列出了我设备附近的蓝牙设备。我如何将列表中的任何一个配对并将数据传输到该设备。我使用的代码来自: 用于列出蓝牙设备。我怎样才能从那里向任何人发送图像或文本

谢谢。

对于图像传输:

对于文本:在同一示例中,只需将字符串转换为字节,而不是图像,而且“示例”中还有蓝牙聊天应用程序。

以下是完整代码

BluetoothTexting.java:

import java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.util.ArrayList;
导入java.util.UUID;
导入android.app.Activity;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入android.bluetooth.BluetoothServerSocket;
导入android.bluetooth.BluetoothSocket;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.os.Handler;
导入android.util.Log;
导入android.view.KeyEvent;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.view.view.OnKeyListener;
导入android.widget.AdapterView;
导入android.widget.ArrayAdapter;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.ListView;
导入android.widget.TextView;
导入android.widget.AdapterView.OnItemClickListener;
公共类BluetoothTexting扩展了活动{
私有静态int发现_请求=1;
私有处理程序=新处理程序();
专用ArrayList设备;
私人阵列适配器aa;
私有列表视图列表;
私人蓝牙适配器;
私人蓝牙插座;
专用UUID UUID=UUID.fromString(“a60f35f0-b93a-11de-8a39-08002009c666”);
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
配置蓝牙();
setupListView();
setupSearchButton();
setupListenButton();
}
私有void配置Bluetooth(){
bluetooth=BluetoothAdapter.getDefaultAdapter();
}
私有void setupListenButton(){
按钮列表按钮=(按钮)findViewById(R.id.Button\u listen);
setOnClickListener(新的OnClickListener(){
公共void onClick(视图){
意向盘=新意向(BluetoothAdapter.ACTION\u REQUEST\u DISCOVERABLE);
startActivityForResult(光盘、发现请求);
}
});
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
if(requestCode==发现请求){
布尔isDiscoverable=resultCode>0;
如果(isDiscoverable){
String name=“bluetoothserver”;
试一试{
最终BluetoothServerSocket btserver=
bluetooth.listenUsingRfcommWithServiceRecord(名称、uuid);
AsyncTask acceptThread=
新建异步任务(){
@凌驾
受保护的BluetoothSocket doInBackground(整数…参数){
试一试{
socket=btserver.accept(参数[0]*1000);
返回插座;
}捕获(IOE异常){
Log.d(“蓝牙”,例如getMessage());
}
返回null;
}
@凌驾
受保护的void onPostExecute(BluetoothSocket结果){
如果(结果!=null)
switchUI();
}            
};          
acceptThread.execute(resultCode);
}捕获(IOE异常){
Log.d(“蓝牙”,例如getMessage());
}
}
}
}
私有void setupListView(){
aa=新阵列适配器(此,
android.R.layout.simple\u list\u item\u 1,
铸造设备);
list=(ListView)findViewById(R.id.list\u发现);
列表.设置适配器(aa);
list.setOnItemClickListener(新的OnItemClickListener(){
public void onItemClick(AdapterView arg0,视图,
整数索引,长arg3){
AsyncTask connectTask=
新建异步任务(){
@凌驾
受保护的Void doInBackground(整数…参数){
试一试{
BluetoothDevice=foundDevices.get(参数[0]);
socket=device.createrFComSocketToServiceRecord(uuid);
socket.connect();
}捕获(IOE异常){
Log.d(“BLUETOOTH_客户端”,例如getMessage());
}
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
switchUI();
}
};
connectTask.execute(索引);
}      
});
}
私有void setupSearchButton(){
按钮搜索按钮=(按钮)findViewById(R.id.Button\u搜索);
setOnClickListener(新的OnClickListener(){
公共void onClick(视图){
注册接收人(发现结果),
新的IntentFilter(BluetoothDevice.ACTION_FOUND));
如果(!bluetooth.isDiscovery()){
foundDevices.clear();
bluetooth.startDiscovery();
}
}
});
}
私有void switchUI(){
final TextView messageText=(TextView)findViewById(R.id.text\u消息);
final EditText textEntry=(EditText)findViewById(R.id.text\u消息);
messageText.setVisibility(View.VISIBLE);
list.setVisibility(View.GONE);
textEntry.setEnabled(true);
setOnKeyListener(新的OnKeyListener(){
公共布尔onKey(视图、int-keyCode、KeyEvent-KeyEvent){
if((keyEvent.getAction()==keyEvent.ACTION\u向下)&&
(keyCode==KeyEvent.keyCode\u DPAD\u CENTER)){
发送消息(so)
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;
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.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class BluetoothTexting extends Activity {

  private static int DISCOVERY_REQUEST = 1;

  private Handler handler = new Handler();
  private ArrayList<BluetoothDevice> foundDevices;
  private ArrayAdapter<BluetoothDevice> aa; 
  private ListView list;

  private BluetoothAdapter bluetooth;
  private BluetoothSocket socket;
  private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    configureBluetooth();
    setupListView();    
    setupSearchButton();
    setupListenButton();
  }

  private void configureBluetooth() {
    bluetooth = BluetoothAdapter.getDefaultAdapter();
  }

  private void setupListenButton() {
    Button listenButton = (Button)findViewById(R.id.button_listen);
    listenButton.setOnClickListener(new OnClickListener() {
      public void onClick(View view) {
        Intent disc = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        startActivityForResult(disc, DISCOVERY_REQUEST);     
      }
    });
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == DISCOVERY_REQUEST) {
      boolean isDiscoverable = resultCode > 0;
      if (isDiscoverable) {
        String name = "bluetoothserver";
        try {
          final BluetoothServerSocket btserver = 
            bluetooth.listenUsingRfcommWithServiceRecord(name, uuid);

          AsyncTask<Integer, Void, BluetoothSocket> acceptThread = 
            new AsyncTask<Integer, Void, BluetoothSocket>() {

            @Override
            protected BluetoothSocket doInBackground(Integer... params) {
              try {
                socket = btserver.accept(params[0]*1000);
                return socket;
              } catch (IOException e) {
                Log.d("BLUETOOTH", e.getMessage());            
              }
              return null;
            }

            @Override
            protected void onPostExecute(BluetoothSocket result) {
              if (result != null)
                switchUI();
            }            
          };          
          acceptThread.execute(resultCode);
        } catch (IOException e) {
          Log.d("BLUETOOTH", e.getMessage());            
        }
      }
    }
  }

  private void setupListView() {
    aa = new ArrayAdapter<BluetoothDevice>(this, 
               android.R.layout.simple_list_item_1,
               foundDevices);
    list = (ListView)findViewById(R.id.list_discovered);    
    list.setAdapter(aa);

    list.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> arg0, View view, 
                              int index, long arg3) {
        AsyncTask<Integer, Void, Void> connectTask = 
          new AsyncTask<Integer, Void, Void>() { 
            @Override
            protected Void doInBackground(Integer... params) {
              try {
                BluetoothDevice device = foundDevices.get(params[0]);
                socket = device.createRfcommSocketToServiceRecord(uuid);
                socket.connect();              
              } catch (IOException e) {
                Log.d("BLUETOOTH_CLIENT", e.getMessage());
              }
              return null;
            }

            @Override
            protected void onPostExecute(Void result) {
              switchUI();
            }
          };
        connectTask.execute(index);
      }      
    });
  }

  private void setupSearchButton() {
    Button searchButton = (Button)findViewById(R.id.button_search);

    searchButton.setOnClickListener(new OnClickListener() {
      public void onClick(View view) {
        registerReceiver(discoveryResult, 
                         new IntentFilter(BluetoothDevice.ACTION_FOUND));

        if (!bluetooth.isDiscovering()) {
          foundDevices.clear();
          bluetooth.startDiscovery();
        }
      }
    });
  }

  private void switchUI() {    
    final TextView messageText = (TextView)findViewById(R.id.text_messages);
    final EditText textEntry = (EditText)findViewById(R.id.text_message);

    messageText.setVisibility(View.VISIBLE);
    list.setVisibility(View.GONE);
    textEntry.setEnabled(true);

    textEntry.setOnKeyListener(new OnKeyListener() {
      public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
        if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) &&
            (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) {
          sendMessage(socket, textEntry.getText().toString());
          textEntry.setText("");
          return true;
        }
        return false;
      }      
    });
    BluetoothSocketListener bsl = new BluetoothSocketListener(socket, handler, messageText);
    Thread messageListener = new Thread(bsl);
    messageListener.start();
  }

  private void sendMessage(BluetoothSocket socket, String msg) {
    OutputStream outStream;
    try {
      outStream = socket.getOutputStream();
      byte[] byteString = (msg + " ").getBytes();
      byteString[byteString.length - 1] = 0;
      outStream.write(byteString);
    } catch (IOException e) {
      Log.d("BLUETOOTH_COMMS", e.getMessage());
    }    
  }

  BroadcastReceiver discoveryResult = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      BluetoothDevice remoteDevice;
      remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
      if (bluetooth.getBondedDevices().contains(remoteDevice)) {  
        foundDevices.add(remoteDevice);
        aa.notifyDataSetChanged();
      }
    }
  };

  private class MessagePoster implements Runnable {
    private TextView textView;
    private String message;

    public MessagePoster(TextView textView, String message) {
      this.textView = textView;
      this.message = message;
    }

    public void run() {
      textView.setText(message);
    }     
  }

  private class BluetoothSocketListener implements Runnable {

      private BluetoothSocket socket;
      private TextView textView;
      private Handler handler;

      public BluetoothSocketListener(BluetoothSocket socket, 
                                     Handler handler, TextView textView) {
        this.socket = socket;
        this.textView = textView;
        this.handler = handler;
      }

    public void run() {
      int bufferSize = 1024;
      byte[] buffer = new byte[bufferSize];      
      try {
        InputStream instream = socket.getInputStream();
        int bytesRead = -1;
        String message = "";
        while (true) {
          message = "";
          bytesRead = instream.read(buffer);
          if (bytesRead != -1) {
            while ((bytesRead==bufferSize)&&(buffer[bufferSize-1] != 0)) {
              message = message + new String(buffer, 0, bytesRead);
              bytesRead = instream.read(buffer);
            }
            message = message + new String(buffer, 0, bytesRead - 1); 

            handler.post(new MessagePoster(textView, message));              
            socket.getInputStream();
          }
        }
      } catch (IOException e) {
        Log.d("BLUETOOTH_COMMS", e.getMessage());
      } 
    }
  }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<EditText
android:id="@+id/text_message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:enabled="false"
/>
<Button
android:id="@+id/button_search"
android:text="Search for listener"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@id/text_message"
/>
<Button
android:id="@+id/button_listen"
android:text="Listen for connection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@id/button_search"
/>

<ListView
android:id="@+id/list_discovered"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@id/button_listen"
android:layout_alignParentTop="true"
/>
<TextView
android:id="@+id/text_messages"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@id/button_listen"
android:layout_alignParentTop="true"
android:visibility="gone"
/>
</RelativeLayout>