具体请看代码:注释掉的就是没有用到的代码,业务逻辑可以按照文字注释去编辑
package main.com.pwj.testmvpv1;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.Context;
import android.os.Binder;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
//数据采集服务,开启后可以自动件数据保存到数据库,同时提供更新界面的接口
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
* <p>
* TODO: Customize class - update intent actions, extra parameters and static
* helper methods.
*/
public class SampleService extends IntentService {
public SampleBinder sampleBinder=new SampleBinder();
public int test_i=0;
private boolean actionBoolean=false;
public class SampleBinder extends Binder{
}
public SampleService() {
super("SampleService");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return sampleBinder;
}
@Override
public void onCreate() {
super.onCreate();
//接入蓝牙数据,异步监听
if (actionBoolean==false){
new Thread(new Runnable() {
@Override
public void run() {
// Log.i("SampleService","Runnable");
while (true){
// Log.i("SampleService","RunnableValue"+test_i);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
test_i++;
}
}
}).start();
actionBoolean=true;
}
Log.i("SampleService","onCreate1");
test_i++;
}
@Override
protected void onHandleIntent(Intent intent) {
//线程内处理逻辑,存储数据到数据库
//回调接口更新UI界面
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Log.i("SampleService","onHandleIntent"+test_i);
}
}, 0, 10);
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
//
// AlarmManager manager=(AlarmManager)getSystemService(ALARM_SERVICE);
// int anHour=1000;
// long triggerAtTime= SystemClock.elapsedRealtime()+anHour;
// Intent i=new Intent(this,SampleService.class);
// PendingIntent pendingIntent=PendingIntent.getService(this,0,i,0);
// manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendingIntent);
Log.i("SampleService","onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}