2017-01-08 5 views
0

In meinem Code, nachdem ich startDiscovery() ausgeführt habe. Nichts scheint zu passieren und ich weiß nicht warum. Wie @Mitch vorgeschlagen habe, habe ich zurück zur Schaltfläche StartDiscovery wechseln gewechselt. Aber jetzt scheint es schlimmer, da es direkt nach dem Drücken der Taste abstürzt.Android Studio Bluetooth startDiscovey funktioniert nicht

public class BTActivity extends AppCompatActivity{ 
    private static final String TAG = "BTActivity"; 
    BluetoothAdapter BTAdapter; 
    public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>(); 
    public DeviceListAdapter mDeviceListAdapter; 
    ListView lvNewDevices; 


    private EcgView mEcgView; 

    //Create a BroadcastReceiver for 
    private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      if (action.equals(BTAdapter.ACTION_STATE_CHANGED)){ 
       final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BTAdapter.ERROR); 

       switch (state){ 
        case BluetoothAdapter.STATE_OFF: 
         Log.d(TAG,"onReceive: STATE OFF"); 
         break; 
        case BluetoothAdapter.STATE_TURNING_OFF: 
         Log.d(TAG,"onReceive: STATE TURNING OFF"); 
         break; 
        case BluetoothAdapter.STATE_ON: 
         Log.d(TAG,"onReceive: STATE ON"); 
         break; 
        case BluetoothAdapter.STATE_TURNING_ON: 
         Log.d(TAG,"onReceive: STATE TURNING ON"); 
         break; 
       } 
      } 
     } 
    }; 

    private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      final String action = intent.getAction(); 
      if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)){ 
       int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR); 

       switch (mode){ 
        case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE: 
         Log.d(TAG,"mBroadcastReceiver2: Discoverability Enabled"); 
         break; 
        case BluetoothAdapter.SCAN_MODE_CONNECTABLE: 
         Log.d(TAG,"mBroadcastReceiver2: Discoverability Disabled. Able to receive connection"); 
         break; 
        case BluetoothAdapter.SCAN_MODE_NONE: 
         Log.d(TAG,"mBroadcastReceiver2: Discoverability Disabled. Not able to receive connection"); 
         break; 
        case BluetoothAdapter.STATE_CONNECTING: 
         Log.d(TAG,"mBroadcastReceiver2: Connecting"); 
         break; 
        case BluetoothAdapter.STATE_CONNECTED: 
         Log.d(TAG,"mBroadcastReceiver2: Connected"); 
         break; 
       } 
      } 
     } 
    }; 

    private final BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      final String action = intent.getAction(); 
      Log.d(TAG, "OnReceive: ACTION FOUND"); 

      if (action.equals(BluetoothDevice.ACTION_FOUND)) { 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       mBTDevices.add(device); 
       Log.d(TAG, "OnReceive: " + device.getName() + ": " + device.getAddress()); 
       mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices); 
       lvNewDevices.setAdapter(mDeviceListAdapter); 
      } 
     } 
    }; 

    private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 

      if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) { 
       BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       //3cases: 
       if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){ 
        Log.d(TAG, "BroadcastReceiver: BOND_BOUNDED"); 
       } 

       if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING){ 
        Log.d(TAG, "BroadcastReceiver: BOND_BOUNDING"); 
       } 

       if (mDevice.getBondState() == BluetoothDevice.BOND_NONE){ 
        Log.d(TAG, "BroadcastReceiver: BOND_NONE"); 
       } 
      } 
     } 
    }; 

    protected void onDestroy(){ 
     super.onDestroy(); 
     unregisterReceiver(mBroadcastReceiver1); 
     unregisterReceiver(mBroadcastReceiver2); 
     unregisterReceiver(mBroadcastReceiver3); 
     unregisterReceiver(mBroadcastReceiver4); 
    } 

    public boolean onCreateOptionsMenu (Menu menu){ 

     MenuInflater menuInflater = getMenuInflater(); 
     menuInflater.inflate(R.menu.main_menu,menu); 


     return super.onCreateOptionsMenu(menu); 
    } 

    public boolean onOptionsItemSelected(MenuItem item) { 
     super.onOptionsItemSelected(item); 

     switch (item.getItemId()) { 
      case R.id.enabledisable: 
       //if BT is enable, turn it off; if not then prompt user to enable BT; 
       if (!BTAdapter.getDefaultAdapter().isEnabled()) { 
        Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
        startActivity(i); 
        IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); 
        registerReceiver(mBroadcastReceiver1, BTIntent); 
       } 

       if(BTAdapter.getDefaultAdapter().isEnabled()) { 
        BTAdapter.getDefaultAdapter().disable(); 
        IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); 
        registerReceiver(mBroadcastReceiver1, BTIntent); 
       } 
       return true; 

      case R.id.enablediscoverable: 
       Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
       discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); 
       startActivity(discoverableIntent); 

       IntentFilter intentFilter = new IntentFilter(BTAdapter.ACTION_SCAN_MODE_CHANGED); 
       registerReceiver(mBroadcastReceiver2, intentFilter); 
       return true; 

      case R.id.discover: 

       Intent intent = new Intent(getApplicationContext(),SearchActivity.class); 
       startActivity(intent); 
       /* 
       Log.d(TAG,"Looking for unpaired devices"); 
       if (BTAdapter.isDiscovering()){ 
        BTAdapter.cancelDiscovery(); 
        Log.d(TAG,"Canceling Discovery"); 

        //checkBTPermissions(); 

        BTAdapter.startDiscovery(); 
        IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
        registerReceiver(mBroadcastReceiver3, discoverDevicesIntent); 
       } 
       if (!BTAdapter.isDiscovering()){ 
        //checkBTPermissions(); 
        Log.d(TAG,"Searching Now"); 

        BTAdapter.startDiscovery(); 
        Log.d(TAG,"Still Searching Now"); 
        IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
        registerReceiver(mBroadcastReceiver3, discoverDevicesIntent); 
        Log.d(TAG,"123"); 
       } 
       */ 
       return true; 

      default: 
       return false; 
     } 
    } 

/* 
    private void checkBTPermissions() { 
     if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){ 
      int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATATION"); 
      permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION"); 
      if (permissionCheck != 0){ 
       this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); 
      } 
     else{ 
       Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK Version < LOLLIPOP"); 
      } 
     } 
    } 
*/ 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_bt); 
     lvNewDevices = (ListView) findViewById(R.id.lvNewDevices); 
     mBTDevices = new ArrayList<>(); 



     IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED); 
     registerReceiver(mBroadcastReceiver4,filter); 

     //lvNewDevices.setOnItemClickListener(BTActivity.this); 

     //Check if the phone support BT 
     BTAdapter = BluetoothAdapter.getDefaultAdapter(); 
     if (BTAdapter == null) { 
      //System.exit(0); 
     } 

     //mConnectThread = new ConnectThread(mDevice); 
     //mConnectThread.start(); 

     mEcgView = (EcgView) findViewById(R.id.ecgView); 

    } 

    public void toMainActivity(View view){ 
     Intent intent = new Intent(getApplicationContext(),MainActivity.class); 
     startActivity(intent); 
    } 
} 

Also nach dem Klick auf die Suche Geräte aus der Aktionsleiste, wird die App zu einer anderen Aktivität gehen. Aber wenn ich in dieser Aktivität auf Suche starten klicke, stürzt die App ab. Ich weiß nicht warum, denn Logik sollte die gleiche sein.

public class SearchActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { 

    private static final String TAG = "SearchActivity"; 
    BluetoothAdapter BTAdapter; 
    public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>(); 
    public DeviceListAdapter mDeviceListAdapter; 
    ListView lvNewDevices; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_search); 

     lvNewDevices = (ListView) findViewById(R.id.lvNewDevices); 
     mBTDevices = new ArrayList<>(); 

     lvNewDevices.setOnItemClickListener(SearchActivity.this); 
    } 

    private final BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      final String action = intent.getAction(); 
      Log.d(TAG, "OnReceive: ACTION FOUND"); 

      if (action.equals(BluetoothDevice.ACTION_FOUND)) { 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       mBTDevices.add(device); 
       Log.d(TAG, "OnReceive: " + device.getName() + ": " + device.getAddress()); 
       mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices); 
       lvNewDevices.setAdapter(mDeviceListAdapter); 
      } 
     } 
    }; 

    public void btnDiscover(View view){ 
     Log.d(TAG,"Looking for unpaired devices"); 
     if (BTAdapter.isDiscovering()){ 
      BTAdapter.cancelDiscovery(); 
      Log.d(TAG,"Canceling Discovery"); 

      //checkBTPermissions(); 

      BTAdapter.startDiscovery(); 
      IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
      registerReceiver(mBroadcastReceiver3, discoverDevicesIntent); 
     } 
     if (!BTAdapter.isDiscovering()){ 
      //checkBTPermissions(); 
      Log.d(TAG,"Searching Now"); 

      BTAdapter.startDiscovery(); 
      Log.d(TAG,"Still Searching Now"); 
      IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
      registerReceiver(mBroadcastReceiver3, discoverDevicesIntent); 
      Log.d(TAG,"123"); 
     } 
    } 

    public void backToBT(View view){ 
     Intent intent = new Intent(getApplicationContext(),BTActivity.class); 
     startActivity(intent); 
    } 


    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 
     //Cancel Discovery as it's costly 
     BTAdapter.cancelDiscovery(); 

     Log.d(TAG,"onItemClick:Clicked a Device"); 
     String deviceName = mBTDevices.get(i).getName(); 
     String deviceAddress = mBTDevices.get(i).getAddress(); 
     Log.d(TAG,"onItemClick: Device Name: " + deviceName); 
     Log.d(TAG,"onItemClick: Device Address " + deviceAddress); 

     //Bonding 
     if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){ 
      Log.d(TAG, "Trying to pair with " + deviceName); 
      mBTDevices.get(i).createBond(); 
     } 
    } 
} 

