蓝牙适配器在android中保持为null

时间:2014-01-02 08:21:04

标签: java android xml eclipse bluetooth

我在android中编写蓝牙适配器代码时遇到问题。蓝牙适配器始终保持为空。我已经为此编写了代码,但我无法打开蓝牙。

我的代码如下

package com.example.bluetoothdemo;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


    @SuppressLint("NewApi")
    public class MainActivity extends Activity {


        String msg="Hello";/* Default message to be sent. */
        BluetoothAdapter adpt=null;// Default it is set to null value.
        public static String MacAddress;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Button btn=(Button)findViewById(R.id.button_send);
            final TextView tv=(TextView)findViewById(R.id.disp_msg);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    adpt=BluetoothAdapter.getDefaultAdapter();

                    if(adpt==null){
                                         // Always this portion is generating errors.
                        tv.append("Bluetooth Not Available in device");
                        Toast.makeText(getApplicationContext(), "Bluetooth is off",Toast.LENGTH_LONG).show();
                    }
                    else{
                        if(!adpt.isEnabled()){
                            //adpt.enable();
                            Intent i=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                            //startActivity(i);
                            startActivityForResult(i, 0);
                            tv.append("Bluetooth is turned on.");
                        }
                    }

                    byte[] toSend=msg.getBytes();

                    try{
                        final UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
                        BluetoothDevice device=adpt.getRemoteDevice(MacAddress);
                        BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
                        socket.connect();
                        OutputStream mmout=socket.getOutputStream();
                        mmout.write(toSend);
                        mmout.flush();
                        mmout.close();
                        socket.close();
                        Toast.makeText(getBaseContext(), MacAddress, Toast.LENGTH_SHORT).show();
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                }
            });
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

    }

我的activity_main.xml文件如下:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal">


      <EditText android:id="@+id/edit_message"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="@string/edit_message" />


       <Button android:id="@+id/button_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_send"
            android:onClick="sendMessage" />

        <TextView android:id="@+id/disp_msg"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/display"
            />
            </LinearLayout>

我的AndroidMenifest.xml文件如下:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.bluetoothdemo"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" />
        <uses-permission android:name="android.permission.BLUETOOTH" />
        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.example.bluetoothdemo.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
     </manifest>-

我也创建了.apk文件并在我的Micromax A89 Ninja手机上运行,​​但错误显示“BluetoothDemo已意外停止。”

1 个答案:

答案 0 :(得分:0)

请写下面的一行

adpt=BluetoothAdapter.getDefaultAdapter();

在此行之后的OnCreate()方法中

setContentView(R.layout.activity_main);