2016-01-14 3 views
0

я пытался использовать Bluetooth общаются между Arduino и Bluetooth и нет никаких ошибок по сборке скажите мне, что это неправильно я имел проблемы с IO Exception, но он решил сейчас .. ., может быть, приложение просто падает, когда я пытаюсь запустить его на телефоне помочь мне я не так хорош в JavaAndroid Arduino Bluetooth сбой связи при запуске

package com.example.administrator.myapplication; 

    import android.support.v7.app.AppCompatActivity; 
    import android.os.Bundle; 
    import android.os.Bundle; 
    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 java.util.Set; 
    import android.content.Intent; 
    import android.content.IntentFilter; 
    import android.view.View; 
    import android.view.View.OnClickListener; 
    import android.widget.ArrayAdapter; 
    import android.widget.Button; 
    import android.widget.ListView; 
    import android.widget.TextView; 
    import android.widget.Toast; 
    import java.io.FileOutputStream; 
    import java.io.IOException; 
    import java.io.OutputStream; 
    import java.io.InputStream; 
    import android.os.ParcelUuid; 





    public class MainActivity extends AppCompatActivity { 

    private static final int REQUEST_ENABLE_BT = 1; 
    private Button onBtn, offBtn ,listBtn ,findBtn; 
    private TextView text; 

    private Button UpBtn ,DownBtn ,LeftBtn ,RightBtn; 

    private BluetoothAdapter myBluetoothAdapter; 
    private Set<BluetoothDevice> pairedDevices; 
    private ListView myListView; 
    private ArrayAdapter<String> BTArrayAdapter; 
    private OutputStream outputStream; 
    private InputStream inStream; 


    protected void onCreate(Bundle savedInstanceState){ 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
     Set<BluetoothDevice> bondedDevices = myBluetoothAdapter.getBondedDevices(); 

     if (myBluetoothAdapter == null) { 
      onBtn.setEnabled(false); 
      offBtn.setEnabled(false); 
      listBtn.setEnabled(false); 
      findBtn.setEnabled(false); 
      UpBtn.setEnabled(false); 
      DownBtn.setEnabled(false); 
      LeftBtn.setEnabled(false); 
      RightBtn.setEnabled(false); 

      text.setText("Status: not supported"); 

      Toast.makeText(getApplicationContext(), "Your device does not support Bluetooth", 
        Toast.LENGTH_LONG).show(); 
     } else { 

      if(bondedDevices.size() > 0){ 

       BluetoothDevice[] devices = (BluetoothDevice[]) bondedDevices.toArray(); 
       BluetoothDevice device = devices[0]; 
       ParcelUuid[] uuids = device.getUuids(); 
       try{ 
        BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid()); 
        socket.connect(); 
        outputStream = socket.getOutputStream(); 
        inStream = socket.getInputStream(); 
       } catch (IOException e){ 

       } 
      } 




      //Movement 
      UpBtn = (Button) findViewById(R.id.Upbutton); 
      DownBtn = (Button) findViewById(R.id.Downbutton); 
      LeftBtn = (Button) findViewById(R.id.Leftbutton); 
      RightBtn = (Button) findViewById(R.id.Rightbutton); 

      UpBtn.setOnClickListener(new OnClickListener() { 
       @Override public void onClick(View v) { 
        try { 
         C(v, 8); 
        } 
         catch (IOException e){ 

          System.out.println("3 SEND FAILED"); 
         } 

       } 
      }); 

      DownBtn.setOnClickListener(new OnClickListener() { 
       @Override public void onClick(View v) { 
        try { 
         C(v, 2); 
        } catch (IOException e) { 
         System.out.println("2 SEND FAILED"); 
        } 
       } 
      }); 

      LeftBtn.setOnClickListener(new OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        try { 
         C(v, 4); 
        } catch (IOException e) { 
         System.out.println(" 4 SEND FAILED"); 
        } 

       } 
      }); 

      RightBtn.setOnClickListener(new OnClickListener() { 
       @Override 
       public void onClick(View v){ 
        try { 
         C(v, 6); 
        } catch (IOException e) { 
         System.out.println(" 6 SEND FAILED"); 
        } 
       } 
      } 
      ); 

      //......................... 
      //.................. 
      //Normal Code 
      text = (TextView) findViewById(R.id.textView); 
      //text.setText ("" + myBluetoothAdapter.getName()); 



      onBtn = (Button) findViewById(R.id.Onbutton); 
      onBtn.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        on(v); 
       } 
      }); 

      offBtn = (Button) findViewById(R.id.Offbutton); 
      offBtn.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        off(v); 
       } 
      }); 

      listBtn = (Button) findViewById(R.id.Listbutton); 
      listBtn.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        list(v); 
       } 
      }); 

      findBtn = (Button) findViewById(R.id.Pairedbutton); 
      findBtn.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        find(v); 
       } 
      }); 

      myListView = (ListView) findViewById(R.id.listView1); 

      // create the arrayAdapter that contains the BTDevices, and set it to the ListView 
      BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); 
      myListView.setAdapter(BTArrayAdapter); 
     } 
    } 

    public void on(View view) { 
     if (!myBluetoothAdapter.isEnabled()) { 
      Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT); 

      Toast.makeText(getApplicationContext(), "Bluetooth turned on", 
        Toast.LENGTH_LONG).show(); 
     } else { 
      Toast.makeText(getApplicationContext(), "Bluetooth is already on", 
        Toast.LENGTH_LONG).show(); 
     } 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     // TODO Auto-generated method stub 
     if (requestCode == REQUEST_ENABLE_BT) { 
      if (myBluetoothAdapter.isEnabled()) { 
       text.setText("Status: Enabled"); 
      } else { 
       text.setText("Status: Disabled"); 
      } 
     } 
    } 

    public void list(View view) { 
     // get paired devices 
     pairedDevices = myBluetoothAdapter.getBondedDevices(); 

     // put it's one to the adapter 
     for (BluetoothDevice device : pairedDevices) 
      BTArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 

     Toast.makeText(getApplicationContext(), "Show Paired Devices", 
       Toast.LENGTH_SHORT).show(); 

    } 

    final BroadcastReceiver bReceiver = new BroadcastReceiver() { 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      // When discovery finds a device 
      if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
       // Get the BluetoothDevice object from the Intent 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       // add the name and the MAC address of the object to the arrayAdapter 
       BTArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
       BTArrayAdapter.notifyDataSetChanged(); 
      } 
     } 
    }; 

    public void find(View view) { 
     if (myBluetoothAdapter.isDiscovering()) { 
      // the button is pressed when it discovers, so cancel the discovery 
      myBluetoothAdapter.cancelDiscovery(); 
     } else { 
      BTArrayAdapter.clear(); 
      myBluetoothAdapter.startDiscovery(); 

      registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); 
     } 
    } 

    public void off(View view) { 
     myBluetoothAdapter.disable(); 
     text.setText("Status: Disconnected"); 

     Toast.makeText(getApplicationContext(), "Bluetooth turned off", 
       Toast.LENGTH_LONG).show(); 
    } 

    public void C (View View , float H) throws IOException{ 
      if(H == 8){ 

        outputStream.write("8".toString().getBytes()); 
      } 
      if(H == 2){ 
        outputStream.write("2".toString().getBytes()); 
      } 
      if(H == 4){ 
        outputStream.write("4".toString().getBytes()); 
      } 
      if(H == 6){ 
        outputStream.write("6".toString().getBytes()); 
      } 

    } 


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

} 

и здесь это проявляется

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.example.administrator.myapplication" > 

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme" > 
    <activity android:name=".MainActivity" > 

     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

</manifest> 
+0

Post logcat пожалуйста. –

+0

Подождите, пока я найду его –

+0

У меня нет телефона прямо сейчас. –

ответ

0

Очень сложно указать корень проблемы без журнала, но это пример https://goo.gl/d7YD92 (от Google), который я последовал несколько месяцев назад, чтобы создать надежную связь Bluetooth с Android и arduino. Работал как заряд после нескольких часов игры с ним. Одно место, которое я также посмотрю, - это ваш манифест, чтобы убедиться, что у вас есть все необходимые разрешения.

+0

вот он, я разместил его в вопросе –

+0

Рад узнать, что это помогло. Не забудьте отметить ответ в качестве ответа :) –

1

Решил, это просто ошибка разрешения только что добавила разрешение bluetooth_admin, и это сработало! спасибо HaMiD Sani за указание на это.

Смежные вопросы