| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399 |
- package com.xzjmyk.pm.basepedo.service;
- import android.annotation.TargetApi;
- import android.app.ActivityManager;
- import android.app.Notification;
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.app.Service;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.hardware.Sensor;
- import android.hardware.SensorEvent;
- import android.hardware.SensorEventListener;
- import android.hardware.SensorManager;
- import android.os.Build;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.IBinder;
- import android.os.Message;
- import android.os.Messenger;
- import android.os.PowerManager;
- import android.os.PowerManager.WakeLock;
- import android.os.RemoteException;
- import android.support.v7.app.NotificationCompat;
- import android.util.Log;
- import com.xzjmyk.pm.activity.MyApplication;
- import com.xzjmyk.pm.activity.R;
- import com.xzjmyk.pm.activity.ui.MainActivity;
- import com.xzjmyk.pm.activity.ui.erp.util.ListUtils;
- import com.xzjmyk.pm.activity.util.PreferenceUtils;
- import com.xzjmyk.pm.basepedo.pojo.StepData;
- import com.xzjmyk.pm.basepedo.ui.MyPedometerActivity;
- import com.xzjmyk.pm.basepedo.utils.CountDownTimer;
- import com.xzjmyk.pm.basepedo.utils.DbUtils;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.List;
- @TargetApi(Build.VERSION_CODES.CUPCAKE)
- /**
- * Created by FANGlh on 2016/12/30.
- */
- public class StepService extends Service implements SensorEventListener {
- private final String TAG = "StepService";
- //默认为10秒进行一次存储
- private static int duration = 10000;
- private static String CURRENTDATE = "";
- private SensorManager sensorManager;
- private com.xzjmyk.pm.basepedo.service.StepDcretor stepDetector;
- private NotificationManager nm;
- private NotificationCompat.Builder builder;
- private Messenger messenger = new Messenger(new MessenerHandler());
- private BroadcastReceiver mBatInfoReceiver;
- private WakeLock mWakeLock;
- private TimeCount time;
- //测试
- private static int i = 0;
- private String DB_NAME = "basepedo";
- private String uustep_service_name = "com.xzjmyk.pm.basepedo.service.StepService";
- private static class MessenerHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case com.xzjmyk.pm.basepedo.config.Constant.MSG_FROM_CLIENT:
- try {
- Messenger messenger = msg.replyTo;
- Message replyMsg = Message.obtain(null, com.xzjmyk.pm.basepedo.config.Constant.MSG_FROM_SERVER);
- Bundle bundle = new Bundle();
- bundle.putInt("step", com.xzjmyk.pm.basepedo.service.StepDcretor.CURRENT_SETP);
- replyMsg.setData(bundle);
- messenger.send(replyMsg);
- } catch (RemoteException e) {
- e.printStackTrace();
- }
- break;
- default:
- super.handleMessage(msg);
- }
- }
- }
- @Override
- public void onCreate() {
- super.onCreate();
- initBroadcastReceiver();
- new Thread(new Runnable() {
- public void run() {
- startStepDetector();
- }
- }).start();
- startTimeCount();
- Log.i("StepService","oncreated");
- }
- @Override
- public void onStart(Intent intent, int startId) {
- super.onStart(intent, startId);
- Log.i("StepService", "onStart");
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- initTodayData();
- updateNotification("今日步数:" + com.xzjmyk.pm.basepedo.service.StepDcretor.CURRENT_SETP + " 步");
- flags = START_STICKY;
- Log.i("StepService", "onStartCommand");
- // return super.onStartCommand(intent,flags,startId);
- return START_REDELIVER_INTENT;
- }
- private String getTodayDate() {
- Date date = new Date(System.currentTimeMillis());
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
- return sdf.format(date);
- }
- private void initTodayData() {
- CURRENTDATE = getTodayDate();
- com.xzjmyk.pm.basepedo.utils.DbUtils.createDb(this, DB_NAME);
- //获取当天的数据,用于展示
- List<com.xzjmyk.pm.basepedo.pojo.StepData> list = com.xzjmyk.pm.basepedo.utils.DbUtils.getQueryByWhere(com.xzjmyk.pm.basepedo.pojo.StepData.class, "today", new String[]{CURRENTDATE});
- if (ListUtils.isEmpty(list)) {
- com.xzjmyk.pm.basepedo.service.StepDcretor.CURRENT_SETP = 0;
- } else if (list.size() == 1) {
- com.xzjmyk.pm.basepedo.service.StepDcretor.CURRENT_SETP = Integer.parseInt(list.get(0).getStep());
- } else {
- Log.i(TAG, "出错了!");
- }
- }
- private void initBroadcastReceiver() {
- final IntentFilter filter = new IntentFilter();
- // 屏幕灭屏广播
- filter.addAction(Intent.ACTION_SCREEN_OFF);
- //日期修改
- filter.addAction(Intent.ACTION_TIME_CHANGED);
- //关机广播
- filter.addAction(Intent.ACTION_SHUTDOWN);
- // 屏幕亮屏广播
- filter.addAction(Intent.ACTION_SCREEN_ON);
- // 屏幕解锁广播
- filter.addAction(Intent.ACTION_USER_PRESENT);
- // 当长按电源键弹出“关机”对话或者锁屏时系统会发出这个广播
- // example:有时候会用到系统对话框,权限可能很高,会覆盖在锁屏界面或者“关机”对话框之上,
- // 所以监听这个广播,当收到时就隐藏自己的对话,如点击pad右下角部分弹出的对话框
- filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
- mBatInfoReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(final Context context, final Intent intent) {
- String action = intent.getAction();
- if (Intent.ACTION_SCREEN_ON.equals(action)) {
- Log.v(TAG, "screen on");
- } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
- Log.v(TAG, "screen off");
- //改为60秒一存储
- duration = 60000;
- } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
- Log.v(TAG, "screen unlock");
- save();
- //改为10秒一存储
- duration = 10000;
- } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.getAction())) {
- Log.v(TAG, " receive Intent.ACTION_CLOSE_SYSTEM_DIALOGS");
- //保存一次
- save();
- } else if (Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
- Log.v(TAG, " receive ACTION_SHUTDOWN");
- save();
- } else if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
- Log.v(TAG, " receive ACTION_TIME_CHANGED");
- initTodayData();
- clearStepData();
- }
- }
- };
- registerReceiver(mBatInfoReceiver, filter);
- }
- private void clearStepData() {
- i = 0;
- StepService.CURRENTDATE = "0";
- }
- private void startTimeCount() {
- time = new TimeCount(duration, 1000);
- time.start();
- }
- /**
- * 更新通知
- */
- private void updateNotification(String content) {
- builder = new NotificationCompat.Builder(this);
- builder.setPriority(Notification.PRIORITY_MIN);
- PendingIntent contentIntent = PendingIntent.getActivity(this, 100,
- new Intent(this, MyPedometerActivity.class), 0);
- builder.setContentIntent(contentIntent);
- // builder.setDeleteIntent(contentIntent);
- builder.setSmallIcon(R.drawable.uuu);
- builder.setTicker("UU运动");
- builder.setContentTitle("UU运动");
- // builder.setOngoing(true); //设置不可清除
- builder.setContentText(content);
- Notification notification = builder.build();
- startForeground(0, notification);
- nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- if (PreferenceUtils.getInt(this,MyPedometerActivity.UU_STEP_NOTICE) == 1){
- nm.notify(R.string.app_name, notification);
- }else if(PreferenceUtils.getInt(this,MyPedometerActivity.UU_STEP_NOTICE) == 0){
- nm.cancelAll();
- }
- try {
- unlock();
- }catch (SecurityException s){
- s.printStackTrace();
- }
- }
- @Override
- public IBinder onBind(Intent intent) {
- return messenger.getBinder();
- }
- private void startStepDetector() {
- if (sensorManager != null && stepDetector != null) {
- sensorManager.unregisterListener(stepDetector);
- sensorManager = null;
- stepDetector = null;
- }
- sensorManager = (SensorManager) this
- .getSystemService(SENSOR_SERVICE);
- getLock(this);
- // android4.4以后可以使用计步传感器
- int VERSION_CODES = Build.VERSION.SDK_INT;
- if (VERSION_CODES >= 19) {
- addCountStepListener();
- } else {
- addBasePedoListener();
- }
- addBasePedoListener();
- addCountStepListener();
- }
- private void addCountStepListener() {
- Sensor detectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
- Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
- if (detectorSensor != null) {
- sensorManager.registerListener(StepService.this, detectorSensor, SensorManager.SENSOR_DELAY_UI);
- } else if (countSensor != null) {
- sensorManager.registerListener(StepService.this, countSensor, SensorManager.SENSOR_DELAY_UI);
- // addBasePedoListener();
- } else {
- Log.v(TAG, "Count sensor not available!");
- }
- }
- private void addBasePedoListener() {
- stepDetector = new StepDcretor(this);
- // 获得传感器的类型,这里获得的类型是加速度传感器
- // 此方法用来注册,只有注册过才会生效,参数:SensorEventListener的实例,Sensor的实例,更新速率
- Sensor sensor = sensorManager
- .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
- // sensorManager.unregisterListener(stepDetector);
- sensorManager.registerListener(stepDetector, sensor,
- SensorManager.SENSOR_DELAY_UI);
- stepDetector
- .setOnSensorChangeListener(new StepDcretor.OnSensorChangeListener() {
- @Override
- public void onChange() {
- updateNotification("今日步数:" + StepDcretor.CURRENT_SETP + " 步");
- }
- });
- }
- @Override
- public void onSensorChanged(SensorEvent event) {
- i++;
- // StepDcretor.CURRENT_SETP ++; //TODO 这里取消屏蔽功能,动一次计步叠加一次
- updateNotification("今日步数:" + StepDcretor.CURRENT_SETP + " 步");
- }
- @Override
- public void onAccuracyChanged(Sensor sensor, int accuracy) {
- }
- class TimeCount extends CountDownTimer {
- public TimeCount(long millisInFuture, long countDownInterval) {
- super(millisInFuture, countDownInterval);
- }
- @Override
- public void onFinish() {
- // 如果计时器正常结束,则开始计步
- time.cancel();
- save();
- startTimeCount();
- }
- @Override
- public void onTick(long millisUntilFinished) {
- }
- }
- private void save() {
- int tempStep = StepDcretor.CURRENT_SETP;
- List<StepData> list = DbUtils.getQueryByWhere(StepData.class, "today", new String[]{CURRENTDATE});
- if (ListUtils.isEmpty(list)) {
- StepData data = new StepData();
- data.setToday(CURRENTDATE);
- data.setStep(tempStep + "");
- DbUtils.insert(data);
- } else if (list.size() == 1) {
- StepData data = list.get(0);
- data.setStep(tempStep + "");
- DbUtils.update(data);
- } else {
- }
- }
- @Override
- public void onDestroy() {
- //取消前台进程
- stopForeground(true);
- stopForeground(false);
- DbUtils.closeDb();
- unregisterReceiver(mBatInfoReceiver);
- if (! isServiceRunning(uustep_service_name) && PreferenceUtils.getInt(MyApplication.getInstance(), MainActivity.UU_STEP)==1){
- Intent intent = new Intent(this, StepService.class);
- startService(intent);
- }
- Intent intent = new Intent("uu.step.destory");
- sendBroadcast(intent);
- Log.v("StepService", "onDestroy");
- super.onDestroy();
- }
- @Override
- public boolean onUnbind(Intent intent) {
- return super.onUnbind(intent);
- }
- private void unlock(){
- setLockPatternEnabled(android.provider.Settings.Secure.LOCK_PATTERN_ENABLED,false);
- }
- private void setLockPatternEnabled(String systemSettingKey, boolean enabled) {
- //推荐使用
- android.provider.Settings.Secure.putInt(getContentResolver(), systemSettingKey,enabled ? 1 : 0);
- }
- synchronized private WakeLock getLock(Context context) {
- if (mWakeLock != null) {
- if (mWakeLock.isHeld())
- mWakeLock.release();
- mWakeLock = null;
- }
- if (mWakeLock == null) {
- PowerManager mgr = (PowerManager) context
- .getSystemService(Context.POWER_SERVICE);
- mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
- StepService.class.getName());
- mWakeLock.setReferenceCounted(true);
- Calendar c = Calendar.getInstance();
- c.setTimeInMillis(System.currentTimeMillis());
- int hour = c.get(Calendar.HOUR_OF_DAY);
- if (hour >= 23 || hour <= 6) {
- mWakeLock.acquire(5000);
- } else {
- mWakeLock.acquire(300000);
- }
- }
- return (mWakeLock);
- }
- private boolean isServiceRunning(String servicename) { //判断UU运动服务是否已经运行
- ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
- for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
- if (servicename.equals(service.service.getClassName())) {
- return true;
- }
- }
- return false;
- }
- }
|