dimanche 26 avril 2015

General regarding service class and multithreading

I am running a code, where the user selects a date and time. The user can select any date and time in the future. These dates and time are stored in sqlite database. After the user selects those dates and time, the activity calls a service class, where I am running a new thread in the following way

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

This thread access the data from the database and matches the time and date with the system time and date. One the date and time matches, I am using alarm manager with broadcast receiver like this

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

I wanted to know, Is this the correct way to do it? When I run the program in emulator, sometimes it runs fine, but other times it shows "Application doing too much work in the main thread". So, am I doing something wrong? or is there a better way to do it?

Aucun commentaire:

Enregistrer un commentaire