StepService.java 15 KB

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