Bluetoothソケットを介してオーディオを送信するアプリケーションを作成しようとしています。これまでのところ、ペアデバイスを取得して接続スレッド(クライアント)を開始しても動作しませんでしたおそらく私は((今はただテキストを送信しようとしている)))。 この私のコード:Bluetoothソケットが動作しない
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
String tag="debuger";
ArrayAdapter<String> listAdapter;
Button connectNew;
ListView listView;
BluetoothAdapter btAdapter;
ArrayList<BluetoothDevice> devices;
Set<BluetoothDevice> deviceArray;
IntentFilter filter;
BroadcastReceiver receiver;
ArrayList<String> pairedDevices;
public static final UUID MY_UUID=UUID.fromString("00001101-0000-1000-8000-00805FB34FB");
protected static final int SUCCESS_CONNECT=0;
protected static final int MESSAGE_READ=1;
Handler mhandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Toast.makeText(getApplicationContext(), "entreing the handler", Toast.LENGTH_LONG).show();
switch (msg.what){
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
getpairedDevices();
}
private void startDiscovery() {
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void init(){
devices=new ArrayList<BluetoothDevice>();
btAdapter=BluetoothAdapter.getDefaultAdapter();
filter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
receiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String s="";
for (int a=0;a<pairedDevices.size();a++){
if(device.getName().equals(pairedDevices.get(a))){
//apend
s="(Paired)";
break;
}
}
listAdapter.add(device.getName()+"\n"+s+device.getAddress());
} if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action));{
// Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_LONG).show();
}
if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
// Toast.makeText(getApplicationContext(),"state",Toast.LENGTH_LONG).show();
}
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
//Toast.makeText(getApplicationContext(),"finish",Toast.LENGTH_LONG).show();
}
}
}; registerReceiver(receiver,filter);
filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver,filter);
filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver,filter);
filter=new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver,filter);
connectNew=(Button)findViewById(R.id.button);
listView=(ListView)findViewById(R.id.listView);
listAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
listView.setAdapter(listAdapter);
pairedDevices=new ArrayList<String>();
listView.setOnItemClickListener(this);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
finish();
}
}
private void getpairedDevices(){
deviceArray=btAdapter.getBondedDevices();
if(deviceArray.size()>0){
for(BluetoothDevice device:deviceArray){
pairedDevices.add(device.getName());
}
}
}
public void TurnOn(View view) {
btAdapter.enable();
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//
if (btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if (listAdapter.getItem(arg2).contains("Paired")){
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
finish();
}
}
private void getpairedDevices(){
deviceArray=btAdapter.getBondedDevices();
if(deviceArray.size()>0){
for(BluetoothDevice device:deviceArray){
pairedDevices.add(device.getName());
}
}
}
public void TurnOn(View view) {
btAdapter.enable();
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//
if (btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if (listAdapter.getItem(arg2).contains("Paired")){
case SUCCESS_CONNECT:
String s="hothyfa its a success";
ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg.obj);
connectedThread.write(s.getBytes());
Toast.makeText(getApplicationContext(),"Succcssss",Toast.LENGTH_LONG).show();
break;
case MESSAGE_READ:
byte[] readbuf=(byte[])msg.obj;
String s2=new String(readbuf);
Toast.makeText(getApplicationContext(),s2,Toast.LENGTH_LONG).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
getpairedDevices();
}
private void startDiscovery() {
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void init(){
devices=new ArrayList<BluetoothDevice>();
btAdapter=BluetoothAdapter.getDefaultAdapter();
filter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
receiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String s="";
for (int a=0;a<pairedDevices.size();a++){
if(device.getName().equals(pairedDevices.get(a))){
//apend
s="(Paired)";
break;
}
}
listAdapter.add(device.getName()+"\n"+s+device.getAddress());
}
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action));{
// Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_LONG).show();
}
if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
// Toast.makeText(getApplicationContext(),"state",Toast.LENGTH_LONG).show();
}
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
//Toast.makeText(getApplicationContext(),"finish",Toast.LENGTH_LONG).show();
}
}
};
registerReceiver(receiver,filter);
filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver,filter);
filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver,filter);
filter=new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver,filter);
connectNew=(Button)findViewById(R.id.button);
listView=(ListView)findViewById(R.id.listView);
listAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
listView.setAdapter(listAdapter);
pairedDevices=new ArrayList<String>();
listView.setOnItemClickListener(this);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
finish();
}
}
private void getpairedDevices(){
deviceArray=btAdapter.getBondedDevices();
if(deviceArray.size()>0){
for(BluetoothDevice device:deviceArray){
pairedDevices.add(device.getName());
}
}
}
public void TurnOn(View view) {
btAdapter.enable();
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//
if (btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if (listAdapter.getItem(arg2).contains("Paired")){
BluetoothDevice selectedDevice = devices.get(arg2);
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
}
else{
Toast.makeText(getApplicationContext(), "device is not paired", Toast.LENGTH_LONG).show();
}
}
public void Discovery(View view) {
startDiscovery();
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Log.i(tag, "construct");
// Get a BluetoothSocket to connect with the given BluetoothDevice
// Toast.makeText(getApplicationContext(),"client thread is working",Toast.LENGTH_LONG).show();
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
// Log.i(tag, "get socket failed");
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
btAdapter.cancelDiscovery();
//Log.i(tag, "connect - run");
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Log.i(tag, "connect - succeeded");
} catch (IOException connectException) { //Log.i(tag, "connect failed");
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
//
Toast.makeText(getApplicationContext(),"reached the handler",Toast.LENGTH_LONG).show();
mhandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
Toast.makeText(getApplicationContext(),"Socket Thread is working",Toast.LENGTH_LONG).show();
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mhandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
、これはlogcatで
D/BluetoothUtilsを思われるものをレイアウト
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="leen.ibrahim.omar.bsapp.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="BLUETOOTH" android:id="@+id/textView" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Go" android:onClick="Discovery" android:id="@+id/button" android:layout_below="@+id/textView" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/listView" android:layout_below="@+id/button" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="47dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enaple" android:id="@+id/button2" android:layout_below="@+id/textView" android:onClick="TurnOn" android:layout_centerHorizontal="true" /> </RelativeLayout>
このです:開始isSocketAllowedBySecurityPolicy:デバイスヌル
W/BluetoothAdapter: Bluetで呼び出されたgetBluetoothService() oothManagerCallback
D/BluetoothSocket:INIT、MPFD: {ParcelFileDescriptor:のFileDescriptor [62]}