2016-12-24 28 views
-1

こんにちはバックグラウンドで1秒ごとに関数を実行します。 アプリのボタンをクリックすると、カウンタが1秒ごとに+1され、別のアプリに切り替えて戻ってくると、バックグラウンドでカウントされているはずです。Android Javaはバックグラウンドで1秒ごとに関数を実行します

どうすればいいですか?

Alarmmanager? ハンドラ?

これを行う最も良い方法は何ですか。バック

答えて

0

数ヶ月... 私はこれについて研究していたと私は、ハンドラ+ wakelockを使用するよりもバッテリーの保存この

- アラームマネージャを発見しました。メソッド名にする

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を使用できます。 ScheduledExecutorServiceを試し、ミックスに別のオプションを投げるために

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

: ここthis

を参照してください、scheduleAtFixedAtFixedRate(...)関数を使用した例です。実行可能ファイルを作成し、scheduleAtFixedRate()を使用してください。私はクリスマスの間に私のデベロッパーコンピュータから離れているので、アプリがバックグラウンドで動作しているかどうかを確認することはできません。上記のリンクにはコード例があります。

関連する問題