2010-09-20 152 views
0

我想在android中以編程方式激活藍牙,並且應用程序安裝正常,但是當我點擊按鈕激活BT時,它會發出異常。我無法處理這個例外。任何幫助是極大的讚賞。我是新來的。這裏是代碼:安卓藍牙激活錯誤

package com.example.helloandroid2; 


import java.io.IOException; 

import android.app.Activity; 
import android.bluetooth.BluetoothAdapter; 
import android.content.Context; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 

public class HelloAndroid extends Activity { 
// Declare our Views, so we can access them later 

private Button activate_buletooth; 
    static final int REQUEST_ENABLE_BT = 0; 
    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // Set Activity Layout 
     setContentView(R.layout.main); 

     activate_buletooth = (Button)findViewById(R.id.activate_buletooth); 

     // Set Click Listener 

      activate_buletooth.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v){ 
      if (mBluetoothAdapter == null) { 
       // Device does not support Bluetooth 
      Context context = getApplicationContext(); 
      CharSequence text = "BT not suported"; 
      int duration = Toast.LENGTH_SHORT; 

      Toast toast = Toast.makeText(context, text, duration); 
      toast.show(); 
      }  
      if (!mBluetoothAdapter.isEnabled()) { 
       Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
       startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
      } 

      // startActivityForResult(discoverableIntent, REQUEST_ENABLE_BT); 

     } 
     }); 

    } 
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
    if(requestCode == REQUEST_ENABLE_BT) 
     { 
     if(resultCode == RESULT_CANCELED) 
      { 
     Context context = getApplicationContext(); 
     CharSequence text = "bt not available"; 
     int duration = Toast.LENGTH_SHORT; 

     Toast toast = Toast.makeText(context, text, duration); 
     toast.show(); 
      } 
     else 
      { 

      } 
     } 
    } 
} 
+0

你的例外有什麼追溯?你是否已將BLUETOOTH和BLUETOOTH_ADMIN權限添加到應用的清單中? – 2010-09-20 15:35:53

+0

我在清單中添加了BLUETOOTH_ADMIN由於我在手機上運行應用程序,因此無法獲得例外。或者我錯過了什麼? – JPro 2010-09-20 15:37:06

回答

0

這是由於默認適配器啓用藍牙所需的時間。 我有同樣的問題,我找到了它。

這個onClick()事件在適配器切換藍牙之前被執行後,預計將被「執行」的代碼。 可以有一個解決方案,像有一個循環,它不會允許進一步的代碼執行,直到藍牙完全打開。或者 可以有一個setDelay()類型的方法可以幫助。

歡迎任何進一步的幫助。