com.brayanarias.alarmproject.activity.AlarmScreenActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.brayanarias.alarmproject.activity.AlarmScreenActivity.java

Source

/*
 * Copyright (C) 2015 brayanarias.com ing.brayanarias@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.brayanarias.alarmproject.activity;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.animation.PathInterpolatorCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Interpolator;
import android.widget.TextView;
import android.widget.Toast;

import com.brayanarias.alarmproject.R;
import com.brayanarias.alarmproject.database.AlarmDataBase;
import com.brayanarias.alarmproject.database.DataBaseManager;
import com.brayanarias.alarmproject.model.Alarm;
import com.brayanarias.alarmproject.receiver.AlarmReceiver;
import com.brayanarias.alarmproject.task.VolumeTask;
import com.brayanarias.alarmproject.util.AlarmUtilities;
import com.brayanarias.alarmproject.util.Constant;

import java.util.Calendar;

public class AlarmScreenActivity extends AppCompatActivity {
    public static final String tag = AlarmScreenActivity.class.getName();
    private static final int WAKELOCK_TIMEOUT = 120 * 1000;
    private static final String TAG = AlarmScreenActivity.class.getName();
    private PowerManager.WakeLock wakeLock;
    private MediaPlayer mediaPlayer;
    private Vibrator vibrator;
    private int actualVolume;
    public static final long[] sVibratePattern = new long[] { 500, 500 };
    private NotificationManager alarmNotificationManager;
    VolumeTask task;
    private boolean flag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_screen);
        int alarmId = getIntent().getIntExtra(Constant.alarmIdKey, -1);
        if (alarmId == -1) {
            finish();
        }
        NotificationManager alarmNotificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        alarmNotificationManager.cancelAll();
        String name = getIntent().getStringExtra(Constant.alarmNameKey);
        if (name == null || name.isEmpty()) {
            name = getString(R.string.app_name);
        }
        String hourFormatted = getIntent().getStringExtra(Constant.alarmHourFormattedKey);
        String msgampm = getIntent().getStringExtra(Constant.alarmAmPmKey);
        String msgNotification = name;
        msgNotification = msgNotification + " - " + hourFormatted + " " + msgampm;
        sendNotification(msgNotification);
        Calendar calendar = Calendar.getInstance();
        String hourText;
        int actualAmPm = calendar.get(Calendar.AM_PM);
        String ampm = actualAmPm == Calendar.AM ? "AM" : "PM";
        int hour = calendar.get(Calendar.HOUR);
        hour = hour == 0 ? 12 : hour;
        int minute = calendar.get(Calendar.MINUTE);
        String minuteString = minute >= 10 ? "" + minute : "0" + minute;
        hourText = hour + ":" + minuteString + " " + ampm;
        TextView tvAlarmHourScreen = (TextView) findViewById(R.id.tvAlarmHourScreen);
        tvAlarmHourScreen.setText(hourText);
        TextView tvAlarmNameScreen = (TextView) findViewById(R.id.tvAlarmNameScreen);
        if (name.equals(getString(R.string.app_name))) {
            name = AlarmUtilities.getSalute(getApplicationContext());
        }
        if (tvAlarmNameScreen != null) {
            tvAlarmNameScreen.setText(name);
        }
        FloatingActionButton btDismiss = (FloatingActionButton) findViewById(R.id.btDismiss);
        if (btDismiss != null) {
            btDismiss.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                    }
                    if (vibrator != null) {
                        vibrator.cancel();
                    }
                    finish();
                }
            });
        }
        FloatingActionButton btPostpone = (FloatingActionButton) findViewById(R.id.btPostpone);
        if (btPostpone != null) {
            btPostpone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int alarmId = getIntent().getIntExtra(Constant.alarmIdKey, -1);
                    int postpone = getIntent().getIntExtra(Constant.alarmPostponeKey, -1);
                    int minutes = getResources().getIntArray(R.array.alarm_postpone_value_array)[postpone];
                    AlarmReceiver.dismissAlarm(alarmId, minutes, getApplicationContext());
                    String text = AlarmUtilities.getMessageRemainingPostpone(postpone, getResources());
                    Toast.makeText(getApplication(), text, Toast.LENGTH_SHORT).show();
                    flag = false;
                    finish();
                }
            });
        }
        int postpone = getIntent().getIntExtra(Constant.alarmPostponeKey, -1);
        //postpone configuration
        if (postpone > 0) {
            String timeText = getResources().getStringArray(R.array.alarm_postpone_array)[postpone];
        } else {
            if (btPostpone != null) {
                btPostpone.setEnabled(false);
            }
        }
        String tone = getIntent().getStringExtra(Constant.alarmToneKey);
        playRingtone(tone);
        //Start animation
        starAnimation();
        //Ensure wakelock release
        Runnable releaseWakelock = new Runnable() {

            @Override
            public void run() {
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

                if (wakeLock != null && wakeLock.isHeld()) {
                    wakeLock.release();
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                    }
                    if (vibrator != null) {
                        vibrator.cancel();
                    }
                    Log.e(TAG, "Entra a realease wakelock");
                    finish();
                }
            }
        };
        new Handler().postDelayed(releaseWakelock, WAKELOCK_TIMEOUT);
    }

    private void starAnimation() {
        View pulseView = findViewById(R.id.pulse);
        View pulseDismiss = findViewById(R.id.pulseDismiss);
        View pulseSnooze = findViewById(R.id.pulseSnooze);
        ValueAnimator pulseAnimator = ObjectAnimator.ofPropertyValuesHolder(pulseView,
                PropertyValuesHolder.ofFloat(View.SCALE_X, 0.0f, 1.0f),
                PropertyValuesHolder.ofFloat(View.SCALE_Y, 0.0f, 1.0f),
                PropertyValuesHolder.ofFloat(View.ALPHA, 1.0f, 0.0f));
        pulseAnimator.setDuration(2000);
        pulseAnimator.setRepeatCount(ValueAnimator.INFINITE);
        Interpolator interpolator = PathInterpolatorCompat.create(0.0f, 0.0f, 0.2f, 1.0f);
        pulseAnimator.setInterpolator(interpolator);
        pulseAnimator.start();
        ValueAnimator dismissAnimator = ObjectAnimator.ofPropertyValuesHolder(pulseDismiss,
                PropertyValuesHolder.ofFloat(View.SCALE_X, 0.0f, 1.0f),
                PropertyValuesHolder.ofFloat(View.SCALE_Y, 0.0f, 1.0f),
                PropertyValuesHolder.ofFloat(View.ALPHA, 1.0f, 0.0f));
        dismissAnimator.setDuration(1000);
        dismissAnimator.setRepeatCount(ValueAnimator.INFINITE);
        dismissAnimator.setInterpolator(interpolator);
        dismissAnimator.start();
        ValueAnimator snoozeAnimator = ObjectAnimator.ofPropertyValuesHolder(pulseSnooze,
                PropertyValuesHolder.ofFloat(View.SCALE_X, 0.0f, 1.0f),
                PropertyValuesHolder.ofFloat(View.SCALE_Y, 0.0f, 1.0f),
                PropertyValuesHolder.ofFloat(View.ALPHA, 1.0f, 0.0f));
        snoozeAnimator.setDuration(1000);
        snoozeAnimator.setRepeatCount(ValueAnimator.INFINITE);
        snoozeAnimator.setInterpolator(interpolator);
        snoozeAnimator.start();
    }

    private void playRingtone(String tone) {
        mediaPlayer = new MediaPlayer();
        try {
            Uri ringtoneUri;
            if (tone.equals("default")) {
                ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
            } else {
                ringtoneUri = Uri.parse(tone);
            }

            if (ringtoneUri != null) {
                mediaPlayer.setDataSource(this, ringtoneUri);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mediaPlayer.setLooping(true);
                mediaPlayer.prepare();
                AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                actualVolume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
                incrementVolume();
                mediaPlayer.start();
                audioManager.setStreamVolume(AudioManager.STREAM_ALARM, 1, 0);
            }
        } catch (Exception e) {
            Log.e(tag, e.getLocalizedMessage(), e);
        }
    }

    private void incrementVolume() {
        task = new VolumeTask(AlarmScreenActivity.this);
        task.execute();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "on Resume Method");
        // Set the window to keep screen on
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        // Acquire wakelock
        PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
        if (wakeLock == null) {
            wakeLock = pm.newWakeLock((PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), tag);
        }

        if (!wakeLock.isHeld()) {
            wakeLock.acquire();
        }
    }

    @Override
    public void onBackPressed() {
        return;
    }

    @Override
    protected void onDestroy() {
        Log.e(TAG, "on Destroy method");
        if (task != null) {
            task.cancel(true);
        }
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audioManager.setStreamVolume(AudioManager.STREAM_ALARM, actualVolume, 0);
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        if (vibrator != null) {
            vibrator.cancel();
        }
        NotificationManager alarmNotificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        alarmNotificationManager.cancelAll();
        if (flag) {
            int deleteAlarm = getIntent().getIntExtra(Constant.alarmDeleteAfterKey, 0);
            int id = getIntent().getIntExtra(Constant.alarmIdKey, -1);

            if (deleteAlarm == 1) {
                DataBaseManager dataBaseManager = DataBaseManager.getInstance(getApplicationContext());
                AlarmDataBase.deleteAlarm(id, dataBaseManager);
            } else if (getIntent().getStringExtra(Constant.alarmDaysKey).equals("0000000")) {
                DataBaseManager dataBaseManager = DataBaseManager.getInstance(getApplicationContext());
                Alarm alarm = AlarmDataBase.getAlarmById(dataBaseManager, id);
                alarm.setActivated(0);
                AlarmDataBase.updateAlarm(alarm, dataBaseManager);
            }
            AlarmReceiver.setAlarms(getApplicationContext());
        }
        super.onDestroy();
    }

    private void sendNotification(String msg) {
        alarmNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String title = getString(R.string.title_activity_main);
        Intent intent = new Intent(this, AlarmScreenActivity.class);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(R.mipmap.ic_launcher)).getBitmap();
        NotificationCompat.Builder alarmNotificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(title).setSmallIcon(R.drawable.ic_fab_alarm).setLargeIcon(bitmap)
                .setCategory(Notification.CATEGORY_ALARM)
                .setColor(ContextCompat.getColor(getBaseContext(), R.color.colorAccent))
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg).setOngoing(true)
                .setContentIntent(pendingIntent);
        alarmNotificationManager.notify(1503, alarmNotificationBuilder.build());
    }

    public Vibrator getVibrator() {
        return vibrator;
    }

    public void setVibrator(Vibrator vibrator) {
        this.vibrator = vibrator;
    }
}