如何在每天不同的时间在android studio中设置每日重复通知?

Posted

技术标签:

【中文标题】如何在每天不同的时间在android studio中设置每日重复通知?【英文标题】:How to set daily repeating notification in android studio at different times each day? 【发布时间】:2017-02-08 18:27:53 【问题描述】:

我目前有每天下午 6 点重复的每日重复通知。我想做的不是下午 6 点,而是在活动即将开始时显示通知。我有一个事件数组列表,它包含日期和时间,这可能吗?以下是我目前显示通知的方式。

这是我的主要活动

Calendar calendar = Calendar.getInstance();
 calendar.set(Calendar.HOUR_OF_DAY, 18);
 calendar.set(Calendar.MINUTE, 30);
 calendar.set(Calendar.SECOND, 0);
 Intent intent1 = new Intent(MainActivity.this, AlarmReceiver.class);
 PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
 AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
 am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

这是在我的广播接收器类中

公共类 AlarmReceiver 扩展 BroadcastReceiver

    @Override
    public void onReceive(Context context, Intent intent) 
        // TODO Auto-generated method stub

        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notificationIntent = new Intent(context, EVentsPerform.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
                context).setSmallIcon(R.drawable.applogo)
                .setContentTitle("Alarm Fired")
                .setContentText("Events To be PErformed").setSound(alarmSound)
                .setAutoCancel(true).setWhen(when)
                .setContentIntent(pendingIntent)
                .setVibrate(new long[]1000, 1000, 1000, 1000, 1000);
        notificationManager.notify(MID, mNotifyBuilder.build());
        MID++;

    


我不知道如何设置时间,以便在发生事件时以及是否有事件时重复。任何指示和帮助都将不胜感激。谢谢

【问题讨论】:

【参考方案1】:

您可以为每个事件设置警报。从数据库中读取所有事件时间,然后为这些事件设置单独的警报。而不是 setRepeating 使用这个。设置的闹钟变种是针对不同的安卓版本将手机从睡眠中唤醒。

private void setAlarm(Long dateInMillis) 

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent alarmIntent = new Intent(this, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    if (Build.VERSION.SDK_INT >= 23) 
        am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, dateInMillis, pi);
     else if (Build.VERSION.SDK_INT >= 19) 
        am.setExact(AlarmManager.RTC_WAKEUP, dateInMillis, pi);
     else 
        am.set(AlarmManager.RTC_WAKEUP, dateInMillis, pi);
    

dateInMillis 是 Calender.getInstance().getTimeInMillis(),表示您要为其设置闹钟的时间。所以我希望你有一个长期存储在你的数据库中,这是让你的生活更轻松的价值

public ArrayList<String> getAlarms() 
    SQLiteDatabase db;
    ArrayList<String> result = new ArrayList<String>();
    String myPath = DATABASE_PATH + DATABASE_NAME;

    db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    selectQuery = "SELECT * FROM TABLE";
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) 
        result.add(cursor.getString(cursor.getColumnIndex("WhateverYourColumnIs")));
        while (cursor.moveToNext()) 
            result.add(cursor.getString(cursor.getColumnIndex("WhateverYourColumnIs")));
        
    
    cursor.close();
    db.close();

    return result;

您可以将字符串转换为 Long

DatabaseHelper db = new DatabaseHelper();
ArrayList<String> alarms = db.getAlarms()

for(String alarm : alarms)
    try
        setAlarm(Long.parseLong(alarm));
    catch(NumberFormatException nfe)
        //Not a number
    

类似的东西

private Long calendarMillis(String date, String time)
    Long result;
    //Do A bunch of stuff to get the information to fill in below from what you bring in.
    Calendar c = Calendar.getInstance();
    c.set(Calendar.YEAR, year);
    //...Calendar.HOUR, Calendar.MONTH, Calendar.DAY
    c.set(Calendar.MINUTE, minute);
    result = c.getTimeInMillis();
    return result;


public class NotificationInformation
    Long alarmTime;
    String name;
    public void NotificationInformation()

    
    public void NotificationInformation(NotificationInformation ni)
        this.name = ni.getName();
        this.alarmTime = ni.getAlarmTime();
    
    //getters and setters
    public void setAlarmTime(Long alarmTime)
        this.alarmTime = alarmTime;
    
    public void setName(String name)
        this.nime = nime;
    
    public Long getAlarmTime()
        return alarmTime;
    
    public String getName()
        return name;
    

【讨论】:

【参考方案2】:
public class DatabaseHandler extends SQLiteOpenHelper 
    private static final String DATABASE_PATH = "/data/data/YOUR_PACKAGE_HERE/databases/";
    private static final String DATABASE_NAME = "YOUR_DATABASE.db";
    private static final int DATABASE_VERSION = 1;
    private SQLiteDatabase myDataBase = null;

    private final Context myContext;
    Context context = null;

    public DatabaseHandler(Context context) 
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.myContext = context;
        // TODO Auto-generated constructor stub
        myDataBase = this.getWritableDatabase();
        myDataBase.close();
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE IF NOT EXISTS INFO (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "alarmTime INTEGER," +
                "name TEXT)");
    

    public void addInfo(long time, String name) 
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("alarmTime", time);
        values.put("name", name);

        db.insert("INFO", null, values);
        db.close();
    

    public ArrayList<NotificationInfo> getInfoAll() 
        String selectQuery;
        SQLiteDatabase db;
        Cursor cursor;
        NotificationInfo ni = new NotificationInfo();

        ArrayList<NotificationInfo> result = new ArrayList<NotificationInfo>();
        String myPath = DATABASE_PATH + DATABASE_NAME;

        db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        selectQuery = "SELECT * FROM INFO";
        cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) 
            ni.setAlarmTime(cursor.getLong(cursor.getColumnIndex("alarmTime"));
            ni.setName(cursor.getLong(cursor.getColumnIndex("name"));
            result.add(new NotificationInfo(ni));
            while(cursor.moveToNext())
                ni.setAlarmTime(cursor.getLong(cursor.getColumnIndex("alarmTime"));
                ni.setName(cursor.getLong(cursor.getColumnIndex("name"));
                result.add(new NotificationInfo(ni));
            
        
        cursor.close();
        db.close();

        return result;
    


public class AlarmActivity extends Activity
    //standard code for activity goes here
    private void buttonClicked()
        Calendar c = Calendar.getInstance();
        DatabaseHandler db = new Databasehandler(AlarmActivity.this);
        ArrayList<NotificationInfo> alarms = db.getInfoAll();
        db.close();

        for(NotificationInfo ni : alarms)
            c.setTimeInMillis(ni.getAlarmTime());
            c.add(Calendar.MINUTE, -30);
            setAlarm(c);
        
    

    private void setAlarm(Long dateInMillis) 
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent alarmIntent = new Intent(this, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        if (Build.VERSION.SDK_INT >= 23) 
            am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, dateInMillis, pi);
         else if (Build.VERSION.SDK_INT >= 19) 
            am.setExact(AlarmManager.RTC_WAKEUP, dateInMillis, pi);
         else 
            am.set(AlarmManager.RTC_WAKEUP, dateInMillis, pi);
        
           


public class NotificationInformation
    Long alarmTime;
    String name;
    public void NotificationInformation()

    
    public void NotificationInformation(NotificationInformation ni)
        this.name = ni.getName();
        this.alarmTime = ni.getAlarmTime();
    
    //getters and setters
    public void setAlarmTime(Long alarmTime)
        this.alarmTime = alarmTime;
    
    public void setName(String name)
        this.nime = nime;
    
    public Long getAlarmTime()
        return alarmTime;
    
    public String getName()
        return name;
    

【讨论】:

您好,我看到您删除了所有的cmets,很抱歉再次打扰您。我之前问过您为什么要创建您没有响应的 DatabaseHandler 类,请问这应该是对我已经拥有的 sqlite 表的补充还是代表它?我真的很感谢你的努力,但我无法把它们放在一起,如果我能在我把代码放在一起的时候给我一些指导,希望我能让它工作。 我没有删除 cmets。主持人可能做了。我使用数据库助手类,因为它实现了 SQLiteHelper。 SQLLiteHelper 类是一个内置模块,用于处理 android 平台内的数据库操作。它让我可以做 db.insert() 之类的事情。查找android database example 好的,那么您是否创建另一个数据库来保存要传递给通知的日期和名称? 不,你为什么要那样做?我不相信您现在根本没有数据库。如何在没有数据库助手类的情况下创建数据库?显示您的数据库代码。 我在 SQLite 中确实有一个数据库,所以我问你为什么创建 DatabaseHandler 类,因为我看到你正在向其中输入值。

以上是关于如何在每天不同的时间在android studio中设置每日重复通知?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Android Studio 中使用具有不同应用名称的风味?

如何在一个 android studio 项目中为两种不同类型的用户提供两种不同的导航抽屉活动?

如何在进入不同活动的情况下不删除 Android Studio 活动中的变量?

如何在 Android Studio 中分析测试?

请教如何使用android studio同时打包多个apk

第二章:Android Studio概述[学习Android Studio汉化教程]