接上篇,我们已经实现了短震,长震的功能了~
现在我们需要实现点击后一直震动的功能
开始我的想法是再循环中不断执行write方法,然而这个办法行不通。
系统会报错。
那要如何实现这个想法呢?其实很简单,使用service实现轮询就行
那想到了解决方案就着手实现方法吧!!
写个服务:
package com.wbnq.ryadie.service; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.app.Service; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.content.Intent; import android.os.IBinder; import android.os.SystemClock; import android.util.Log; import com.wbnq.ryadie.HexUtil; import com.wbnq.ryadie.OfflineApplication; import com.wbnq.ryadie.R; import com.wbnq.ryadie.StaticData; import com.wbnq.ryadie.broadcast.AlarmReceiver; import java.util.Date; import static com.wbnq.ryadie.StaticData.GATDATA; import static com.wbnq.ryadie.StaticData.GATPOWER; /** * Created by guwei on 16-9-20. */ public class ReadData extends Service { BluetoothGatt bluetoothGatt; BluetoothGattCharacteristic bleGattCharacteristic; OfflineApplication application; boolean isrunning; public static final String TAG = "ReadData_service"; // @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { application = (OfflineApplication) getApplication(); isrunning = application.getIsthreadrunning(); //这里开辟一条线程,用来执行具体的逻辑操作: new Thread(new Runnable() { @Override public void run() { Log.d("BackService", new Date().toString()); bleGattCharacteristic = application.getCharacteristic(); bluetoothGatt = application.getBluetoothGatt(); if (isrunning) { Log.e(TAG, "run: 开始轮询服务"); //向设备发送获取数据的命令 write(GATDATA); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } //向设备发送获取电量的命令 write(GATPOWER); } else { Log.e(TAG, "run: 停止轮询服务"); } } }).start(); AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE); //这里是定时的,这里设置的是每隔两秒打印一次时间=-=,自己改 int anHour = 20 * 1000; long triggerAtTime = SystemClock.elapsedRealtime() + anHour; Intent i = new Intent(this, AlarmReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi); return super.onStartCommand(intent, flags, startId); } //向设备写入命令方法 private void write(String commond) { Log.i(TAG, "write: in write \t " + bluetoothGatt + "\t" + bleGattCharacteristic); if (bleGattCharacteristic != null && bluetoothGatt != null) { bleGattCharacteristic.setValue(HexUtil.hexStringToBytes(commond)); bluetoothGatt.writeCharacteristic(bleGattCharacteristic); commond = null; } } @Override public void onDestroy() { super.onDestroy(); Log.e(TAG, "onDestroy: "); } }