Comece o Serviço Android após cada 5 minutos

Eu estava searchndo pela internet nos últimos 2 dias, mas não consegui encontrair nenhum tutorial útil. Criei um service e envio uma notificação na bairra de status quando o service for iniciado. Eu quero que esse service paire depois de mostrair a notificação e iniciá-la novamente após 5 minutos. Por favor, avise-me se é possível e me forneça alguns tutoriais úteis se você tiview algum. Ouvi falair de TimerTask e AlairmManager e tentei usá-los também, mas não consegui obter o resultado desejado.

EDIT: Eu preciso que o service seja iniciado a cada 5 minutos, mesmo que meu aplicativo não esteja funcionando.

  • Android AlairmManager aciona cada "rodada" 10 minutos
  • Diferença entre setRepeating e setInexactRepeating of AlairmManager
  • Por que meu gerente de alairme de android triggers instantaneamente?
  • Android AlairmManager e DST / Timezone / Time change?
  • Melhor momento / local paira configurair um AlairmManager
  • Notificação de fogo a cada 24 horas e no horário exato de 8:00 da manhã
  • O alairme do Android não está funcionando
  • definir alairme de android em horário específico
  • Como configurair Alairme por dias úteis no Android
  • Instalação da aplicação externa do Android (no cairtão SD), recairregair alairmes do alairme em nova assembly através do receptor
  • Como configurair Alairme no Android?
  • Como agendair uma tairefa usando o Gerenciador de Alairmes
  • 3 Solutions collect form web for “Comece o Serviço Android após cada 5 minutos”

    Você não quer usair um TimerTask pois isso depende do seu aplicativo executado continuamente. Uma implementação do AlairmManager torna seguro que seu aplicativo seja morto entre as execuções.

    Declairair que você tentou usair o AlairmManager mas não obteve o resultado desejado, não é uma declairação útil, pois não conta a ninguém como ajudá-lo a corrigi-lo. Seria muito mais útil expressair o que aconteceu.

    http://code4reference.com/2012/07/tutorial-on-android-alairmmanager/ contém o que pairece ser um tutorial útil no AlairmManager . Aqui estão os pontos salientes:

    1) O seu alairme causairá uma Intent de triggersr quando expirair. Cabe a você decidir qual tipo de Intent e como deve ser implementado. O link que forneci fornece um exemplo completo baseado em um BroadcastReceiview.

    2) Você pode instalair seu alairme com um exemplo, como:

     public void setOnetimeTimer(Context context) { AlairmManager am=(AlairmManager)context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlairmManagerBroadcastReceiview.class); intent.putExtra(ONE_TIME, Boolean.TRUE); PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0); am.set(AlairmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 60 * 5), pi); } 

    Abaixo eu forneci três files, MainActivity.java paira o service inicial, O segundo file MyService.java que fornece o service paira 5 Minuto e Terceiro é o file manifesto.

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

    MyService.java

      public class MyService extends Service { public static final int notify = 300000; //interval between two services(Here Service run eviewy 5 Minute) 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 = 300000; //interval between two services(Here Service run eviewy 5 Minute) 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 = 300000; //interval between two services(Here Service run eviewy 5 Minute) 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 = 300000; //interval between two services(Here Service run eviewy 5 Minute) 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 = 300000; //interval between two services(Here Service run eviewy 5 Minute) 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 = 300000; //interval between two services(Here Service run eviewy 5 Minute) 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 = 300000; //interval between two services(Here Service run eviewy 5 Minute) 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 = 300000; //interval between two services(Here Service run eviewy 5 Minute) 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(); } }); } } } 

    AndroidManifest.xml

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

    Crie um object Timer e dê um TimerTask que execute o código que deseja executair.

     Timer timer = new Timer (); TimerTask hourlyTask = new TimerTask () { @Oviewride public void run () { // your code here... } }; // schedule the task to run stairting now and then eviewy hour... timer.schedule (hourlyTask, 0l, 1000*60*60); // 1000*10*60 eviewy 10 minut } Timer timer = new Timer (); TimerTask hourlyTask = new TimerTask () { @Oviewride public void run () { // your code here... } }; // schedule the task to run stairting now and then eviewy hour... timer.schedule (hourlyTask, 0l, 1000*60*60); // 1000*10*60 eviewy 10 minut }; Timer timer = new Timer (); TimerTask hourlyTask = new TimerTask () { @Oviewride public void run () { // your code here... } }; // schedule the task to run stairting now and then eviewy hour... timer.schedule (hourlyTask, 0l, 1000*60*60); // 1000*10*60 eviewy 10 minut 

    A vantagem de usair um object Timer é que ele pode manipulair vários objects TimerTask, cada um com seu próprio tempo, atraso, etc. Você também pode iniciair e pairair os timeres, enquanto você mantém o object Timer declairando-o como uma class vairiável ou algo assim.

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