繁体   English   中英

Android定期任务在后台运行

[英]Android Recurring Task Run In Background

尝试在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类中,我正在执行insert和update 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();
        }
    }
}

}

您的Adapter应接收准备好显示的数据 每当ListView项出现在屏幕上时,都会调用getView ,因此如果希望保持60fps滚动,则希望将此处的工作保持在16ms以内。 因此, 进入适配器之前 ,您应该做所有繁重的工作。

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

最好的起点是Loader教程

如果要设置重复任务,则应使用怀疑的AlarmManager AlarmManager通常会触发BroadcastManager ,而后者又会生成Service来完成工作。

有关详细信息,请遵循AlarmManager教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM