Advertisement
Nicba1010

Test

Jul 17th, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.27 KB | None | 0 0
  1. public class FakeService extends Service {
  2. /**
  3. * Play alarm up to 10 minutes before silencing
  4. */
  5. private static final int ALARM_TIMEOUT_SECONDS = 10 * 60;
  6. private static final long[] sVibratePattern = new long[]{500, 500};
  7. public static final String FAKE_SERVICE_PARAM = "FAKE_SERVICE_PARAM";
  8. private static final int NOTIFICATION_ID = 1;
  9. private static final String CHANNEL_ID = "ALARM_CHANNEL ID";
  10. private static final String CHANNEL_NAME = "ALARM_CHANNEL NAME";
  11. public static String ACTION_ALARM_SNOOZE = "com.troido.intent.action.ACTION_ALARM_SNOOZE";
  12. private boolean mPlaying = false;
  13. private Vibrator mVibrator;
  14. private MediaPlayer mMediaPlayer;
  15. private TelephonyManager mTelephonyManager;
  16. private int mInitialCallState;
  17. BroadcastReceiver snoozeAlarmReceiver = new BroadcastReceiver() {
  18. @Override
  19. public void onReceive(Context context, Intent intent) {
  20. String action = intent.getAction();
  21. if (action != null && action.equalsIgnoreCase(ACTION_ALARM_SNOOZE)) {
  22. stopSelf();
  23. }
  24. }
  25. };
  26. @Nullable
  27. @Override
  28. public IBinder onBind(Intent intent) {
  29. return null;
  30. }
  31. @Override
  32. public int onStartCommand(Intent intent, int flags, int startId) {
  33. if (intent == null) {
  34. stopSelf();
  35. return START_NOT_STICKY;
  36. }
  37. Commands.ALARM alarmType = (Commands.ALARM) intent.getSerializableExtra(FAKE_SERVICE_PARAM);
  38. Notification notification = createNotification(alarmType);
  39. registerSnoozeAlarmReceiver();
  40. startForeground(NOTIFICATION_ID, notification);
  41. play(alarmType);
  42. // Record the initial call state here so that the new alarm has the
  43. // newest state.
  44. mInitialCallState = mTelephonyManager.getCallState();
  45. return START_NOT_STICKY;
  46. }
  47. @RequiresApi(Build.VERSION_CODES.O)
  48. private String createNotificationChannel() {
  49. String channelId = CHANNEL_ID;
  50. NotificationChannel chan = new NotificationChannel(channelId, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
  51. chan.setLightColor(Color.RED);
  52. chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
  53. NotificationManager service = ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE));
  54. if (service != null) {
  55. service.createNotificationChannel(chan);
  56. }
  57. return channelId;
  58. }
  59. private void registerSnoozeAlarmReceiver() {
  60. IntentFilter intentFilter = new IntentFilter();
  61. intentFilter.addAction(ACTION_ALARM_SNOOZE);
  62. registerReceiver(snoozeAlarmReceiver, intentFilter);
  63. }
  64. private Notification createNotification(Commands.ALARM alarmType) {
  65. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  66. createNotificationChannel();
  67. }
  68. Intent snoozeIntent = new Intent();
  69. snoozeIntent.setAction(ACTION_ALARM_SNOOZE);
  70. PendingIntent snoozePendingIntent =
  71. PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);
  72. String alarmText = "";
  73. if (alarmType == Commands.ALARM.BURGLARY) {
  74. alarmText += "ALARM FOR BURGLARY IS RINGING..";
  75. } else if (alarmType == Commands.ALARM.Fire) {
  76. alarmText += "ALARM FOR FIRE IS RINGING..";
  77. } else if (alarmType == Commands.ALARM.BOTH) {
  78. alarmText += "ALARM FOR FIRE AND BURGLARY IS RINGING..";
  79. }
  80. NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
  81. .setSmallIcon(R.drawable.ic_launcher)
  82. .setContentTitle("ALARM! ALARM! ALARM!")
  83. .setContentText(alarmText)
  84. .setPriority(NotificationCompat.PRIORITY_DEFAULT)
  85. .setContentIntent(snoozePendingIntent)
  86. .addAction(R.drawable.ic_snooze, getString(R.string.snooze),
  87. snoozePendingIntent);
  88. return mBuilder.build();
  89. }
  90. private Uri getUriAlert() {
  91. Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
  92. if (alert == null) {
  93. // alert is null, using backup
  94. alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
  95. // I can't see this ever being null (as always have a default notification)
  96. // but just incase
  97. if (alert == null) {
  98. // alert backup is null, using 2nd backup
  99. alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
  100. }
  101. }
  102. return alert;
  103. }
  104. // Volume suggested by media team for in-call alarms.
  105. private static final float IN_CALL_VOLUME = 0.125f;
  106. private void play(Commands.ALARM alarmType) {
  107. // stop() checks to see if we are already playing.
  108. stop();
  109. Log.v("ALARM", "AlarmKlaxon.play() ");
  110. // TODO: Reuse mMediaPlayer instead of creating a new one and/or use
  111. // RingtoneManager.
  112. mMediaPlayer = new MediaPlayer();
  113. mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
  114. public boolean onError(MediaPlayer mp, int what, int extra) {
  115. Log.e("ALARM", "Error occurred while playing audio.");
  116. mp.stop();
  117. mp.release();
  118. mMediaPlayer = null;
  119. return true;
  120. }
  121. });
  122. try {
  123. // Check if we are in a call. If we are, use the in-call alarm
  124. // resource at a low volume to not disrupt the call.
  125. if (mTelephonyManager.getCallState()
  126. != TelephonyManager.CALL_STATE_IDLE) {
  127. Log.v("ALARM", "Using the in-call alarm");
  128. mMediaPlayer.setVolume(IN_CALL_VOLUME, IN_CALL_VOLUME);
  129. setDataSourceFromResource(getResources(), mMediaPlayer,
  130. R.raw.burglary);
  131. } else {
  132. if (alarmType == Commands.ALARM.BURGLARY || alarmType == Commands.ALARM.BOTH) {
  133. setDataSourceFromResource(getResources(), mMediaPlayer,
  134. R.raw.burglary);
  135. } else if (alarmType == Commands.ALARM.Fire) {
  136. setDataSourceFromResource(getResources(), mMediaPlayer,
  137. R.raw.fire);
  138. }
  139. }
  140. startAlarm(mMediaPlayer);
  141. } catch (Exception ex) {
  142. Log.v("ALARM", "Using the fallback ringtone");
  143. // The alert may be on the sd card which could be busy right
  144. // now. Use the fallback ringtone.
  145. try {
  146. // Must reset the media player to clear the error state.
  147. mMediaPlayer.reset();
  148. setDataSourceFromResource(getResources(), mMediaPlayer,
  149. R.raw.burglary);
  150. startAlarm(mMediaPlayer);
  151. } catch (Exception ex2) {
  152. // At this point we just don't play anything.
  153. Log.e("ALARM", "Failed to play fallback ringtone", ex2);
  154. }
  155. }
  156. /* Start the vibrator after everything is ok with the media player */
  157. mVibrator.vibrate(sVibratePattern, 0);
  158. enableKiller();
  159. mPlaying = true;
  160. }
  161. // Do the common stuff when starting the alarm.
  162. private void startAlarm(MediaPlayer player)
  163. throws java.io.IOException, IllegalArgumentException,
  164. IllegalStateException {
  165. final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  166. // do not play alarms if stream volume is 0
  167. // (typically because ringer mode is silent).
  168. if (audioManager != null && audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
  169. player.setAudioStreamType(AudioManager.STREAM_ALARM);
  170. player.setLooping(true);
  171. player.prepare();
  172. player.start();
  173. }
  174. }
  175. private void setDataSourceFromResource(Resources resources,
  176. MediaPlayer player, int res) throws java.io.IOException {
  177. AssetFileDescriptor afd = resources.openRawResourceFd(res);
  178. if (afd != null) {
  179. player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
  180. afd.getLength());
  181. afd.close();
  182. }
  183. }
  184. /**
  185. * Stops alarm audio and disables alarm if it not snoozed and not
  186. * repeating
  187. */
  188. public void stop() {
  189. Log.v("TAG", "AlarmKlaxon.stop()");
  190. if (mPlaying) {
  191. mPlaying = false;
  192. // Stop audio playing
  193. if (mMediaPlayer != null) {
  194. mMediaPlayer.stop();
  195. mMediaPlayer.release();
  196. mMediaPlayer = null;
  197. }
  198. // Stop vibrator
  199. mVibrator.cancel();
  200. }
  201. disableKiller();
  202. }
  203. /**
  204. * Kills alarm audio after ALARM_TIMEOUT_SECONDS, so the alarm
  205. * won't run all day.
  206. * <p>
  207. * This just cancels the audio, but leaves the notification
  208. * popped, so the user will know that the alarm tripped.
  209. */
  210. private void enableKiller() {
  211. mHandler.sendMessageDelayed(mHandler.obtainMessage(KILLER, ""),
  212. 1000 * ALARM_TIMEOUT_SECONDS);
  213. }
  214. private void disableKiller() {
  215. mHandler.removeMessages(KILLER);
  216. }
  217. // Internal messages
  218. private static final int KILLER = 1000;
  219. @SuppressLint("HandlerLeak")
  220. private Handler mHandler = new Handler() {
  221. public void handleMessage(Message msg) {
  222. switch (msg.what) {
  223. case KILLER:
  224. Log.v("ALARM", "*********** Alarm killer triggered ***********");
  225. stopSelf();
  226. break;
  227. }
  228. }
  229. };
  230. private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
  231. @Override
  232. public void onCallStateChanged(int state, String ignored) {
  233. // The user might already be in a call when the alarm fires. When
  234. // we register onCallStateChanged, we get the initial in-call state
  235. // which kills the alarm. Check against the initial call state so
  236. // we don't kill the alarm during a call.
  237. if (state != TelephonyManager.CALL_STATE_IDLE
  238. && state != mInitialCallState) {
  239. stopSelf();
  240. }
  241. }
  242. };
  243. @Override
  244. public void onCreate() {
  245. mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
  246. // Listen for incoming calls to kill the alarm.
  247. mTelephonyManager =
  248. (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
  249. if (mTelephonyManager != null) {
  250. mTelephonyManager.listen(
  251. mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
  252. }
  253. AlarmAlertWakeLock.acquireCpuWakeLock(this);
  254. }
  255. @Override
  256. public void onDestroy() {
  257. stop();
  258. // Stop listening for incoming calls.
  259. mTelephonyManager.listen(mPhoneStateListener, 0);
  260. AlarmAlertWakeLock.releaseCpuLock();
  261. unregisterReceiver(snoozeAlarmReceiver);
  262. }
  263. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement