2016-12-24 91 views
-1

你好,我想在後臺每秒運行一個函數。 因此,點擊應用程序中的一個按鈕後,計數器就會去,每一秒它會得到+ 1,如果我將切換到另一個應用程序,並得到它應該仍然在後臺計數。Android Java在後臺每秒執行一次函數

我該怎麼做

Alarmmanager? 處理程序?

這樣做的最好方法是什麼。

回答

0

幾個月前.. 我研究過這個,我發現這個

- 報警管理器中節省更多的電池比使用處理器+激活鎖定。但它的時間段期間問題..

實現:

UpdateCountInSecond.java

public class UpdateCountInSecond extends Service { 
    int count=0 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO: Return the communication channel to the service. 
     throw new UnsupportedOperationException("Not yet implemented"); 
    } 

    @Override 
    public void onCreate() { 
     // TODO Auto-generated method stub 
     super.onCreate(); 
    } 

    @Override 
    public void onDestroy() { 
     // TODO Auto-generated method stub 
     super.onDestroy(); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     // TODO Auto-generated method stub 
     //your work 
     count++; 
     return super.onStartCommand(intent, flags, startId); 
    }  
} 

做出方法名稱:startServiceAlaramManager()和調用它您的主要活動或可能是您的啓動畫面

public void startServiceAlaramManager(){ 
     // Start service using AlarmManager 

     Calendar cal = Calendar.getInstance(); 
     cal.add(Calendar.SECOND, 10); 

     Intent intent = new Intent(this, UpdateCountInSecond .class); 

     PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0); 

     AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
     //1 sec =1000 miliseconds 
     alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 
       1000, pintent); 
     Toast.makeText(MainActivity.this, "alaram manager set", Toast.LENGTH_SHORT).show(); 

     startService(new Intent(this, UpdateCountInSecond .class)); 
    } 
0

您可以使用TimerTask和服務。 參考this

這裏,是使用scheduleAtFixedAtFixedRate(...)函數的一個例子:

int counter=0; 
Timer t = new Timer(); 
    t.scheduleAtFixedRate(
     new TimerTask() { 
      @Override 
      public void run() { 
       counter++; 
       //Your code here 
     }, 
     1000, //delay from start in milli seconds 
     1000 //update interval in milli seconds 
); 
0

要扔另一種選擇混進去,嘗試ScheduledExecutorService。創建一個可運行的並使用scheduleAtFixedRate()。我在聖誕節時遠離開發計算機,因此無法檢查此應用程序在後臺運行時是否仍然有效。上面的鏈接中有一個代碼示例。