Can't get bluetooth Adapter in Android

别说谁变了你拦得住时间么 提交于 2020-01-05 08:09:13

问题


I was trying to implement the bluetooth chat example given in the android samples. I am running it on a jelly beans device which has Android 4.1 version running on it .

The application simply force closes. A part of launcher activity code of launcher activity goes like this.

WHEN I COMMENT THE LINE "mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();" THE APPLICATION DOES NOT FORCE CLOSE. and all the toast messages are also displayed which are not with the line uncommented

    private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
private BluetoothChatService mChatService = null;


@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

     Toast.makeText(getApplicationContext(),"BluetothChat oncreate()", Toast.LENGTH_LONG).show();
    if(D) Log.e(TAG, "+++ ON CREATE +++");

    // Set up the window layout
    setContentView(R.layout.main);

    // Get local Bluetooth adapter
  try {     

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

   //}
    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }     
 } catch (Exception e) {
       Toast.makeText(this,e.toString(), Toast.LENGTH_LONG).show(); 

 }
}

@Override
public void onStart() {



    Toast.makeText(getApplicationContext(),"BluetothChat onstart()", Toast.LENGTH_LONG).show();
    super.onStart();
    if(D) Log.e(TAG, "++ ON START ++");

    // If BT is not on, request that it be enabled.
    // setupChat() will then be called during onActivityResult
    try {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the chat session
        } else {
            if (mChatService == null) {
                setupChat();
            }
        }
    } catch (Exception e) {
     Toast.makeText(this,e.toString(), Toast.LENGTH_LONG).show(); 
    }


}

来源:https://stackoverflow.com/questions/13339542/cant-get-bluetooth-adapter-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!