BLE2

MainActivity.java

package com.example.tawara.bletest2;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

private final static String TAG = "BLECAST_BL main";

private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_ENABLE_BT = 1;
private TextView tv1;
private TextView tv2;
private TextView tv3;
private TextView tv4;
private int counter = 0;

private final int REQUEST_PERMISSION = 1000;

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

// if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_LOCATION_STATE);
// return;
// }
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,}, REQUEST_PERMISSION);

return;
}
// private boolean checkPermission() {
// if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_LOCATION_STATE);
// return false;
// }
// return true;
// }

//センサー値表示用テキストビュー
tv1 = (TextView)findViewById(R.id.textView1);
tv2 = (TextView)findViewById(R.id.textView2);
tv3 = (TextView)findViewById(R.id.textView3);
tv4 = (TextView)findViewById(R.id.textView4);

// getActionBar().setTitle("BLECAST_BL スキャン");

// if (savedInstanceState == null) {
// getFragmentManager().beginTransaction()
// .add(R.id.container, new PlaceholderFragment())
// .commit();
// }


// 対象デバイスがBLEをサポートしているかのチェック。
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "このデバイスではBLEはサポートされておりません。", Toast.LENGTH_SHORT).show();
finish();
}

// Bluetooth adapter 初期化. (API 18以上が必要)
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

// 対象デバイスBluetoothをサポートしているかのチェック.
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetoothがサポートされておりません。", Toast.LENGTH_SHORT).show();
finish();
return;
}
}

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

// Bluetooth機能が有効になっているかのチェック。無効の場合はダイアログを表示して有効をうながす。(intentにて)
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}

//Start scan
mBluetoothAdapter.startLeScan(mLeScanCallback);
}

@Override
protected void onPause() {
super.onPause();
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}

// スキャンのコールバック
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
// デバイスが発見された時
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String name = device.getName();
if(name != null){
if(name.equals("ENV_0")){
showData(device, scanRecord);
}
}
}
});
}
};

//データの表示
private void showData(BluetoothDevice device, byte[] scanRecord){
int len = scanRecord.length;
//センサー値を画面に表示
//int sensorData = (scanRecord[9]&0xFF) + ((scanRecord[10]&0xFF)*256);
int sensorData = (scanRecord[6]&0xFF) + ((scanRecord[7]&0xFF)*256);
//tv1.setText(String.valueOf(sensorData));

//湿度
int namaShitsudo = ((scanRecord[9]&0xFF)*256) + (scanRecord[10]&0xFF);
Log.d("生湿度",String.valueOf(namaShitsudo));
double soutaiShitsudo = (125 * namaShitsudo / 65536) - 6;
Log.d("相対湿度",String.valueOf(soutaiShitsudo));
tv1.setText("相対湿度" + ":" + String.valueOf(soutaiShitsudo));

//温度
int namaOndo = ((scanRecord[11]&0xFF)*256) + (scanRecord[12]&0xFF);
Log.d("生温度",String.valueOf(namaOndo));
double soutaiOndo = (175.72 * namaOndo / 65536) - 46.85;
Log.d("相対温度",String.valueOf(soutaiOndo));
tv2.setText("相対温度" + ":" + String.valueOf(soutaiOndo));

//カウンタ
counter++;
tv3.setText("カウンタ" + ":" + String.valueOf(counter));

// 現在の時刻を取得
Date date = new Date();
// 表示形式を設定
SimpleDateFormat sdf = new SimpleDateFormat("yyyy'年'MM'月'dd'日' kk'時'mm'分'ss'秒'");
tv4.setText("更新日時" + ":" + sdf.format(date));

//生データをログ出力
String str = "";
String addressNum = device.getAddress().toString(); //Advertising MAC Address
for(int i=0; i<len; i++){
str += String.format("%x",scanRecord[i]&0xFF)+":";
}
Log.d(TAG,addressNum+"="+str);
}
}

●AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tawara.bletest2">

<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true" />

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>


<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>

●activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tawara.bletest2.MainActivity">

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:text="TextView"
android:textSize="24sp"
app:layout_constraintTop_toBottomOf="@+id/textView3"
tools:layout_editor_absoluteX="143dp" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="27dp"
android:text="TextView"
android:textSize="24sp"
app:layout_constraintTop_toBottomOf="@+id/textView2"
tools:layout_editor_absoluteX="143dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="@+id/textView" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="31dp"
android:text="TextView"
android:textSize="24sp"
app:layout_constraintTop_toBottomOf="@+id/textView"
tools:layout_editor_absoluteX="143dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="33dp"
android:text="TextView"
android:textSize="24sp"
app:layout_constraintTop_toBottomOf="@+id/textView1"
tools:layout_editor_absoluteX="143dp" />

</android.support.constraint.ConstraintLayout>