java - Android 循环任务在后台运行

标签 java android alarmmanager recurring

我在尝试在 Android 中执行重复任务时遇到一些问题。以下是我填充 ListView 的方法:

public View getView(int position, View convertView, ViewGroup parent) {
    String recurID;
    if (convertView == null) {

        convertView = inflater.inflate(R.layout.recur_listview_row, null);

        viewHolder = new ViewHolder();
        viewHolder.txt_ddate = (TextView) convertView.findViewById(R.id.txtDisplayRecurDate);
        viewHolder.txt_damount = (TextView) convertView.findViewById(R.id.txtDisplayRecurAmount);
        viewHolder.txt_dfrequency = (TextView) convertView.findViewById(R.id.txtDisplayFrequency);

        convertView.setTag(viewHolder);

    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    recurID = _recurlist.get(position).getRecurringID();
    // Format and calculate the next payment date based on frequency
    try {
        String dateStr = _recurlist.get(position).getRecurringStartDate();
        String frequencyStr = _recurlist.get(position).getFrequency();

        Calendar cal = Calendar.getInstance();
        cal.setTime(dateFormat.parse(dateStr));

        if (frequencyStr.equals("Daily")) {
            cal.add(Calendar.DAY_OF_MONTH, 1);
            viewHolder.txt_ddate.setText("Next Payment On: " + dateFormat.format(cal.getTimeInMillis()));
            cal.add(Calendar.DAY_OF_MONTH, -1);
        } else if (frequencyStr.equals("Weekly")) {
            cal.add(Calendar.WEEK_OF_YEAR, 1);
            viewHolder.txt_ddate.setText("Next Payment On: " + dateFormat.format(cal.getTimeInMillis()));
            cal.add(Calendar.WEEK_OF_YEAR, -1);
        } 
    } catch (ParseException e) {
        e.printStackTrace();
    }

    viewHolder.txt_dfrequency.setText(_recurlist.get(position).getFrequency().trim());

    if (_recurlist.get(position).getRecurringType().equals("W")) {
        viewHolder.txt_damount.setTextColor(Color.rgb(180, 4, 4));
        viewHolder.txt_damount.setText("Credit $ " + amount);
    } else if (_recurlist.get(position).getRecurringType().equals("D")) {
        viewHolder.txt_damount.setTextColor(Color.rgb(8, 138, 8));
        viewHolder.txt_damount.setText("Debit $ " + amount);
    }

    // Get current date
    String currentDate = "Next Payment On: " + dateFormat.format(new Date());

    // If current date matches with the next payment date, insert new
    // transaction record
    if (currentDate.equals(viewHolder.txt_ddate.getText())) {
        DatabaseAdapter mDbHelper = new DatabaseAdapter(Recurring.this);
        mDbHelper.createDatabase();
        mDbHelper.open();
        TransactionRecModel trm = new TransactionRecModel();
        CategoryController cc = new CategoryController(mDbHelper.open());

        trm.setDate(dateFormat.format(new Date()));
        if (_recurlist.get(position).getRecurringType().equals("W")) {
            trm.setType("W");
        } else if (_recurlist.get(position).getRecurringType().equals("D")) {
            trm.setType("D");
        }
        trm.setAmount(Float.parseFloat(formatAmount));

        TransactionRecController trc = new TransactionRecController(mDbHelper.open());
        if (trc.addTransactionRec(trm)) {
            // After successfully insert transaction record, update the
            // recurring start date
            rm = new RecurringModel();
            rm.setRecurringID(recurID);
            rm.setRecurringStartDate(dateFormat.format(new Date()));

            RecurringController rc = new RecurringController(mDbHelper.open());
            if (rc.updateRecurringDate(rm)) {
                mDbHelper.close();
            }
        }
    }

    return convertView;
}

从代码中,我尝试获取当前日期并与根据频率计算的下一个付款日期进行比较。但是,使用这些代码,它不会在后台运行。

假设我设置了一个重复事件,该事件将在昨天每天重复。但我今天没有运行该应用程序。正确地说,循环应该在后台运行并执行循环。但不知何故,事实并非如此。

我想知道我是否需要像 AlarmManager 这样的服务来做到这一点?

提前致谢。

编辑

所以我改变的是当我尝试比较日期时的部分,如果日期匹配,它将调用alarmManager并一路解析一些值:

if (currentDate.equals(viewHolder.txt_ddate.getText())) {
    long when = new Date().getTime();
    notificationCount = notificationCount + 1;
    AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent notificationIntent = new Intent(context, ReminderAlarm.class);
    notificationIntent.putExtra("RecurID", recurID);                
    notificationIntent.putExtra("Date", dateFormat.format(new Date()));
    notificationIntent.putExtra("Description", viewHolder.txt_ddesc.getText().toString());
    notificationIntent.putExtra("Type", _recurlist.get(position).getRecurringType());
    notificationIntent.putExtra("Amount", Float.parseFloat(formatAmount));
    notificationIntent.putExtra("CategoryID", viewHolder.txt_dcat.getText().toString());
    notificationIntent.putExtra("NotifyCount", notificationCount);
    PendingIntent pi = PendingIntent.getBroadcast(context, notificationCount, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mgr.set(AlarmManager.RTC_WAKEUP, when, pi);
}

在我的 ReminderAlarm 类中,我正在执行插入和更新 SQL 语句:

public class ReminderAlarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

    String recurID = intent.getStringExtra("RecurID");
    String date = intent.getStringExtra("Date");
    String description = intent.getStringExtra("Description");
    String type = intent.getStringExtra("Type");
    Float amount = Float.parseFloat(intent.getStringExtra("Amount"));
    String categoryID = intent.getStringExtra("CategoryID");

    DatabaseAdapter mDbHelper = new DatabaseAdapter(ReminderAlarm.this);
    mDbHelper.createDatabase();
    mDbHelper.open();
    TransactionRecModel trm = new TransactionRecModel();
    CategoryController cc = new CategoryController(mDbHelper.open());

    trm.setDate(date);
    trm.setTransDescription(description);
    if (type.equals("W")) {
        trm.setType("W");
    } else if (type.equals("D")) {
        trm.setType("D");
    }
    trm.setAmount(amount);

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

    TransactionRecController trc = new TransactionRecController(mDbHelper.open());
    if (trc.addTransactionRec(trm)) {
        // After successfully insert transaction record, update the
        // recurring start date
        RecurringModel rm = new RecurringModel();
        rm.setRecurringID(recurID);
        rm.setRecurringStartDate(date);

        RecurringController rc = new RecurringController(mDbHelper.open());
        if (rc.updateRecurringDate(rm)) {
            mDbHelper.close();
        }
    }
}

}

最佳答案

您的适配器应该接收准备显示的数据。每次 ListView 项目出现在屏幕上时都会调用 getView,因此如果您希望保持 60fps 滚动,则希望将此处的工作时间保持在 16 毫秒以下。因此,您应该在它到达适配器之前完成所有繁重的工作。

由于数据库数据通常无法显示,因此您通常会使用Loader来获取数据,并将其转换为适配器就绪的“项目”列表。这应该发生在您的 ActivityFragment 中,并且您在 onLoadFinished 中填充 Adapter。这通常意味着创建一个新的 POJO 来表示显示数据。

最好的起点是 Loader tutorial .

如果您想设置重复任务,您应该使用AlarmManager,正如您所怀疑的那样。 AlarmManager 通常会触发 BroadcastManager,后者又会生成一个 Service 来完成工作。

关注AlarmManager tutorial了解更多详情。

关于java - Android 循环任务在后台运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25934628/

相关文章:

java - JSF 2 - 未检测到@ManagedBean

java - Android MapView - 扩展 OverlayItem 以存储用于在 onTap 中访问的 URL

java - Android AlarmManager.cancel() 实际上并没有取消闹钟/PendingIntent

android - 作业调度程序 : controlling delay from constraints being met to job being run

java - 从 PHP 向 Java 发送信息

java - Ruby 获取最大整数大小值

java - Android requestLocationUpdates 方法中的位置更新

android - AlarmManager.RTC_WAKEUP 没有唤醒设备?

java - 带有 flatmap 和 takewhile 的 Spring reactor webclient 顺序请求

android - 为什么 html5 功能在我的 android 应用程序中不起作用?