{"id":1178,"date":"2022-03-15T01:44:41","date_gmt":"2022-03-15T01:44:41","guid":{"rendered":"https:\/\/es-andreabianchini.it\/andrewsblog\/?p=1178"},"modified":"2022-03-15T01:51:32","modified_gmt":"2022-03-15T01:51:32","slug":"servizi-in-android","status":"publish","type":"post","link":"https:\/\/es-andreabianchini.it\/andrewsblog\/?p=1178","title":{"rendered":"Servizi in Android"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">&#8220;<strong>Le basi<\/strong><br>Per creare un servizio, devi creare una sottoclasse di Service o utilizzare una delle sue sottoclassi esistenti. Nella tua implementazione, devi sovrascrivere alcuni metodi di callback che gestiscono aspetti chiave del ciclo di vita del servizio e fornire un meccanismo che consenta ai componenti di associarsi al servizio, se appropriato. Questi sono i metodi di callback pi\u00f9 importanti che dovresti sovrascrivere:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">onStartCommand()<br>Il sistema richiama questo metodo chiamando startService() quando un altro componente (come un&#8217;attivit\u00e0) richiede l&#8217;avvio del servizio. Quando questo metodo viene eseguito, il servizio viene avviato e pu\u00f2 essere eseguito in background a tempo indeterminato. Se lo implementi, \u00e8 tua responsabilit\u00e0 interrompere il servizio quando il suo lavoro \u00e8 completo chiamando stopSelf() o stopService(). Se si desidera fornire solo l&#8217;associazione, non \u00e8 necessario implementare questo metodo.<br><br>onBind()<br>Il sistema richiama questo metodo chiamando bindService() quando un altro componente desidera eseguire il binding con il servizio (ad esempio per eseguire RPC). Nell&#8217;implementazione di questo metodo, devi fornire un&#8217;interfaccia che i client utilizzano per comunicare con il servizio restituendo un IBinder. Devi sempre implementare questo metodo; tuttavia, se non si desidera consentire l&#8217;associazione, \u00e8 necessario restituire null.<br><br>onCreate()<br>Il sistema richiama questo metodo per eseguire procedure di installazione una tantum quando il servizio viene creato inizialmente (prima di chiamare onStartCommand() o onBind()). Se il servizio \u00e8 gi\u00e0 in esecuzione, questo metodo non viene chiamato.<br><br>onDestroy()<br>Il sistema richiama questo metodo quando il servizio non viene pi\u00f9 utilizzato e viene distrutto. Il tuo servizio dovrebbe implementarlo per ripulire tutte le risorse come thread, listener registrati o ricevitori. Questa \u00e8 l&#8217;ultima chiamata ricevuta dal servizio.&#8221;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Esempio di servizio in Android :<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class HelloService extends Service {\n  private Looper serviceLooper;\n  private ServiceHandler serviceHandler;\n\n  \/\/ Handler that receives messages from the thread\n  private final class ServiceHandler extends Handler {\n      public ServiceHandler(Looper looper) {\n          super(looper);\n      }\n      @Override\n      public void handleMessage(Message msg) {\n          \/\/ Normally we would do some work here, like download a file.\n          \/\/ For our sample, we just sleep for 5 seconds.\n          try {\n              Thread.sleep(5000);\n          } catch (InterruptedException e) {\n              \/\/ Restore interrupt status.\n              Thread.currentThread().interrupt();\n          }\n          \/\/ Stop the service using the startId, so that we don't stop\n          \/\/ the service in the middle of handling another job\n          stopSelf(msg.arg1);\n      }\n  }\n\n  @Override\n  public void onCreate() {\n    \/\/ Start up the thread running the service. Note that we create a\n    \/\/ separate thread because the service normally runs in the process's\n    \/\/ main thread, which we don't want to block. We also make it\n    \/\/ background priority so CPU-intensive work doesn't disrupt our UI.\n    HandlerThread thread = new HandlerThread(\"ServiceStartArguments\",\n            Process.THREAD_PRIORITY_BACKGROUND);\n    thread.start();\n\n    \/\/ Get the HandlerThread's Looper and use it for our Handler\n    serviceLooper = thread.getLooper();\n    serviceHandler = new ServiceHandler(serviceLooper);\n  }\n\n  @Override\n  public int onStartCommand(Intent intent, int flags, int startId) {\n      Toast.makeText(this, \"service starting\", Toast.LENGTH_SHORT).show();\n\n      \/\/ For each start request, send a message to start a job and deliver the\n      \/\/ start ID so we know which request we're stopping when we finish the job\n      Message msg = serviceHandler.obtainMessage();\n      msg.arg1 = startId;\n      serviceHandler.sendMessage(msg);\n\n      \/\/ If we get killed, after returning from here, restart\n      return START_STICKY;\n  }\n\n  @Override\n  public IBinder onBind(Intent intent) {\n      \/\/ We don't provide binding, so return null\n      return null;\n  }\n\n  @Override\n  public void onDestroy() {\n    Toast.makeText(this, \"service done\", Toast.LENGTH_SHORT).show();\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Articolo completo :<br><a href=\"https:\/\/developer.android.com\/guide\/components\/services#java\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/developer.android.com\/guide\/components\/services#java<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;Le basiPer creare un servizio, devi creare una sottoclasse di Service o utilizzare una delle sue sottoclassi esistenti. Nella tua implementazione, devi sovrascrivere alcuni metodi di callback che gestiscono aspetti chiave del ciclo di vita del servizio e fornire un meccanismo che consenta ai componenti di associarsi al servizio, se appropriato. Questi sono i metodi &hellip; <a href=\"https:\/\/es-andreabianchini.it\/andrewsblog\/?p=1178\" class=\"more-link\">Leggi tutto<span class=\"screen-reader-text\"> &#8220;Servizi in Android&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[15,7],"tags":[],"class_list":["post-1178","post","type-post","status-publish","format-standard","hentry","category-android","category-stem"],"_links":{"self":[{"href":"https:\/\/es-andreabianchini.it\/andrewsblog\/index.php?rest_route=\/wp\/v2\/posts\/1178","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/es-andreabianchini.it\/andrewsblog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/es-andreabianchini.it\/andrewsblog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/es-andreabianchini.it\/andrewsblog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/es-andreabianchini.it\/andrewsblog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1178"}],"version-history":[{"count":2,"href":"https:\/\/es-andreabianchini.it\/andrewsblog\/index.php?rest_route=\/wp\/v2\/posts\/1178\/revisions"}],"predecessor-version":[{"id":1180,"href":"https:\/\/es-andreabianchini.it\/andrewsblog\/index.php?rest_route=\/wp\/v2\/posts\/1178\/revisions\/1180"}],"wp:attachment":[{"href":"https:\/\/es-andreabianchini.it\/andrewsblog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1178"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/es-andreabianchini.it\/andrewsblog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1178"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/es-andreabianchini.it\/andrewsblog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1178"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}