2014-12-05 146 views
0

我正在编写一个Android应用程序,用于将计步器与使用蓝牙的Android应用程序进行接口连接。 这里是蓝牙Android蓝牙编程

package com.example.bluetooth_demo; 

import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.bluetooth.BluetoothAdapter; 
import android.content.Intent; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.Toast; 


public class Simer extends ActionBarActivity { 
    ArrayAdapter<String> listadapter ; 
    Button connectnew; 
    BluetoothAdapter btadapter; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_simer); 

     init(); 
     if(btadapter==null){ 
      Toast.makeText(getApplicationContext(), "No bluetooth", 0).show(); 
      finish(); 
     } 
     else{ 
      if (!btadapter.isEnabled()) { 
       Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
       startActivityForResult(turnOnIntent, 1); 

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


     } 

    } 
private void init(){ 

connectnew = (Button)findViewById(R.id.button1); 
btadapter = BluetoothAdapter.getDefaultAdapter(); 

} 

    } 

我的示例代码,它工作正常,直到我编程高达

if(btadapter==null){ 
       Toast.makeText(getApplicationContext(), "No bluetooth", 0).show(); 
       finish(); 
      } 

但是当我加入如下代码

if (!btadapter.isEnabled()) { 
        Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
        startActivityForResult(turnOnIntent, 1); 

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

没有奏效。它给出了一个错误不幸的是,应用程序已停止,并在日食我没有找到源。

什么问题? 我想如果(!btadapter.isEnabled())正在创建一些问题。

+0

在“turnOnintent”和跟随行上设置一些断点,以便您可以看到异常。 startActivity行可能会引发异常 – 2014-12-05 12:12:14

回答

0

其实问题是,我没有添加蓝牙清单文件的权限,添加以下行后它工作正常。

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