【问题标题】:Android Running SQL statement in backgroundAndroid后台运行SQL语句
【发布时间】:2014-11-23 18:00:56
【问题描述】:

我在使用 Android 中的警报管理器时遇到了一些问题。我遇到的是,当我将闹钟设置为每分钟重复一次时,它可以工作:

mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(), 60000, pi);

但是,当我尝试将其设置为每天运行一次通知时,它不起作用:

mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);

这是我执行警报管理器的部分。这个方法是在 onCreate 调用的:

public void buildListView() {
    // Database part to retrieve the data

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 0 );
    calendar.set(Calendar.MINUTE, 1);
        notificationCount = notificationCount + 1;
        AlarmManager mgr = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Intent notificationIntent = new Intent(context,
                ReminderAlarm.class);
        notificationIntent.putExtra("RecurID", recurID);    
        notificationIntent.putExtra("RecurStartDate", recurDate);   
        notificationIntent.putExtra("CurrentDate", dateFormat.format(new Date()));
        notificationIntent.putExtra("Description", recurDesc);
        notificationIntent.putExtra("Type", recurType);
        notificationIntent.putExtra("Amount", formatAmount);
        notificationIntent.putExtra("CategoryName", categoryName);
        notificationIntent.putExtra("Frequency", frequency);
        notificationIntent.putExtra("NotifyCount", notificationCount);
        PendingIntent pi = PendingIntent.getBroadcast(context,
                notificationCount, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);

        ComponentName receiver = new ComponentName(context, BootReceiver.class);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    }
}

从上面的方法,它会调用一个接收器:

public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent i) {
    if (i.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
        int notificationCount = Integer.parseInt(i.getExtras()
                .get("NotifyCount").toString());
        scheduleAlarms(context,notificationCount);
    }
}

static void scheduleAlarms(Context context, int notificationCount) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 1);
    AlarmManager mgr = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
    Intent notificationIntent = new Intent(context, ReminderAlarm.class);
    PendingIntent pi = PendingIntent.getService(context, notificationCount,
            notificationIntent, 0);

    mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
            calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
}

}

然后从bootReceiver类调用alarmReminder类做SQL语句和提示通知:

public class ReminderAlarm extends BroadcastReceiver {
private NotificationManager mNotificationManager;
private Notification notification;

@Override
public void onReceive(Context context, Intent intent) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    //Getting all the data from extras

