扫描服务上的BLE设备

时间:2014-11-19 08:56:43

标签: android android-service bluetooth-lowenergy

服务

package com.example.deneme312;

import java.util.ArrayList;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class mservice extends Service implements LeScanCallback {


    private static String mBluetoothDeviceAddress = null;
    private ArrayList<BluetoothDevice> mDevices= new ArrayList<BluetoothDevice>();
    private BluetoothGatt mConnectedGatt;
    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothGatt mBluetoothGatt;


    private static int mConnectionState;
    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;
    private static final int REQUEST_ENABLE_BT = 0;
    private static final Handler mHandler = null;


    public void startscanning (){
        mHandler.post(mStartRunnable);
        mHandler.postDelayed(mStopRunnable, 3000);
    }

    Handler mhandler = new Handler();
    private final IBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        mservice getService() {
            // Return this instance of LocalService so clients can call public
            // methods
            return mservice.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {

        return mBinder;
    }

    @Override
    public void onCreate() {
        mBluetoothManager=(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter= mBluetoothManager.getAdapter();
        super.onCreate();
    }


    @Override
    public void onRebind(Intent intent) {
        // TODO Auto-generated method stub
        super.onRebind(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // TODO Auto-generated method stub
        return super.onUnbind(intent);
    }


    final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
            // TODO Auto-generated method stub
            super.onConnectionStateChange(gatt, status, newState);

            if (newState == BluetoothProfile.STATE_CONNECTED) {

                Toast.makeText(getApplicationContext(), "baglanti kuruldu", Toast.LENGTH_SHORT).show();

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                Toast.makeText(getApplicationContext(), "baglanti kesildi", Toast.LENGTH_SHORT).show();

            }


        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            // TODO Auto-generated method stub
            super.onServicesDiscovered(gatt, status);
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic, int status) {
            // TODO Auto-generated method stub
            super.onCharacteristicRead(gatt, characteristic, status);
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic, int status) {
            // TODO Auto-generated method stub
            super.onCharacteristicWrite(gatt, characteristic, status);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic) {
            // TODO Auto-generated method stub
            super.onCharacteristicChanged(gatt, characteristic);
            Toast.makeText(getApplicationContext(), "char changed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt,
                BluetoothGattDescriptor descriptor, int status) {
            // TODO Auto-generated method stub
            super.onDescriptorRead(gatt, descriptor, status);
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt,
                BluetoothGattDescriptor descriptor, int status) {
            // TODO Auto-generated method stub
            super.onDescriptorWrite(gatt, descriptor, status);
        }

        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
            // TODO Auto-generated method stub
            super.onReliableWriteCompleted(gatt, status);
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            // TODO Auto-generated method stub
            super.onReadRemoteRssi(gatt, rssi, status);
        }


    };
    private Runnable mStopRunnable = new Runnable() {
        @Override
        public void run() {
            stopScan();
        }
    };
    private Runnable mStartRunnable = new Runnable() {
        @Override
        public void run() {
            startScan();
        }
    };

    public void startScan() {
        mBluetoothAdapter.startLeScan(this);

    }

    public void stopScan() {
        mBluetoothAdapter.stopLeScan(this);

    }


    @Override
    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
        stopScan();
        connect(device.getName());

    }
    public boolean connect(final String address) {
        String TAG="connecting situation";
        if (mBluetoothAdapter == null || address == null) {
            Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }


        // Previously connected device.  Try to reconnect.
        if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
                && mBluetoothGatt != null) {
            Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
            if (mBluetoothGatt.connect()) {
                mConnectionState = STATE_CONNECTING;
                return true;
            } else {
                return false;
            }
        }

        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            Log.w(TAG, "Device not found.  Unable to connect.");
            return false;
        }
        // We want to directly connect to the device, so we are setting the autoConnect
        // parameter to false.
        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
        Log.d(TAG, "Trying to create a new connection.");
        mBluetoothDeviceAddress = address;
        mConnectionState = STATE_CONNECTING;
        return true;
    }

}

活性

package com.example.deneme312;


import com.example.deneme312.mservice.LocalBinder;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothManager;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
    private static final String TAG = null;

    Button mb;

    private boolean mBound1;
    mservice mService;
    boolean mBound = false;
    int clc = 0;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mb = (Button) findViewById(R.id.start_fragment);
        mb.setOnClickListener(this);

    }

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent(this, mservice.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == R.id.start_fragment) {
            mService.startscanning();

        }
    }



    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            // We've bound to LocalService, cast the IBinder and get
            // LocalService instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound1 = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound1 = false;
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound1) {
            unbindService(mConnection);
            mBound1 = false;
        }
    }

}

现在这里的代码不起作用。有一些活动绑定了一个服务,并从服务中调用一个函数(startscanning),试图从那个服务中找到可用的设备,并且它对于那些类型的任何想法都是错误的。错误????在此先感谢

11-19 11:30:47.275: E/AndroidRuntime(27612): FATAL EXCEPTION: main
11-19 11:30:47.275: E/AndroidRuntime(27612): java.lang.NullPointerException
11-19 11:30:47.275: E/AndroidRuntime(27612):    at com.example.deneme312.mservice.startscanning(mservice.java:43)
11-19 11:30:47.275: E/AndroidRuntime(27612):    at com.example.deneme312.MainActivity.onClick(MainActivity.java:55)
11-19 11:30:47.275: E/AndroidRuntime(27612):    at android.view.View.performClick(View.java:4475)
11-19 11:30:47.275: E/AndroidRuntime(27612):    at android.view.View$PerformClick.run(View.java:18786)
11-19 11:30:47.275: E/AndroidRuntime(27612):    at android.os.Handler.handleCallback(Handler.java:730)
11-19 11:30:47.275: E/AndroidRuntime(27612):    at android.os.Handler.dispatchMessage(Handler.java:92)
11-19 11:30:47.275: E/AndroidRuntime(27612):    at android.os.Looper.loop(Looper.java:176)
11-19 11:30:47.275: E/AndroidRuntime(27612):    at android.app.ActivityThread.main(ActivityThread.java:5419)
11-19 11:30:47.275: E/AndroidRuntime(27612):    at java.lang.reflect.Method.invokeNative(Native Method)
11-19 11:30:47.275: E/AndroidRuntime(27612):    at java.lang.reflect.Method.invoke(Method.java:525)
11-19 11:30:47.275: E/AndroidRuntime(27612):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
11-19 11:30:47.275: E/AndroidRuntime(27612):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
11-19 11:30:47.275: E/AndroidRuntime(27612):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

您正在使用静态变量mHandler

private static final Handler mHandler = null; // H is caps

再次初始化另一个变量

Handler mhandler = new Handler();  // h is small letter

删除     private static final Handler mHandler = null;

并使用以下代码

 Handler mhandler = new Handler(); 
 public void startscanning (){
    mhandler.post(mStartRunnable);
    mhandler.postDelayed(mStopRunnable, 3000);
}