Skip to content

Commit

Permalink
Support for changing sensitivity of shake detector
Browse files Browse the repository at this point in the history
Sensitivity of shake detector can now be changed by going to settings.
  • Loading branch information
WrichikBasu committed Nov 2, 2020
1 parent d59af43 commit cfb6042
Show file tree
Hide file tree
Showing 14 changed files with 496 additions and 123 deletions.
4 changes: 2 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ android {
applicationId "in.basulabs.shakealarmclock"
minSdkVersion 21
targetSdkVersion 30
versionCode 8
versionName "1.2.5"
versionCode 10
versionName "1.2.7"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
Expand Down
1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<uses-feature android:name="android.hardware.audio.output" android:required="true"/>
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true"/>

<application
android:name=".MyApplication"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -476,11 +476,9 @@ private void checkForUpdates() {
dialog.cancel();

try {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=in.basulabs" +
".shakealarmclock")));
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=in.basulabs.shakealarmclock")));
} catch (android.content.ActivityNotFoundException exception) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google" +
".com/store/apps/details?id=in.basulabs.shakealarmclock")));
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=in.basulabs.shakealarmclock")));
}
})
.start();
Expand Down
282 changes: 231 additions & 51 deletions app/src/main/java/in/basulabs/shakealarmclock/Activity_Settings.java

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ public void onAttach(@NonNull Context context) {
if (context instanceof DialogListener) {
listener = (DialogListener) context;
} else {
throw new ClassCastException(context.getClass() + " must implement AlertDialog_DiscardChanges" +
".DialogListener");
throw new ClassCastException(context.getClass() + " must implement AlertDialog_DiscardChanges.DialogListener");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class AlertDialog_PermissionReason extends DialogFragment {

private DialogListener listener;

private String message;
private final String message;

public AlertDialog_PermissionReason(String message) {
this.message = message;
Expand All @@ -31,8 +31,7 @@ public void onAttach(@NonNull Context context) {
if (context instanceof DialogListener) {
listener = (DialogListener) context;
} else {
throw new ClassCastException(context.getClass() + " must implement AlertDialog_PermissionReason" +
".DialogListener");
throw new ClassCastException(context.getClass() + " must implement AlertDialog_PermissionReason.DialogListener");
}
}

Expand All @@ -43,8 +42,7 @@ public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
builder.setMessage(message)
.setPositiveButton(getResources().getString(R.string.cancelDialog_positive),
(dialogInterface, i) -> listener
.onDialogPositiveClick(AlertDialog_PermissionReason.this))
(dialogInterface, i) -> listener.onDialogPositiveClick(AlertDialog_PermissionReason.this))
.setNegativeButton(getResources().getString(R.string.cancelDialog_negative),
(dialogInterface, i) -> {
listener.onDialogNegativeClick(AlertDialog_PermissionReason.this);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package in.basulabs.shakealarmclock;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

public class AlertDialog_TestShakeSensitivity extends DialogFragment {

private AlertDialog_TestShakeSensitivity.DialogListener listener;

public interface DialogListener {

void onDialogNegativeClick(DialogFragment dialogFragment);

}

@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof AlertDialog_TestShakeSensitivity.DialogListener) {
listener = (AlertDialog_TestShakeSensitivity.DialogListener) context;
} else {
throw new ClassCastException(context.getClass() + " must implement AlertDialog_TestShakeSensitivity.DialogListener");
}
}

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
builder.setTitle(R.string.title_shakeDetectionTest)
.setMessage(getResources().getString(R.string.message_shakeDetectionTest))
.setNegativeButton(getResources().getString(R.string.negative_shakeDetectionTest), (dialogInterface, i) -> {
listener.onDialogNegativeClick(AlertDialog_TestShakeSensitivity.this);
dismiss();
})
.setCancelable(false);

return builder.create();
}

@Override
public void onDetach() {
super.onDetach();
listener = null;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,11 @@ final class ConstantsAndStatics {
/**
* {@link android.content.SharedPreferences} key to store the default power button operation. Can be either {@link #DISMISS} or {@link #SNOOZE}.
*/
static final String SHARED_PREF_KEY_DEFAULT_POWER_BTN_OPERATION = "in.basulabs.shakealarmclock.DEFAULT_POWER_BTN_OPERATION";
static final String SHARED_PREF_KEY_DEFAULT_POWER_BTN_OPERATION = "in.basulabs.shakealarmclock.DEFAULT_POWER_BTN_OPERATION";

static final String SHARED_PREF_KEY_SHAKE_SENSITIVITY = "in.basulabs.shakealarmclock.SHAKE_SENSITIVITY";

static final float DEFAULT_SHAKE_SENSITIVITY = 3.2f;

/**
* Indicates that the ringing alarm should be snoozed.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,7 @@ private void initialiseShakeSensor() {
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(Integer.toString(NOTIFICATION_ID),
"in.basulabs.shakealarmclock Notifications", importance);
NotificationChannel channel = new NotificationChannel(Integer.toString(NOTIFICATION_ID),"in.basulabs.shakealarmclock Notifications", importance);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
channel.setSound(null, null);
assert notificationManager != null;
Expand All @@ -228,8 +227,7 @@ private Notification buildRingNotification() {
fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 3054,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 3054, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this,
Integer.toString(NOTIFICATION_ID))
Expand All @@ -254,17 +252,15 @@ private void ringAlarm() {
notificationManager.notify(NOTIFICATION_ID, buildRingNotification());
initialiseShakeSensor();

if (! (alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_ALARM_TYPE)
== ConstantsAndStatics.ALARM_TYPE_VIBRATE_ONLY)) {
if (! (alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_ALARM_TYPE) == ConstantsAndStatics.ALARM_TYPE_VIBRATE_ONLY)) {

mediaPlayer = new MediaPlayer();
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();

audioManager.setStreamVolume(AudioManager.STREAM_ALARM,
alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_ALARM_VOLUME), 0);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_ALARM_VOLUME), 0);

try {
mediaPlayer.setDataSource(this, alarmToneUri);
Expand All @@ -274,8 +270,7 @@ private void ringAlarm() {
} catch (IOException ignored) {
}

if (alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_ALARM_TYPE)
== ConstantsAndStatics.ALARM_TYPE_SOUND_AND_VIBRATE) {
if (alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_ALARM_TYPE) == ConstantsAndStatics.ALARM_TYPE_SOUND_AND_VIBRATE) {
alarmVibration();
}
mediaPlayer.start();
Expand Down Expand Up @@ -319,8 +314,7 @@ private void snoozeAlarm() {

if (alarmDetails.getBoolean(ConstantsAndStatics.BUNDLE_KEY_IS_SNOOZE_ON)) {

if (numberOfTimesTheAlarmHasBeenSnoozed < alarmDetails
.getInt(ConstantsAndStatics.BUNDLE_KEY_SNOOZE_FREQUENCY)) {
if (numberOfTimesTheAlarmHasBeenSnoozed < alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_SNOOZE_FREQUENCY)) {

numberOfTimesTheAlarmHasBeenSnoozed++;

Expand Down Expand Up @@ -349,9 +343,7 @@ private void dismissAlarm() {
stopRinging();
cancelPendingIntent();

Thread thread_toggleAlarm = new Thread(
() -> alarmDatabase.alarmDAO()
.toggleAlarm(alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_ALARM_ID), 0));
Thread thread_toggleAlarm = new Thread(() -> alarmDatabase.alarmDAO().toggleAlarm(alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_ALARM_ID), 0));

//////////////////////////////////////////////////////
// If repeat is on, set another alarm. Otherwise
Expand Down Expand Up @@ -433,17 +425,16 @@ private void stopRinging() {
private void setAlarm(LocalDateTime alarmDateTime) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

Intent intent = new Intent(this, AlarmBroadcastReceiver.class);
intent.setAction(ConstantsAndStatics.ACTION_DELIVER_ALARM);
intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
intent.putExtra(ConstantsAndStatics.BUNDLE_KEY_ALARM_DETAILS, alarmDetails);
Intent intent = new Intent(this, AlarmBroadcastReceiver.class)
.setAction(ConstantsAndStatics.ACTION_DELIVER_ALARM)
.setFlags(Intent.FLAG_RECEIVER_FOREGROUND)
.putExtra(ConstantsAndStatics.BUNDLE_KEY_ALARM_DETAILS, alarmDetails);

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, alarmID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

ZonedDateTime zonedDateTime = ZonedDateTime.of(alarmDateTime.withSecond(0), ZoneId.systemDefault());

alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(zonedDateTime.toEpochSecond() * 1000,
pendingIntent), pendingIntent);
alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(zonedDateTime.toEpochSecond() * 1000, pendingIntent), pendingIntent);
}

//---------------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -486,7 +477,7 @@ public void onSensorChanged(SensorEvent event) {
float gForce = (float) Math.sqrt(gX * gX + gY * gY + gZ * gZ);
// gForce will be close to 1 when there is no movement.

if (gForce >= 3.8f) {
if (gForce >= sharedPreferences.getFloat(ConstantsAndStatics.SHARED_PREF_KEY_SHAKE_SENSITIVITY, ConstantsAndStatics.DEFAULT_SHAKE_SENSITIVITY)) {
long currTime = System.currentTimeMillis();
if (Math.abs(currTime - lastShakeTime) > MINIMUM_MILLIS_BETWEEN_SHAKES) {
lastShakeTime = currTime;
Expand Down Expand Up @@ -516,17 +507,6 @@ private void shakeVibration() {
} else {
vibrator.vibrate(200);
}
Thread thread = new Thread(() -> {
try {
Thread.sleep(200);
} catch (InterruptedException ignored) {
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException ignored) {
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,7 @@ public int onStartCommand(Intent intent, int flags, int startId) {
assert alarmDetails != null;
alarmID = alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_ALARM_ID);

numberOfTimesTheAlarmhasBeenSnoozed =
intent.getExtras().getInt(Service_RingAlarm.BUNDLE_KEY_NO_OF_TIMES_SNOOZED);
numberOfTimesTheAlarmhasBeenSnoozed = intent.getExtras().getInt(Service_RingAlarm.BUNDLE_KEY_NO_OF_TIMES_SNOOZED);

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConstantsAndStatics.ACTION_CANCEL_ALARM);
Expand All @@ -89,21 +88,20 @@ public int onStartCommand(Intent intent, int flags, int startId) {
alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_ALARM_MINUTE), 0, 0),
ZoneId.systemDefault());

ZonedDateTime newAlarmDateTime = alarmDateTime.plusMinutes(numberOfTimesTheAlarmhasBeenSnoozed * alarmDetails
.getInt(ConstantsAndStatics.BUNDLE_KEY_SNOOZE_TIME_IN_MINS));
ZonedDateTime newAlarmDateTime = alarmDateTime.plusMinutes(numberOfTimesTheAlarmhasBeenSnoozed *
alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_SNOOZE_TIME_IN_MINS));

snoozeTimer = new CountDownTimer(Math.abs(Duration.between(ZonedDateTime.now(),
newAlarmDateTime).toMillis()), 500) {
snoozeTimer = new CountDownTimer(Math.abs(Duration.between(ZonedDateTime.now(), newAlarmDateTime).toMillis()), 500) {

@Override
public void onTick(long l) {
public void onTick(long millisUntilFinished) {
}

@Override
public void onFinish() {
Intent intent1 = new Intent(myInstance, Service_RingAlarm.class);
intent1.putExtra(ConstantsAndStatics.BUNDLE_KEY_ALARM_DETAILS, alarmDetails);
intent1.putExtra(Service_RingAlarm.BUNDLE_KEY_NO_OF_TIMES_SNOOZED, numberOfTimesTheAlarmhasBeenSnoozed);
Intent intent1 = new Intent(myInstance, Service_RingAlarm.class)
.putExtra(ConstantsAndStatics.BUNDLE_KEY_ALARM_DETAILS, alarmDetails)
.putExtra(Service_RingAlarm.BUNDLE_KEY_NO_OF_TIMES_SNOOZED, numberOfTimesTheAlarmhasBeenSnoozed);
ContextCompat.startForegroundService(myInstance, intent1);
myInstance.stopSelf();
}
Expand All @@ -122,10 +120,8 @@ public void onFinish() {
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(Integer.toString(NOTIFICATION_ID),
"in.basulabs.shakealarmclock Notifications", importance);
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(Integer.toString(NOTIFICATION_ID),"in.basulabs.shakealarmclock Notifications", importance);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
channel.setSound(null, null);
assert notificationManager != null;
notificationManager.createNotificationChannel(channel);
Expand All @@ -139,11 +135,9 @@ private Notification buildSnoozeNotification() {

Intent intent = new Intent();
intent.setAction(ConstantsAndStatics.ACTION_CANCEL_ALARM);
PendingIntent contentPendingIntent = PendingIntent.getBroadcast(this, 5017, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent contentPendingIntent = PendingIntent.getBroadcast(this, 5017, intent, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this,
Integer.toString(NOTIFICATION_ID))
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, Integer.toString(NOTIFICATION_ID))
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(getResources().getString(R.string.notifContent_snooze))
.setPriority(NotificationCompat.PRIORITY_HIGH)
Expand Down Expand Up @@ -226,13 +220,11 @@ private void dismissAlarm() {

intent.putExtra(ConstantsAndStatics.BUNDLE_KEY_ALARM_DETAILS, alarmDetails);

PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this,
alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_ALARM_ID), intent, 0);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, alarmDetails.getInt(ConstantsAndStatics.BUNDLE_KEY_ALARM_ID), intent, 0);

ZonedDateTime zonedDateTime = ZonedDateTime.of(alarmDateTime.withSecond(0), ZoneId.systemDefault());

alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(zonedDateTime.toEpochSecond() * 1000,
pendingIntent2), pendingIntent2);
alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(zonedDateTime.toEpochSecond() * 1000, pendingIntent2), pendingIntent2);
}
ConstantsAndStatics.schedulePeriodicWork(this);
stopForeground(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ private void activateAlarmsIfInactive() {

}

if (stopExecuting && ! isStopped()) {
if ((stopExecuting && ! isStopped()) || Service_RingAlarm.isThisServiceRunning || Service_SnoozeAlarm.isThisServiceRunning) {
break;
}
}
Expand Down
Loading

0 comments on commit cfb6042

Please sign in to comment.