    Calendar cal = Calendar.getInstance();
    try {
        cal.setTime(dateFormat.parse(recurStartDate));
        if (frequencyStr.equals("Daily")) {
            cal.add(Calendar.DAY_OF_MONTH, 1);
            nextPaymentDate = dateFormat.format(cal.getTimeInMillis());
            cal.add(Calendar.DAY_OF_MONTH, -1);
        } else if (frequencyStr.equals("Weekly")) {
            cal.add(Calendar.WEEK_OF_YEAR, 1);
            nextPaymentDate = dateFormat.format(cal.getTimeInMillis());
            cal.add(Calendar.WEEK_OF_YEAR, -1);
        } 
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // If dates match then execute the SQL statements
    if (currentDate.equals(nextPaymentDate)) {
        DatabaseAdapter mDbHelper = new DatabaseAdapter(
                context.getApplicationContext());
        mDbHelper.createDatabase();
        mDbHelper.open();
        TransactionRecModel trm = new TransactionRecModel();
        CategoryController cc = new CategoryController(mDbHelper.open());

        trm.setDate(currentDate);
        trm.setTransDescription(description);
        trm.setType(type);
        trm.setAmount(Float.parseFloat(amount));

        // Get the categoryID based on categoryName
        String catID = cc.getCatIDByName(categoryName);
        trm.setCategory(catID);

        // Check if the recurring record exists before insert new
        // transaction record
        RecurringController rc1 = new RecurringController(mDbHelper.open());
        boolean recurExist = rc1.checkRecurExist(recurStartDate,
                description, catID);
        if (recurExist == true) {
            TransactionRecController trc = new TransactionRecController(
                    mDbHelper.open());
            // Check if the transaction record exists to prevent
            // duplication
            boolean moveNext = trc.checkTransExist(trm);
            if (moveNext == false) {

                if (trc.addTransactionRec(trm)) {
                    // Update recurring start date after insertion of
                    // transaction
                    RecurringModel rm = new RecurringModel();
                    rm.setRecurringID(recurID);
                    rm.setRecurringStartDate(currentDate);

                    RecurringController rc = new RecurringController(
                            mDbHelper.open());
                    if (rc.updateRecurringDate(rm)) {
                        mNotificationManager = (NotificationManager) context
                                .getSystemService(Context.NOTIFICATION_SERVICE);
                        PendingIntent contentIntent = PendingIntent
                                .getActivity(context, Integer.parseInt(intent.getExtras()
                                        .get("NotifyCount").toString()), new Intent(), 0);
                        notification = new Notification(
                                R.drawable.ic_launcher, "Notification",
                                System.currentTimeMillis());
                        notification
                                .setLatestEventInfo(context, description,
                                        nextPaymentDate, contentIntent);
                        mNotificationManager.notify(
                                Integer.parseInt(intent.getExtras()
                                        .get("NotifyCount").toString()),
                                notification);
                        mDbHelper.close();
                    }
                }
            }
        }
    }
}

奇怪的是,当我将它设置为每分钟重复一次时,它会工作并在我的提醒警报类中执行插入和更新 SQL。但是,当我将其重新设置为每天运行一次时,它不起作用。我想知道我的代码的哪一部分出错了。

提前致谢。

【问题讨论】:

  • 你如何测试它?可以试试setExactRepeating()函数吗?
  • 我昨天通过添加循环记录进行了测试。但直到今天,在我手动启动应用程序之前,它都不会在提醒警报类中执行我的插入和更新 SQL 语句。它应该在后台运行
  • 您可以通过更改设备时间设置来检查它。我猜你不必等待 1 天。
  • @tasomaniac 我认为它基于日历运行?那么从设备设置中更改日期有效吗?但基本上如果我用一分钟测试它,它运行得很好。我不知道为什么当我将其更改为每天一次时它无法正常运行
  • @tasomaniac 你介意更具体还是指出我做错的部分?因为我真的不知道它为什么会这样。

标签: java android sql date alarmmanager


【解决方案1】:

您是否尝试通过关闭应用程序以 1 分钟间隔发出警报,并检查 DB 插入是否发生?

您也可以尝试更改:

DatabaseAdapter mDbHelper = new DatabaseAdapter(context.getApplicationContext());

DatabaseAdapter mDbHelper = new DatabaseAdapter(context);

【讨论】:

  • 是的,我尝试了 1 和 5 分钟。首先,我设置了一个循环任务。之后,我关闭应用程序。这算作关闭应用程序吗?奇怪的是数据库插入只在我启动应用程序时运行,它不会在我为警报管理器设置的计时器内运行
  • 我测试了很多次。我意识到有一个问题。假设我每两小时设置一次重复,对于每一次,在我设置任务后的一分钟,它将执行数据库插入。然后,我清除了交易记录并更改了我的设备的时间设置,它再次完美运行。但是假设我将其设置为每天一次,在我设置任务后的一分钟不会提示任何通知,这意味着由于日期不同而未执行数据库插入。第二天,它不会运行。
  • 也就是说,如果它在我设置的一分钟内没有执行数据库插入,它就不会运行。你有什么想法吗?
  • 如果 db 插入在 1 或 2 分钟的间隔内有效,那么我看不出它在 1 天的间隔内无效的任何原因。
  • 它以一种非常奇怪的方式运行。假设我在 2014 年 3 月 10 日设置了一个重复任务。它应该在 04/10/2014 12.01AM 执行 DB 插入。但不知何故,它被推迟了一天,即 2014 年 5 月 10 日,但所有数据库插入和更新都运行良好。你有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多