我目前正在尝试学习如何编写Android程序。我刚刚读完了“使用Android SDK构建Android应用程序的Android开发人员手册”一书。我试着编写以下代码:
Package src.com.cookbook.BlueToothSample;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class BlueToothExampleActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// button
Button startBTButton = (Button) findViewById (R.id.Start_BT);
startBTButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
startBlueTooth();
}
});
}
private void startBlueTooth()
{
Intent enableIntent = new Intent(BluetoothAdapter
.ACTION_REQUEST_ENABLE);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String acton = intent.getAction();
//When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(
BluetoothDevice.EXTRA_DEVICE);
Log.v("BlueTooth Testing", device.getName() + '\n'
+ device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
myBluetooth.startDiscover();
}
我收到以下错误:语法错误,插入“}”以完成ClassBody。 我以为我把所有支架排成一列。在阅读本论坛后,我将购买“专业Android应用程序开发人员”一书。任何帮助将不胜感激。
答案 0 :(得分:1)
此代码:
registerReceiver(mReceiver, filter);
myBluetooth.startDiscover();
必须出现在构造函数或方法中。快速浏览一下,我所看到的只是错误的,但没有任何承诺也没有。
编辑:
一种方法可能是实际上唯一有意义的方法,我的不好。
编辑:
评论中提到的包装东西......好抓@Ted
答案 1 :(得分:0)
您的java语法无效。
你不能这样做:
private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
// Code here
}
也不是直接在课堂上
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
myBluetooth.startDiscover();
答案 2 :(得分:0)
你已经在错误的地方注册了broadcastereceiver,所以来了
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
myBluetooth.startDiscover();
在oncreate()
中