如何在android的后台自动调用每小时的方法?

时间:2015-03-23 10:04:34

标签: android service background-process

我创建了一个带有Service的Android项目,它运行正常,但是如果应用程序运行或不运行,我会自动创建一些更新,就像每小时一个方法调用一样。  我把服务类和服务的代码从mainActivity类开始。

public class LocationService extends Service  {//uses Main thread not create in another thread.
int mTime ;
@Override
public void onCreate() {
    super.onCreate();
    Toast.makeText(getApplicationContext(),"Create Service",Toast.LENGTH_LONG).show();
    mTime = 1;
}

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    Log.d("Service","onStartCommand") ;
    //Toast.makeText(getApplicationContext(),"Start Service",Toast.LENGTH_LONG).show();


}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
   /* Intent mIntent = intent ;
    String msg = mIntent.getStringExtra("msg")*/
   // Toast.makeText(getApplicationContext(),"onStart Command Service",Toast.LENGTH_LONG).show();
     //Toast.makeText(getApplicationContext(),"Message is = "+intent.getStringExtra("message"),Toast.LENGTH_LONG).show();
    Calendar cal = Calendar.getInstance();
    Intent mIntent = new Intent(this, LocationService.class);
    PendingIntent pintent = PendingIntent
            .getService(this, 0, intent, 0);

    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    // Start service every hour
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            600 * 1000, pintent);//1000*60 = minute
    Date date = new Date();
    mTime++;
    if(mTime >=25000)
        mTime = 1 ;
    String mDate = date.toString() ;
    DeptTable mDeptTable = new DeptTable(mTime,
            mDate);

    new AsyncDept().execute(mDeptTable);

    Log.e("Service","onStartCommand") ;

    return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();
    Toast.makeText(getApplicationContext(),"Destroy Service",Toast.LENGTH_LONG).show();

}

protected class AsyncDept extends
        AsyncTask<DeptTable, Void, Void>
{

    @Override
    protected Void doInBackground(DeptTable... params) {
        RestAPI api = new RestAPI();
        try {

            api.AddDepartmentDetails(""+params[0].getNo(),
                    params[0].getName());

        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.d("AsyncCreateUser", e.getMessage());

        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

    }

}

}

在上面的代码方法调用但不切实际的时间所以任何解决方案请事先告诉我。

2 个答案:

答案 0 :(得分:0)

更改

 alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            600 * 1000, pintent);//1000*60 = minute 

to

 alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            60 * 60 * 1000, pintent);//This makes hour

答案 1 :(得分:0)

您可以使用基于线程的类:

public class OBSynkSchedule extends Thread {

  private static OBSynkSchedule instance = null;
  private int sleepTime = -1;
  private boolean keepRunning = false;

  private OBSynkSchedule() {
  }

  public static OBSynkSchedule get() {
    if (instance == null) {
      instance = new OBSynkSchedule();
    }
    return instance;
  }

  public static void startManager() {
      OBSynkSchedule mng = get();
      mng.keepRunning = true;
      mng.start();
  }

  public static void stopManager() {
      OBSynkSchedule mng = get();
      mng.keepRunning = false;
      mng.interrupt();
  }

  public void run() {

     sleepTime = Config.getSleepTime();
     if (sleepTime == -1) {
        // default sleep time 2 hours
        sleepTime = 120;
     }
     // in minutes -> sleepTime x (60000 milisec)
     sleepTime = sleepTime * 60000;
     int i = 1;
     while (keepRunning) {
         try {
              try {
                get().DoIt();
              } catch (Exception e) {
          }
          sleep(sleepTime);
      } catch (Exception e) {
          //Log.error("FeedBackSchedule", this, "run", "Failed to check events: ", e); 
      }
  }
 }

  private void DoIt() {
      try{
         OBDBSynk.synchronize();
      }catch(Exception e) {
      //Log.error("removeInactiveDevices", this, "removeInactiveDevices", "An error occorred when getting devices list: ", e); 
      }
  }

}