2017-02-20 1 views
0

UART를 사용하는 센서로 작동하는 모바일 앱을 개발 중입니다. 예 : official github page은 완벽하지만 작동하지 않는 코드를 추출합니다. 내가 바꾼 유일한 것은 장치 검색이지만,이 코드는 Polar H7 장치 (장치 이름과 장치 주소를 발견하고 다음 활동으로 보내는 것)와 완벽하게 작동합니다. 내가 UART 장치에 연결을 시도하고이 활동에, 여기에 코드입니다 :Android에서 UART 서비스를 초기화 할 수 없습니다.

공용 클래스 UartRecordingActivity이 AppCompatActivity {

private final static String TAG = UartRecordingActivity.class.getSimpleName(); 

// BLE stuff 
public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME"; 
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS"; 


//private BleService bleService; 

private String deviceName; 
private String deviceAddress; 

//private BleServicesAdapter gattServiceAdapter; 

private boolean isConnected = false; 



private static final int REQUEST_SELECT_DEVICE = 1; 
private static final int REQUEST_ENABLE_BT = 2; 
private static final int UART_PROFILE_READY = 10; 
private static final int UART_PROFILE_CONNECTED = 20; 
private static final int UART_PROFILE_DISCONNECTED = 21; 
private static final int STATE_OFF = 10; 
private int mState = UART_PROFILE_DISCONNECTED; 

private UartService mService = null; 
private BluetoothDevice mDevice = null; 
private BluetoothAdapter mBtAdapter = null; 


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

    Log.i(TAG, "onCreate"); 

    final Intent intent = getIntent(); 
    deviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME); 
    deviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS); 

    final Intent gattServiceIntent = new Intent(this, UartService.class); 
    bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE); 

} 

@Override 
protected void onStart() { 
    super.onStart(); 

    mBtAdapter = BluetoothAdapter.getDefaultAdapter(); 
    service_init(); 

    mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress); 
    mService.connect(deviceAddress); 
} 

private void service_init() { 
    Intent bindIntent = new Intent(this, UartService.class); 
    bindService(bindIntent, mServiceConnection, BIND_AUTO_CREATE); 

    LocalBroadcastManager.getInstance(this).registerReceiver(UARTStatusChangeReceiver, 
      makeGattUpdateIntentFilter()); 
} 

//UART service connected/disconnected 
private ServiceConnection mServiceConnection = new ServiceConnection() { 
    public void onServiceConnected(ComponentName className, IBinder rawBinder) { 
     mService = ((UartService.LocalBinder) rawBinder).getService(); 
     Log.d(TAG, "onServiceConnected mService= " + mService); 
     if (!mService.initialize()) { 
      Log.e(TAG, "Unable to initialize Bluetooth"); 
      finish(); 
     } 

    } 


    public void onServiceDisconnected(ComponentName classname) { 
     mService = null; 
    } 
}; 


@Override 
public boolean onOptionsItemSelected(MenuItem menuItem) { 
    if (menuItem.getItemId() == android.R.id.home) { 
     Intent intent = new Intent(this, HomeActivity.class); 
     startActivity(intent); 
    } 
    return super.onOptionsItemSelected(menuItem);} 

민간 최종 브로드 캐스트 리시버 UARTStatusChangeReceiver = 새로운 브로드 캐스트 리시버() { @Override 공공 무효를 확장 onReceive (컨텍스트 컨텍스트, 의도 의도) { String action = intent.getAction();

final Intent mIntent = intent; 
    //*********************// 
    if (action.equals(UartService.ACTION_GATT_CONNECTED)) { 
     runOnUiThread(new Runnable() { 
      public void run() { 
       String currentDateTimeString = DateFormat.getTimeInstance().format(new Date()); 
       Log.d(TAG, "UART_CONNECT_MSG"); 

       mState = UART_PROFILE_CONNECTED; 
      } 
     }); 
    } 

    //*********************// 
    if (action.equals(UartService.ACTION_GATT_DISCONNECTED)) { 

     runOnUiThread(new Runnable() { 
      public void run() { 
       String currentDateTimeString = DateFormat.getTimeInstance().format(new Date()); 
       Log.d(TAG, "UART_DISCONNECT_MSG"); 
       mState = UART_PROFILE_DISCONNECTED; 
       mService.close(); 
      } 
     }); 
    } 

    //*********************// 
    if (action.equals(UartService.ACTION_GATT_SERVICES_DISCOVERED)) { 
     mService.enableTXNotification(); 
    } 
    //*********************// 
    if (action.equals(UartService.ACTION_DATA_AVAILABLE)) { 
     Log.i("data","received"); 
     final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA); 
     //handle data 
    } 
    //*********************// 
    if (action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_UART)) { 
    } 

} 

}};

private static IntentFilter makeGattUpdateIntentFilter() { 
    final IntentFilter intentFilter = new IntentFilter(); 
    intentFilter.addAction(UartService.ACTION_GATT_CONNECTED); 
    intentFilter.addAction(UartService.ACTION_GATT_DISCONNECTED); 
    intentFilter.addAction(UartService.ACTION_GATT_SERVICES_DISCOVERED); 
    intentFilter.addAction(UartService.ACTION_DATA_AVAILABLE); 
    intentFilter.addAction(UartService.DEVICE_DOES_NOT_SUPPORT_UART); 
    return intentFilter; 
}} 

오류가이 선에 의해 발생 (mService는 NullPointerException이 원인 :. 당신이 bindService를 호출 할 때 때문에 바인딩하여 서비스에 연결되어

mService.connect(deviceAddress); 

답변

1

방법 OnServiceConnected이 보장 ONSTART 콜백에서 당신은 NullPointer이 연결하기에 약간의 시간이 필요합니다. 코드를 다음과 같이 만드십시오 :

public void onServiceConnected(ComponentName className, IBinder rawBinder) { 
    mService = ((UartService.LocalBinder) rawBinder).getService(); 
    Log.d(TAG, "onServiceConnected mService= " + mService); 
    if (!mService.initialize()) { 
     Log.e(TAG, "Unable to initialize Bluetooth"); 
     finish(); 
    } 
    mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress); 
    mService.connect(deviceAddress); 
} 
관련 문제