【发布时间】:2014-12-11 22:35:38
【问题描述】:
我正在编写一个 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();
}
它没有工作。它给出了一个错误不幸的是应用程序已停止,并且在 Eclipse 中我找不到源。
有什么问题? 我认为如果 (!btadapter.isEnabled()) 造成了一些问题。
【问题讨论】:
-
在“turnOnintent”和以下行设置一些断点,这样你就可以看到异常。异常可能是在 startActivity 行抛出