android – 防止周末发生重复闹钟

前端之家收集整理的这篇文章主要介绍了android – 防止周末发生重复闹钟前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个闹钟应用程序使用AlarmManager类,允许用户设置一次性闹钟或重复闹钟.我想扩展功能,以便用户可以将闹钟排除在外,例如在周末.

我已经把代码封锁了周末的闹钟到AlarmReceiver.java.

>我不知道AlarmReceiver.java是否是在周末放置警报的代码的正确位置.
>我不知道我正在使用的代码在周末阻止闹钟是正确的.基本上我告诉AlarmReceiver如果今天是星期六或星期天什么都不做.否则,消除警报.

AlarmActivity.java代码设置闹钟:

//Set a one time alarm
            if (repeatInterval == 0) {
                    alarmManager.set(AlarmManager.RTC,alarmTime.getTimeInMillis(),pendingIntent);
                    AlarmReceiver alarmReceiver = new AlarmReceiver(this); //https://stackoverflow.com/questions/16678763/the-method-getapplicationcontext-is-undefined

                    Toast.makeText(AlarmActivity.this,"Your one time reminder is now set for " + hourSet + ":" + minuteSetString + amPmlabel,Toast
                            .LENGTH_LONG)
                            .show();
            }

            //Set a repeating alarm
            else {
                alarmManager.setRepeating(AlarmManager.RTC,repeatIntervalMilliseconds,pendingIntent);
                AlarmReceiver alarmReceiver = new AlarmReceiver(this); //https://stackoverflow.com/questions/16678763/the-method-getapplicationcontext-is-undefined

                    Toast.makeText(AlarmActivity.this,"Your reminder is now set for " + hourSet + ":" + minuteSetString + amPmlabel + " and will " +
                            "repeat " +
                            "every " +
                            repeatInterval + " minutes.",Toast.LENGTH_LONG).show();
        }

AlarmService.Java:

package com.joshbgold.move.backend;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import com.joshbgold.move.R;
import com.joshbgold.move.main.AlarmActivity;

public class AlarmService extends IntentService {
    private NotificationManager alarmNotificationManager;

    public AlarmService() {
        super("AlarmService");
    }

    @Override
    public void onHandleIntent(Intent intent) {

            sendNotification("Move reminder");

    }

    private void sendNotification(String msg) {
        alarmNotificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(this,new Intent(this,AlarmActivity.class),0);

        NotificationCompat.Builder alarmNotificationBuilder = new NotificationCompat.Builder(
                this).setContentTitle("Reminder").setSmallIcon(R.mipmap.ic_launcher)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg);


        alarmNotificationBuilder.setContentIntent(contentIntent);
        alarmNotificationManager.notify(1,alarmNotificationBuilder.build());
    }

}

AlarmReceiver.Java:

package com.joshbgold.move.backend;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.content.WakefulBroadcastReceiver;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class AlarmReceiver extends WakefulBroadcastReceiver {

    Context myContext;
    public AlarmReceiver(Context context){
        myContext = context;
    }

    public AlarmReceiver(){

    }

    //get the current day
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
    Date date = new Date();
    String dayOfTheWeek = simpleDateFormat.format(date);

    Calendar calendar = Calendar.getInstance();
    int currentHour = calendar.HOUR_OF_DAY;

    boolean noWeekends = true;
    boolean workHoursOnly = true;

    @Override
    public void onReceive(final Context context,Intent intent) {


        try {  //this value could be null if user has not set it...
            noWeekends = loadPrefs("noWeekends",noWeekends);
            workHoursOnly = loadPrefs("workHoursOnly",workHoursOnly);
        } catch (Exception e) {
            e.printStackTrace();
        }


        if(dayOfTheWeek == "Saturday" || dayOfTheWeek == "Sunday"  && noWeekends == true) {
            //Alarm is not wanted on the weekend
            try {
                wait(1);  //waits for one-thousandth of a millisecond
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        else if ((currentHour < 9 || currentHour > 17)  && workHoursOnly == true){
            //Alarm outside of work hours
            try {
                wait(1);  //waits for one-thousandth of a millisecond
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        else {

            Intent myIntent = new Intent();
            myIntent.setClassName("com.joshbgold.move","com.joshbgold.move.main.ReminderActivity");
            myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(myIntent);
        }
    }

    //get prefs
    private boolean loadPrefs(String key,boolean value) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(myContext);
        boolean data = sharedPreferences.getBoolean(key,value);
        return data;
    }
}

AlarmReceiver.java(更正后的代码)

package com.joshbgold.move.backend;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.content.WakefulBroadcastReceiver;
import java.util.Calendar;

public class AlarmReceiver extends WakefulBroadcastReceiver {

    Context myContext;
    public AlarmReceiver(Context context){
        myContext = context;
    }

    public AlarmReceiver() {

    }

    private boolean workHoursOnly = false;
    private boolean noWeekends = false;

    @Override
    public void onReceive(final Context context,Intent intent) {

        Calendar calendar = Calendar.getInstance();
        int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
        int today = calendar.get(Calendar.DAY_OF_WEEK);
        boolean isWeekend = (today == Calendar.SUNDAY) || (today == Calendar.SATURDAY);
        boolean isOutsideWorkHours = (currentHour < 9) || (currentHour > 16);

        //checkPrefs checks whether a preferences key exists
        if (checkPrefs("workHoursOnlyKey")){
            workHoursOnly = loadPrefs("workHoursOnlyKey",workHoursOnly);
        }

        if(checkPrefs("noWeekendsKey")){
            noWeekends = loadPrefs("noWeekendsKey",noWeekends);
        }

        /* try {  //this value could be null if user has not set it...
            workHoursOnly = loadPrefs("workHoursOnly",workHoursOnly);
        } catch (Exception e) {
            e.printStackTrace();
        }
       */

        /*try {  //this value could be null if user has not set it...
        noWeekends = loadPrefs("noWeekends",noWeekends);
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        if(isWeekend && noWeekends) {
            //Alarm is not wanted on the weekend
            try {
                Thread.sleep(1);  //waits for millisecond
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        else if (isOutsideWorkHours  && workHoursOnly){
            //Alarm not wanted outside of work hours
            try {
                Thread.sleep(1);  //waits for millisecond
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        else {
            //Alarm is wanted,and should go off
            Intent myIntent = new Intent();
            myIntent.setClassName("com.joshbgold.move","com.joshbgold.move.main.ReminderActivity");
            myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(myIntent);
        }
    }

    //check if a prefs key exists
    private boolean checkPrefs(String key){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(myContext);
        boolean exists = sharedPreferences.contains(key);
        return exists;
    }

    //get prefs
    private boolean loadPrefs(String key,value);
        return data;
    }
}

解决方法

你的做法很好反正我建议你避免使用硬编码的字符串进行周末检查.您已经在代码中定义了一个Calendar对象,只需使用它:
Calendar calendar = Calendar.getInstance();
//..
int today  = calendar.get(Calendar.DAY_OF_WEEK);
boolean isWeekend = (today == Calendar.SUNDAY) || (today == Calendar.SATURDAY);

并相应更新您的代码

//...
  int today  = calendar.get(Calendar.DAY_OF_WEEK);
  boolean isWeekend = (today == Calendar.SUNDAY) || (today == Calendar.SATURDAY);
  if(isWeekend && noWeekends == true) {
        //Alarm is not wanted on the weekend
        try {
            Thread.sleep(1);  
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
  //...

猜你在找的Android相关文章