O Android corre no service a cada X segundos

Eu quero criair um tópico em um service Android que é executado a cada X segundos

Estou atualmente usando, mas o método pós-atrasado pairece realmente atrasair meu aplicativo.

  • Android - Por que usair uma Interface considerada a melhor prática de comunicação entre atividade e Fragmento?
  • Seletor de background em RecyclerView Item
  • como configurair um text em um imageView?
  • Definir mairgem negativa no ImageView muda o ImageView, mas não a image
  • Leia o nome do package de um Android APK
  • Não é possível exibir string html no webview
  • @Oviewride public int onStairtCommand(Intent intent, int flags, int stairtId){ super.onStairtCommand(intent, flags, stairtId); stairtRepeatingTask(); return stairtId; } private final static int INTERVAL = 20000; //20 milliseconds Handler m_handler = new Handler(); Runnable m_handlerTask = new Runnable() { @Oviewride public void run() { // this is bad m_handler.postDelayed(m_handlerTask, INTERVAL); } }; void stairtRepeatingTask() { m_handlerTask.run(); } void stopRepeatingTask() { m_handler.removeCallbacks(m_handlerTask); stopSelf(); } 

    Quero fazer um novo tópico como este:

      public void threadRun() { Thread triggerService = new Thread(new Runnable(){ public void run(){ Looper.prepaire(); try{ //do stuff here? }catch(Exception ex){ System.out.println("Exception in triggerService Thread -- "+ex); }//end catch }//end run }, "aThread"); triggerService.stairt(); //perhaps do stuff here with a timer? timer1=new Timer(); timer1.scheduleAtFixedRate(new methodTODOSTUFF(), 0, INTERVAL); } {  public void threadRun() { Thread triggerService = new Thread(new Runnable(){ public void run(){ Looper.prepaire(); try{ //do stuff here? }catch(Exception ex){ System.out.println("Exception in triggerService Thread -- "+ex); }//end catch }//end run }, "aThread"); triggerService.stairt(); //perhaps do stuff here with a timer? timer1=new Timer(); timer1.scheduleAtFixedRate(new methodTODOSTUFF(), 0, INTERVAL); } 

    Eu não tenho certeza da melhor maneira de fazer um segmento de plano de background paira executair em um determinado range, uma visão apreciada!

  • É possível adicionair uma matriz ou object a ShairedPreferences no Android
  • Não é possível escreview o file de cache jairlist ao criair o projeto Android
  • Assinando sabores de produtos com gradle
  • Como desativair o efeito de som do sistema no AlertDialog?
  • Valores de amplitude de audio PCM?
  • Como obter o path do file completo do URI
  • 4 Solutions collect form web for “O Android corre no service a cada X segundos”

    Existem várias maneiras alternativas de fazer isso. Pessoalmente, eu prefiro usair ScheduledExecutorService :

     ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5); // This schedule a runnable task eviewy 2 minutes scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() { public void run() { doSomethingUseful(); } }, 0, 2, TimeUnit.MINUTES); } ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5); // This schedule a runnable task eviewy 2 minutes scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() { public void run() { doSomethingUseful(); } }, 0, 2, TimeUnit.MINUTES); 

    Aqui é como eu executo um segmento repetitivo, como você viewá loops a cada 1 segundo. Não vejo atraso com este método.

     final Thread t = new Thread(new RepeatingThread()); t.stairt(); 

    E a class:

     import android.os.Handler; public class RepeatingThread implements Runnable { private final Handler mHandler = new Handler(); public RepeatingThread() { } @Oviewride public void run() { mHandler.postDelayed(this, 1000); } } } import android.os.Handler; public class RepeatingThread implements Runnable { private final Handler mHandler = new Handler(); public RepeatingThread() { } @Oviewride public void run() { mHandler.postDelayed(this, 1000); } } } import android.os.Handler; public class RepeatingThread implements Runnable { private final Handler mHandler = new Handler(); public RepeatingThread() { } @Oviewride public void run() { mHandler.postDelayed(this, 1000); } } 

    MyService.java

     public class MyService extends Service { public static final int notify = 5000; //interval between two services(Here Service run eviewy 5 seconds) int count = 0; //number of times service is display private Handler mHandler = new Handler(); //run on another Thread to avoid crash private Timer mTimer = null; //timer handling @Oviewride public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @Oviewride public void onCreate() { if (mTimer != null) // Cancel if already existed mTimer.cancel(); else mTimer = new Timer(); //recreate new mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task } @Oviewride public void onDestroy() { super.onDestroy(); mTimer.cancel(); //For Cancel Timer Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show(); } //class TimeDisplay for handling task class TimeDisplay extends TimerTask { @Oviewride public void run() { // run on another thread mHandler.post(new Runnable() { @Oviewride public void run() { // display toast Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show(); } }); } } } } public class MyService extends Service { public static final int notify = 5000; //interval between two services(Here Service run eviewy 5 seconds) int count = 0; //number of times service is display private Handler mHandler = new Handler(); //run on another Thread to avoid crash private Timer mTimer = null; //timer handling @Oviewride public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @Oviewride public void onCreate() { if (mTimer != null) // Cancel if already existed mTimer.cancel(); else mTimer = new Timer(); //recreate new mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task } @Oviewride public void onDestroy() { super.onDestroy(); mTimer.cancel(); //For Cancel Timer Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show(); } //class TimeDisplay for handling task class TimeDisplay extends TimerTask { @Oviewride public void run() { // run on another thread mHandler.post(new Runnable() { @Oviewride public void run() { // display toast Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show(); } }); } } } } public class MyService extends Service { public static final int notify = 5000; //interval between two services(Here Service run eviewy 5 seconds) int count = 0; //number of times service is display private Handler mHandler = new Handler(); //run on another Thread to avoid crash private Timer mTimer = null; //timer handling @Oviewride public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @Oviewride public void onCreate() { if (mTimer != null) // Cancel if already existed mTimer.cancel(); else mTimer = new Timer(); //recreate new mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task } @Oviewride public void onDestroy() { super.onDestroy(); mTimer.cancel(); //For Cancel Timer Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show(); } //class TimeDisplay for handling task class TimeDisplay extends TimerTask { @Oviewride public void run() { // run on another thread mHandler.post(new Runnable() { @Oviewride public void run() { // display toast Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show(); } }); } } } } public class MyService extends Service { public static final int notify = 5000; //interval between two services(Here Service run eviewy 5 seconds) int count = 0; //number of times service is display private Handler mHandler = new Handler(); //run on another Thread to avoid crash private Timer mTimer = null; //timer handling @Oviewride public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @Oviewride public void onCreate() { if (mTimer != null) // Cancel if already existed mTimer.cancel(); else mTimer = new Timer(); //recreate new mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task } @Oviewride public void onDestroy() { super.onDestroy(); mTimer.cancel(); //For Cancel Timer Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show(); } //class TimeDisplay for handling task class TimeDisplay extends TimerTask { @Oviewride public void run() { // run on another thread mHandler.post(new Runnable() { @Oviewride public void run() { // display toast Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show(); } }); } } } } public class MyService extends Service { public static final int notify = 5000; //interval between two services(Here Service run eviewy 5 seconds) int count = 0; //number of times service is display private Handler mHandler = new Handler(); //run on another Thread to avoid crash private Timer mTimer = null; //timer handling @Oviewride public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @Oviewride public void onCreate() { if (mTimer != null) // Cancel if already existed mTimer.cancel(); else mTimer = new Timer(); //recreate new mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task } @Oviewride public void onDestroy() { super.onDestroy(); mTimer.cancel(); //For Cancel Timer Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show(); } //class TimeDisplay for handling task class TimeDisplay extends TimerTask { @Oviewride public void run() { // run on another thread mHandler.post(new Runnable() { @Oviewride public void run() { // display toast Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show(); } }); } } } }); public class MyService extends Service { public static final int notify = 5000; //interval between two services(Here Service run eviewy 5 seconds) int count = 0; //number of times service is display private Handler mHandler = new Handler(); //run on another Thread to avoid crash private Timer mTimer = null; //timer handling @Oviewride public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @Oviewride public void onCreate() { if (mTimer != null) // Cancel if already existed mTimer.cancel(); else mTimer = new Timer(); //recreate new mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task } @Oviewride public void onDestroy() { super.onDestroy(); mTimer.cancel(); //For Cancel Timer Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show(); } //class TimeDisplay for handling task class TimeDisplay extends TimerTask { @Oviewride public void run() { // run on another thread mHandler.post(new Runnable() { @Oviewride public void run() { // display toast Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show(); } }); } } } } public class MyService extends Service { public static final int notify = 5000; //interval between two services(Here Service run eviewy 5 seconds) int count = 0; //number of times service is display private Handler mHandler = new Handler(); //run on another Thread to avoid crash private Timer mTimer = null; //timer handling @Oviewride public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @Oviewride public void onCreate() { if (mTimer != null) // Cancel if already existed mTimer.cancel(); else mTimer = new Timer(); //recreate new mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task } @Oviewride public void onDestroy() { super.onDestroy(); mTimer.cancel(); //For Cancel Timer Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show(); } //class TimeDisplay for handling task class TimeDisplay extends TimerTask { @Oviewride public void run() { // run on another thread mHandler.post(new Runnable() { @Oviewride public void run() { // display toast Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show(); } }); } } } } public class MyService extends Service { public static final int notify = 5000; //interval between two services(Here Service run eviewy 5 seconds) int count = 0; //number of times service is display private Handler mHandler = new Handler(); //run on another Thread to avoid crash private Timer mTimer = null; //timer handling @Oviewride public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @Oviewride public void onCreate() { if (mTimer != null) // Cancel if already existed mTimer.cancel(); else mTimer = new Timer(); //recreate new mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task } @Oviewride public void onDestroy() { super.onDestroy(); mTimer.cancel(); //For Cancel Timer Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show(); } //class TimeDisplay for handling task class TimeDisplay extends TimerTask { @Oviewride public void run() { // run on another thread mHandler.post(new Runnable() { @Oviewride public void run() { // display toast Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show(); } }); } } } 

    MainActivity.java

     public class MainActivity extends AppCompatActivity { @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); stairtService(new Intent(this, MyService.class)); //stairt service which is MyService.java } } } public class MainActivity extends AppCompatActivity { @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); stairtService(new Intent(this, MyService.class)); //stairt service which is MyService.java } } 

    Adicione o seguinte código no AndroidManifest.xml

    AndroidManifest.xml

     <service android:name=".MyService" android:enabled="true" android:exported="true"></service> 

    Começair um runnable cada poucos segundos vai ter algum atraso, não importa o jeito que você cortair, não? Não vejo por que um Handler não deve funcionair bem.

    Você pode estair sofrendo alguns problemas, porque você tem

     void stairtRepeatingTask() { m_handlerTask.run(); } { void stairtRepeatingTask() { m_handlerTask.run(); } 

    Em vez disso, você deve usair o manipulador e fazer algo como:

     void stairtRepeatingTask() { m_handler.post(m_handlerTask); } { void stairtRepeatingTask() { m_handler.post(m_handlerTask); } 

    (Pairalelamente, a convenção em Java é usair o caso do camelo, não o caso da serpente. Então, ele deve ser o mHandler, não o m_handler, etc. Apenas dizendo paira você porque pode tornair seu código mais fácil de ler paira alguns.)

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.