StepService.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package com.xzjmyk.pm.basepedo.service;
  2. import android.annotation.TargetApi;
  3. import android.app.ActivityManager;
  4. import android.app.Notification;
  5. import android.app.NotificationManager;
  6. import android.app.PendingIntent;
  7. import android.app.Service;
  8. import android.content.BroadcastReceiver;
  9. import android.content.Context;
  10. import android.content.Intent;
  11. import android.content.IntentFilter;
  12. import android.hardware.Sensor;
  13. import android.hardware.SensorEvent;
  14. import android.hardware.SensorEventListener;
  15. import android.hardware.SensorManager;
  16. import android.os.Build;
  17. import android.os.Bundle;
  18. import android.os.Handler;
  19. import android.os.IBinder;
  20. import android.os.Message;
  21. import android.os.Messenger;
  22. import android.os.PowerManager;
  23. import android.os.PowerManager.WakeLock;
  24. import android.os.RemoteException;
  25. import android.support.v7.app.NotificationCompat;
  26. import android.util.Log;
  27. import com.xzjmyk.pm.activity.MyApplication;
  28. import com.xzjmyk.pm.activity.R;
  29. import com.xzjmyk.pm.activity.ui.MainActivity;
  30. import com.xzjmyk.pm.activity.ui.erp.util.ListUtils;
  31. import com.xzjmyk.pm.activity.util.PreferenceUtils;
  32. import com.xzjmyk.pm.basepedo.pojo.StepData;
  33. import com.xzjmyk.pm.basepedo.ui.MyPedometerActivity;
  34. import com.xzjmyk.pm.basepedo.utils.CountDownTimer;
  35. import com.xzjmyk.pm.basepedo.utils.DbUtils;
  36. import java.text.SimpleDateFormat;
  37. import java.util.Calendar;
  38. import java.util.Date;
  39. import java.util.List;
  40. @TargetApi(Build.VERSION_CODES.CUPCAKE)
  41. /**
  42. * Created by FANGlh on 2016/12/30.
  43. */
  44. public class StepService extends Service implements SensorEventListener {
  45. private final String TAG = "StepService";
  46. //默认为10秒进行一次存储
  47. private static int duration = 10000;
  48. private static String CURRENTDATE = "";
  49. private SensorManager sensorManager;
  50. private com.xzjmyk.pm.basepedo.service.StepDcretor stepDetector;
  51. private NotificationManager nm;
  52. private NotificationCompat.Builder builder;
  53. private Messenger messenger = new Messenger(new MessenerHandler());
  54. private BroadcastReceiver mBatInfoReceiver;
  55. private WakeLock mWakeLock;
  56. private TimeCount time;
  57. //测试
  58. private static int i = 0;
  59. private String DB_NAME = "basepedo";
  60. private String uustep_service_name = "com.xzjmyk.pm.basepedo.service.StepService";
  61. private static class MessenerHandler extends Handler {
  62. @Override
  63. public void handleMessage(Message msg) {
  64. switch (msg.what) {
  65. case com.xzjmyk.pm.basepedo.config.Constant.MSG_FROM_CLIENT:
  66. try {
  67. Messenger messenger = msg.replyTo;
  68. Message replyMsg = Message.obtain(null, com.xzjmyk.pm.basepedo.config.Constant.MSG_FROM_SERVER);
  69. Bundle bundle = new Bundle();
  70. bundle.putInt("step", com.xzjmyk.pm.basepedo.service.StepDcretor.CURRENT_SETP);
  71. replyMsg.setData(bundle);
  72. messenger.send(replyMsg);
  73. } catch (RemoteException e) {
  74. e.printStackTrace();
  75. }
  76. break;
  77. default:
  78. super.handleMessage(msg);
  79. }
  80. }
  81. }
  82. @Override
  83. public void onCreate() {
  84. super.onCreate();
  85. initBroadcastReceiver();
  86. new Thread(new Runnable() {
  87. public void run() {
  88. startStepDetector();
  89. }
  90. }).start();
  91. startTimeCount();
  92. Log.i("StepService","oncreated");
  93. }
  94. @Override
  95. public void onStart(Intent intent, int startId) {
  96. super.onStart(intent, startId);
  97. Log.i("StepService", "onStart");
  98. }
  99. @Override
  100. public int onStartCommand(Intent intent, int flags, int startId) {
  101. initTodayData();
  102. updateNotification("今日步数:" + com.xzjmyk.pm.basepedo.service.StepDcretor.CURRENT_SETP + " 步");
  103. flags = START_STICKY;
  104. Log.i("StepService", "onStartCommand");
  105. // return super.onStartCommand(intent,flags,startId);
  106. return START_REDELIVER_INTENT;
  107. }
  108. private String getTodayDate() {
  109. Date date = new Date(System.currentTimeMillis());
  110. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  111. return sdf.format(date);
  112. }
  113. private void initTodayData() {
  114. CURRENTDATE = getTodayDate();
  115. com.xzjmyk.pm.basepedo.utils.DbUtils.createDb(this, DB_NAME);
  116. //获取当天的数据,用于展示
  117. 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});
  118. if (ListUtils.isEmpty(list)) {
  119. com.xzjmyk.pm.basepedo.service.StepDcretor.CURRENT_SETP = 0;
  120. } else if (list.size() == 1) {
  121. com.xzjmyk.pm.basepedo.service.StepDcretor.CURRENT_SETP = Integer.parseInt(list.get(0).getStep());
  122. } else {
  123. Log.i(TAG, "出错了!");
  124. }
  125. }
  126. private void initBroadcastReceiver() {
  127. final IntentFilter filter = new IntentFilter();
  128. // 屏幕灭屏广播
  129. filter.addAction(Intent.ACTION_SCREEN_OFF);
  130. //日期修改
  131. filter.addAction(Intent.ACTION_TIME_CHANGED);
  132. //关机广播
  133. filter.addAction(Intent.ACTION_SHUTDOWN);
  134. // 屏幕亮屏广播
  135. filter.addAction(Intent.ACTION_SCREEN_ON);
  136. // 屏幕解锁广播
  137. filter.addAction(Intent.ACTION_USER_PRESENT);
  138. // 当长按电源键弹出“关机”对话或者锁屏时系统会发出这个广播
  139. // example:有时候会用到系统对话框,权限可能很高,会覆盖在锁屏界面或者“关机”对话框之上,
  140. // 所以监听这个广播,当收到时就隐藏自己的对话,如点击pad右下角部分弹出的对话框
  141. filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
  142. mBatInfoReceiver = new BroadcastReceiver() {
  143. @Override
  144. public void onReceive(final Context context, final Intent intent) {
  145. String action = intent.getAction();
  146. if (Intent.ACTION_SCREEN_ON.equals(action)) {
  147. Log.v(TAG, "screen on");
  148. } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
  149. Log.v(TAG, "screen off");
  150. //改为60秒一存储
  151. duration = 60000;
  152. } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
  153. Log.v(TAG, "screen unlock");
  154. save();
  155. //改为10秒一存储
  156. duration = 10000;
  157. } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.getAction())) {
  158. Log.v(TAG, " receive Intent.ACTION_CLOSE_SYSTEM_DIALOGS");
  159. //保存一次
  160. save();
  161. } else if (Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
  162. Log.v(TAG, " receive ACTION_SHUTDOWN");
  163. save();
  164. } else if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
  165. Log.v(TAG, " receive ACTION_TIME_CHANGED");
  166. initTodayData();
  167. clearStepData();
  168. }
  169. }
  170. };
  171. registerReceiver(mBatInfoReceiver, filter);
  172. }
  173. private void clearStepData() {
  174. i = 0;
  175. StepService.CURRENTDATE = "0";
  176. }
  177. private void startTimeCount() {
  178. time = new TimeCount(duration, 1000);
  179. time.start();
  180. }
  181. /**
  182. * 更新通知
  183. */
  184. private void updateNotification(String content) {
  185. builder = new NotificationCompat.Builder(this);
  186. builder.setPriority(Notification.PRIORITY_MIN);
  187. PendingIntent contentIntent = PendingIntent.getActivity(this, 100,
  188. new Intent(this, MyPedometerActivity.class), 0);
  189. builder.setContentIntent(contentIntent);
  190. // builder.setDeleteIntent(contentIntent);
  191. builder.setSmallIcon(R.drawable.uuu);
  192. builder.setTicker("UU运动");
  193. builder.setContentTitle("UU运动");
  194. // builder.setOngoing(true); //设置不可清除
  195. builder.setContentText(content);
  196. Notification notification = builder.build();
  197. startForeground(0, notification);
  198. nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  199. if (PreferenceUtils.getInt(this,MyPedometerActivity.UU_STEP_NOTICE) == 1){
  200. nm.notify(R.string.app_name, notification);
  201. }else if(PreferenceUtils.getInt(this,MyPedometerActivity.UU_STEP_NOTICE) == 0){
  202. nm.cancelAll();
  203. }
  204. try {
  205. unlock();
  206. }catch (SecurityException s){
  207. s.printStackTrace();
  208. }
  209. }
  210. @Override
  211. public IBinder onBind(Intent intent) {
  212. return messenger.getBinder();
  213. }
  214. private void startStepDetector() {
  215. if (sensorManager != null && stepDetector != null) {
  216. sensorManager.unregisterListener(stepDetector);
  217. sensorManager = null;
  218. stepDetector = null;
  219. }
  220. sensorManager = (SensorManager) this
  221. .getSystemService(SENSOR_SERVICE);
  222. getLock(this);
  223. // android4.4以后可以使用计步传感器
  224. int VERSION_CODES = Build.VERSION.SDK_INT;
  225. if (VERSION_CODES >= 19) {
  226. addCountStepListener();
  227. } else {
  228. addBasePedoListener();
  229. }
  230. addBasePedoListener();
  231. addCountStepListener();
  232. }
  233. private void addCountStepListener() {
  234. Sensor detectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
  235. Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
  236. if (detectorSensor != null) {
  237. sensorManager.registerListener(StepService.this, detectorSensor, SensorManager.SENSOR_DELAY_UI);
  238. } else if (countSensor != null) {
  239. sensorManager.registerListener(StepService.this, countSensor, SensorManager.SENSOR_DELAY_UI);
  240. // addBasePedoListener();
  241. } else {
  242. Log.v(TAG, "Count sensor not available!");
  243. }
  244. }
  245. private void addBasePedoListener() {
  246. stepDetector = new StepDcretor(this);
  247. // 获得传感器的类型,这里获得的类型是加速度传感器
  248. // 此方法用来注册,只有注册过才会生效,参数:SensorEventListener的实例,Sensor的实例,更新速率
  249. Sensor sensor = sensorManager
  250. .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
  251. // sensorManager.unregisterListener(stepDetector);
  252. sensorManager.registerListener(stepDetector, sensor,
  253. SensorManager.SENSOR_DELAY_UI);
  254. stepDetector
  255. .setOnSensorChangeListener(new StepDcretor.OnSensorChangeListener() {
  256. @Override
  257. public void onChange() {
  258. updateNotification("今日步数:" + StepDcretor.CURRENT_SETP + " 步");
  259. }
  260. });
  261. }
  262. @Override
  263. public void onSensorChanged(SensorEvent event) {
  264. i++;
  265. // StepDcretor.CURRENT_SETP ++; //TODO 这里取消屏蔽功能,动一次计步叠加一次
  266. updateNotification("今日步数:" + StepDcretor.CURRENT_SETP + " 步");
  267. }
  268. @Override
  269. public void onAccuracyChanged(Sensor sensor, int accuracy) {
  270. }
  271. class TimeCount extends CountDownTimer {
  272. public TimeCount(long millisInFuture, long countDownInterval) {
  273. super(millisInFuture, countDownInterval);
  274. }
  275. @Override
  276. public void onFinish() {
  277. // 如果计时器正常结束,则开始计步
  278. time.cancel();
  279. save();
  280. startTimeCount();
  281. }
  282. @Override
  283. public void onTick(long millisUntilFinished) {
  284. }
  285. }
  286. private void save() {
  287. int tempStep = StepDcretor.CURRENT_SETP;
  288. List<StepData> list = DbUtils.getQueryByWhere(StepData.class, "today", new String[]{CURRENTDATE});
  289. if (ListUtils.isEmpty(list)) {
  290. StepData data = new StepData();
  291. data.setToday(CURRENTDATE);
  292. data.setStep(tempStep + "");
  293. DbUtils.insert(data);
  294. } else if (list.size() == 1) {
  295. StepData data = list.get(0);
  296. data.setStep(tempStep + "");
  297. DbUtils.update(data);
  298. } else {
  299. }
  300. }
  301. @Override
  302. public void onDestroy() {
  303. //取消前台进程
  304. stopForeground(true);
  305. stopForeground(false);
  306. DbUtils.closeDb();
  307. unregisterReceiver(mBatInfoReceiver);
  308. if (! isServiceRunning(uustep_service_name) && PreferenceUtils.getInt(MyApplication.getInstance(), MainActivity.UU_STEP)==1){
  309. Intent intent = new Intent(this, StepService.class);
  310. startService(intent);
  311. }
  312. Intent intent = new Intent("uu.step.destory");
  313. sendBroadcast(intent);
  314. Log.v("StepService", "onDestroy");
  315. super.onDestroy();
  316. }
  317. @Override
  318. public boolean onUnbind(Intent intent) {
  319. return super.onUnbind(intent);
  320. }
  321. private void unlock(){
  322. setLockPatternEnabled(android.provider.Settings.Secure.LOCK_PATTERN_ENABLED,false);
  323. }
  324. private void setLockPatternEnabled(String systemSettingKey, boolean enabled) {
  325. //推荐使用
  326. android.provider.Settings.Secure.putInt(getContentResolver(), systemSettingKey,enabled ? 1 : 0);
  327. }
  328. synchronized private WakeLock getLock(Context context) {
  329. if (mWakeLock != null) {
  330. if (mWakeLock.isHeld())
  331. mWakeLock.release();
  332. mWakeLock = null;
  333. }
  334. if (mWakeLock == null) {
  335. PowerManager mgr = (PowerManager) context
  336. .getSystemService(Context.POWER_SERVICE);
  337. mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
  338. StepService.class.getName());
  339. mWakeLock.setReferenceCounted(true);
  340. Calendar c = Calendar.getInstance();
  341. c.setTimeInMillis(System.currentTimeMillis());
  342. int hour = c.get(Calendar.HOUR_OF_DAY);
  343. if (hour >= 23 || hour <= 6) {
  344. mWakeLock.acquire(5000);
  345. } else {
  346. mWakeLock.acquire(300000);
  347. }
  348. }
  349. return (mWakeLock);
  350. }
  351. private boolean isServiceRunning(String servicename) { //判断UU运动服务是否已经运行
  352. ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
  353. for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
  354. if (servicename.equals(service.service.getClassName())) {
  355. return true;
  356. }
  357. }
  358. return false;
  359. }
  360. }