【问题标题】:General regarding service class and multithreading关于服务类和多线程的一般信息
【发布时间】:2015-04-26 10:06:11
【问题描述】:

我正在运行一个代码,用户可以在其中选择日期和时间。用户可以选择未来的任何日期和时间。这些日期和时间存储在 sqlite 数据库中。用户选择这些日期和时间后,活动调用一个服务类,我在其中以以下方式运行一个新线程

public int onStartCommand(Intent intent, int flags, int startId) {
    final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    final SqliteController db = new SqliteController(getApplicationContext());

    new Thread(new Runnable() {
        @Override
        public void run() {

            List<Greetings> greetings = db.getAllGreetings();
            if (db.getGreetingsCount() >= 0) {
                do {
                    for (Greetings g : greetings) {
                        Calendar cal = Calendar.getInstance();
                      .........
                      .........//other codes

该线程从数据库中访问数据,并将时间和日期与系统时间和日期相匹配。一个日期和时间匹配,我正在使用这样的广播接收器的警报管理器

if (dnt.equals(cdt)) {
             Intent aint = new Intent(getApplicationContext(), AlarmReceiver.class);

              aint.putExtra("msg", msg);
              aint.putExtra("phone", phone);
              aint.putExtra("id", id);
  PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, aint, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
          db.deleteGreetings(g);
                        }

我想知道,这是正确的做法吗?当我在模拟器中运行程序时,有时它运行良好,但有时它显示“应用程序在主线程中做太多工作”。那么,我做错了吗?还是有更好的方法?

【问题讨论】:

    标签: android multithreading sqlite


    【解决方案1】:

    由于您发布的几乎所有代码都在后台线程中运行,因此这不会导致您的应用程序在主线程中执行过多的工作。您的问题可能来自其他来源。

    您可以尝试使用 Android 文档 here 中所述的 traceview 分析您的应用。尝试找出哪些方法最耗费时间来缩小搜索范围。

    顺便说一句,如果您的服务只是创建一个在后台运行此任务的线程,您应该使用IntentService 而不是服务。然后实现 onHandleIntent 方法而不是 onStartCommand 方法。 IntentService 将在单个后台 Looper 中处理它接收到的所有操作。

    【讨论】:

    • 谢谢,我试试traceview和intentservice方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 2014-09-16
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多