Android重复任务在后台运行

时间:2014-09-19 13:05:31

标签: java android alarmmanager recurring

尝试在Android中执行定期任务时出现问题。以下是我填充列表视图的方式:

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

}

1 个答案:

答案 0 :(得分:1)

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

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

最佳起点是Loader tutorial

如果您要设置定期任务,则应使用您怀疑的AlarmManagerAlarmManager通常会触发BroadcastManager,而后者会产生Service来完成工作。

关注AlarmManager tutorial了解详情。