在后台运行Android的SQL语句 [英] Android Running SQL statement in background

查看:203
本文介绍了在后台运行Android的SQL语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些麻烦,在Android的报警管理。我所遇到的是当我将闹钟设置为重复的每一分钟,它的工作原理:

I am having some trouble with Alarm manager in Android. What I've encountered is when I set the alarm to repeat for every single minute, it works:

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

然而,当我尝试将它设置为每天运行一次的通知,这是行不通的:

However, when I try to set it to run the notification once per day, it does not work:

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

这是我执行警报管理的一部分。这种方法被称为在的onCreate:

This is the part where I execute the Alarm manager. This method was called at 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);
    }
}

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

And from the method above, it will call a receiver:

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语句,并及时通知:

Then from the bootReceiver class, it will call the alarmReminder class to do the SQL statement and prompt notification:

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();
                    }
                }
            }
        }
    }
}

但奇怪的是,当我将其设置为重复的每一分钟,它的工作原理和执行我的reminderAlarm类中的插入和更新SQL。然而,当我将其设置回每天运行一次,这是行不通的。我不知道哪我codeS的一部分出了问题。

The strange thing is when I set it to repeat for every single minute, it works and execute the insert and update SQL in my reminderAlarm class. However, when I set it back to run once per day, it does not work. I wonder which part of my codes went wrong.

先谢谢了。

推荐答案

你有没有试着用1分钟时间报警关闭应用程序,并检查DB插入是否正在发生或不?

Did you try the alarm with 1 min interval by closing the application, and check whether the DB insertion is happening or not?

你也可以尝试改变:

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

DatabaseAdapter mDbHelper = new DatabaseAdapter(context);

这篇关于在后台运行Android的SQL语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