Und das Manifest angebracht ist

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

    <user-feature android:name="android.hardware.bluetooth" /> 

    <uses-permission android:name="android.permission.BLUETOOTH" /> 
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" /> 

    <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> 
     <activity android:name=".BTActivity" /> 
     <activity android:name=".SearchActivity"></activity> 
    </application> 

</manifest> 

Dies ist der Logcat

1-07 21:40:39.633 32744-367/com.example.ted.pawan462 I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8974_LA.BF.1.1.3_RB1__release_AU (Ia6c73e7530) 
                    OpenGL ES Shader Compiler Version: E031.29.00.00 
                    Build Date: 12/04/15 Fri 
                    Local Branch: mybranch17080070 
                    Remote Branch: quic/LA.BF.1.1.3_rb1.5 
                    Local Patches: NONE 
                    Reconstruct Branch: NOTHING 
01-07 21:40:39.635 32744-367/com.example.ted.pawan462 I/OpenGLRenderer: Initialized EGL, version 1.4 
01-07 21:40:41.786 32744-32744/com.example.ted.pawan462 I/ListPopupWindow: Could not find method setEpicenterBounds(Rect) on PopupWindow. Oh well. 
01-07 21:40:41.812 32744-32744/com.example.ted.pawan462 W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView 
01-07 21:43:54.309 32744-367/com.example.ted.pawan462 D/OpenGLRenderer: endAllStagingAnimators on 0x9db76280 (MenuPopupWindow$MenuDropDownListView) with handle 0x9d2784b0 
01-07 21:43:55.320 32744-32744/com.example.ted.pawan462 D/SearchActivity: Looking for unpaired devices 
01-07 21:43:55.327 32744-32744/com.example.ted.pawan462 D/AndroidRuntime: Shutting down VM 
01-07 21:43:55.329 32744-32744/com.example.ted.pawan462 E/AndroidRuntime: FATAL EXCEPTION: main 
                      Process: com.example.ted.pawan462, PID: 32744 
                      Theme: themes:{default=overlay:com.wsdeveloper.galaxys7, iconPack:com.wsdeveloper.galaxys7, fontPkg:com.wsdeveloper.galaxys7, com.android.systemui=overlay:com.wsdeveloper.galaxys7, com.android.systemui.navbar=overlay:com.wsdeveloper.galaxys7} 
                      java.lang.IllegalStateException: Could not execute method for android:onClick 
                       at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293) 
                       at android.view.View.performClick(View.java:5204) 
                       at android.view.View$PerformClick.run(View.java:21158) 
                       at android.os.Handler.handleCallback(Handler.java:739) 
                       at android.os.Handler.dispatchMessage(Handler.java:95) 
                       at android.os.Looper.loop(Looper.java:148) 
                       at android.app.ActivityThread.main(ActivityThread.java:5461) 
                       at java.lang.reflect.Method.invoke(Native Method) 
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
                      Caused by: java.lang.reflect.InvocationTargetException 
                       at java.lang.reflect.Method.invoke(Native Method) 
                       at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                       at android.view.View.performClick(View.java:5204)  
                       at android.view.View$PerformClick.run(View.java:21158)  
                       at android.os.Handler.handleCallback(Handler.java:739)  
                       at android.os.Handler.dispatchMessage(Handler.java:95)  
                       at android.os.Looper.loop(Looper.java:148)  
                       at android.app.ActivityThread.main(ActivityThread.java:5461)  
                       at java.lang.reflect.Method.invoke(Native Method)  
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  
                      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isDiscovering()' on a null object reference 
                       at com.example.ted.pawan462.SearchActivity.btnDiscover(SearchActivity.java:58) 
                       at java.lang.reflect.Method.invoke(Native Method)  
                       at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)  
                       at android.view.View.performClick(View.java:5204)  
                       at android.view.View$PerformClick.run(View.java:21158)  
                       at android.os.Handler.handleCallback(Handler.java:739)  
                       at android.os.Handler.dispatchMessage(Handler.java:95)  
                       at android.os.Looper.loop(Looper.java:148)  
                       at android.app.ActivityThread.main(ActivityThread.java:5461)  
                       at java.lang.reflect.Method.invoke(Native Method)  
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  

Ich glaube, ich könnte es noch schlimmer gemacht haben.

Antwort

0

Das einzige, was mir auffällt ist, dass Sie checkBTPermissions() kommentiert haben. Aber ich gehe davon aus, dass Sie das auskommentiert haben.

Vergewissern Sie sich auch, dass Ihre anderen Geräte auf "Erkennbar" eingestellt sind oder das Telefon sie nicht sehen kann.

Ansonsten denke ich, dass es ziemlich gut aussieht. Vielleicht etwas Seltsames, weil du ein Menü benutzt? Nicht sicher :(.

+0

Ich sehe nicht, wo Sie Ihren BluetoothAdapter (mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();) für eine Sache erklärt haben.Kleben Sie das einfach in Ihre onCreate-Methode. – mitch

Verwandte Themen