CERCA
PER MODELLO
FullScreen Chatbox! :)

Utente del giorno: complicazio con ben 2 Thanks ricevuti nelle ultime 24 ore
Utente della settimana: 9mm con ben 10 Thanks ricevuti negli ultimi sette giorni
Utente del mese: 9mm con ben 34 Thanks ricevuti nell'ultimo mese

Visualizzazione dei risultati da 1 a 7 su 7
Discussione:

Activity e Service in processi separati

Se questa discussione ti è stata utile, ti preghiamo di lasciare un messaggio di feedback in modo che possa essere preziosa in futuro anche per altri utenti come te!
  1. #1
    Androidiano


    Registrato dal
    Jan 2010
    Messaggi
    138

    Ringraziamenti
    5
    Ringraziato 2 volte in 2 Posts
    Predefinito

    Activity e Service in processi separati

    Non so se qualcuno ha già chiesto una cosa del genere ma non sono riuscito a trovarne traccia, comunque :

    Sto realizzando un app formata da un'activity, un servizio e un broadcastreceiver.

    il servizio è istanziato dinamicamente dall'activity e il receiver è istanziato dinamicamente dal servizio.

    Avrei necessita di separare i processi di activity e servizio per fare in modo che killando l'activity (manualmente o ad opera del sistema) il servizio rimanga in esecuzione.

    Ho provato a inserire il return sticky in startcommand e messo nel manifest android:process diversi per activity e service(uguale per il receiver).

    Ma in ogni caso da osmonitor o da top in betterterminal vedo un unico processo per la mia app..

    Dove sbaglio

    PS : è normale che mi faccia mettere @string prima del nome del processo nella doc ho letto che è importante anche il primo carattere del nome del processo

    Grazie come sempre...

  2.  
  3. #2
    Senior Droid L'avatar di Azatoth


    Registrato dal
    Apr 2009
    Località
    Misinto (MI)
    Messaggi
    568

    Ringraziamenti
    1
    Ringraziato 38 volte in 28 Posts
    Predefinito

    Quote Originariamente inviato da serkejal Visualizza il messaggio
    Non so se qualcuno ha già chiesto una cosa del genere ma non sono riuscito a trovarne traccia, comunque :

    Sto realizzando un app formata da un'activity, un servizio e un broadcastreceiver.

    il servizio è istanziato dinamicamente dall'activity e il receiver è istanziato dinamicamente dal servizio.

    Avrei necessita di separare i processi di activity e servizio per fare in modo che killando l'activity (manualmente o ad opera del sistema) il servizio rimanga in esecuzione.

    Ho provato a inserire il return sticky in startcommand e messo nel manifest androidrocess diversi per activity e service(uguale per il receiver).

    Ma in ogni caso da osmonitor o da top in betterterminal vedo un unico processo per la mia app..

    Dove sbaglio

    PS : è normale che mi faccia mettere @string prima del nome del processo nella doc ho letto che è importante anche il primo carattere del nome del processo

    Grazie come sempre...
    secondo me hai le idee un po' confuse...

    il broadcast receiver serve per ricevere un 'segnale' (chiamamolo pure evento) esterno. Grazie al fatto che l'applicazione è registrata su quel determinato 'segnale' (perchè è esplicitato nel manifest dell'applicazione), appena arriva quel segnale, Android attiva il broadcast receiver e questo a sua volta fa quello che vuole: per esempio fa uno startService(...) se deve far partire un servizio per esempio al boot (quindi sarà in ascolto sull'evento android.permission.RECEIVE_BOOT_COMPLETED).

    Ora il servizio è attivo e ci starà finchè le risorse lo permettono, quindi devi scriverlo rispettando tutti i crismi del ciclo di vita dei servizi.

    Fatto questo in modo che il servizio risponde a tutte le esigenze necessarie, è il caso di gestire l'interfaccia con l'utente: quindi ti creerai la tua activity come preferisci.

    Tutto questo in linea teorica. Tutto dipende da cosa deve fare la tua applicazione.


    Google Nexus One USA
    ROM: CyanogenMod 6.1.1 - Android 2.2.1
    Radio: 5.12.00.08
    Recovery: Clockwork

    Sviluppatore di: Swapper per utenti root | Modus Operandi

    Ecco le mie app Android

  4. #3
    Androidiano


    Registrato dal
    Jan 2010
    Messaggi
    138

    Ringraziamenti
    5
    Ringraziato 2 volte in 2 Posts
    Predefinito

    Non credo di avere le idee un confuse anzi...
    Non pongo il problema perchè ho problemi di implementazione, l'applicazione funziona e anche bene ( tra un po' la metto nel market ) il punto è che ,ad esempio, per chi come me usa app come task killer conviene avere due processi separati uno per le activity e un altro per i servizi in modo da poter killare a piacimento il primo e mettere negli ignorati il secondo. (esempi sono i player musicali)

    Nel mio caso quindi avrei bisogno di dividere i processi tenendo separati activity da servizio e broadcast recivier.

    Secondo io non dichiaro intent-filter nel manifest perchè cosi il servizio partirebbe appena viene ricevuto quell'intent da gestire, ma a me deve essere l'utente a decidere quando far partire il servizio e quando stopparlo non un "segnale particolare" di conseguenza faccio un semplice startService() al click di un bottone.
    Stessa cosa per il broadcast receiver, non deve essere attivo sempre ma solo quando è attivo il servizio quindi anche lui è attivato dinamicamente dal servizio, pronto a ricevere, e non dal manifest.

    Spero di essere stato chiaro...
    Cmq ripeto l'app funge e anche bene,e le entità sono ben gestite, non credo di essere confuso quello che non riesco a fare è separare i processi, se dici che lo sono almeno spiegami meglio perchè quello che hai scritto non si applica al mio caso!
    In ogni caso grazie della riposta lo credevo un post morto

  5. #4
    Senior Droid L'avatar di Azatoth


    Registrato dal
    Apr 2009
    Località
    Misinto (MI)
    Messaggi
    568

    Ringraziamenti
    1
    Ringraziato 38 volte in 28 Posts
    Predefinito

    Quote Originariamente inviato da serkejal Visualizza il messaggio
    Non credo di avere le idee un confuse anzi...
    Non pongo il problema perchè ho problemi di implementazione, l'applicazione funziona e anche bene ( tra un po' la metto nel market ) il punto è che ,ad esempio, per chi come me usa app come task killer conviene avere due processi separati uno per le activity e un altro per i servizi in modo da poter killare a piacimento il primo e mettere negli ignorati il secondo. (esempi sono i player musicali)

    Nel mio caso quindi avrei bisogno di dividere i processi tenendo separati activity da servizio e broadcast recivier.

    Secondo io non dichiaro intent-filter nel manifest perchè cosi il servizio partirebbe appena viene ricevuto quell'intent da gestire, ma a me deve essere l'utente a decidere quando far partire il servizio e quando stopparlo non un "segnale particolare" di conseguenza faccio un semplice startService() al click di un bottone.
    Stessa cosa per il broadcast receiver, non deve essere attivo sempre ma solo quando è attivo il servizio quindi anche lui è attivato dinamicamente dal servizio, pronto a ricevere, e non dal manifest.

    Spero di essere stato chiaro...
    Cmq ripeto l'app funge e anche bene,e le entità sono ben gestite, non credo di essere confuso quello che non riesco a fare è separare i processi, se dici che lo sono almeno spiegami meglio perchè quello che hai scritto non si applica al mio caso!
    In ogni caso grazie della riposta lo credevo un post morto
    ok, ora è più chiara l'esigenza.
    Infatti come ti ho scritto, inizialmente ho detto 'secondo me hai le idee confuse', poi ho ribadito che 'Tutto dipende da cosa deve fare la tua applicazione'.
    Non è legge quello che ho scritto, anzi, si applica ad applicazioni tipicamente 'background': la tua è un'applicazione 'mista' quindi direi che ci sta.

    Comunque sei in una botte di ferro perchè ogni classe Activity o Service sta a sè stante.

    cito dalla documentazione
    Android applications don't have a single entry point for everything in the application (no main() function, for example). Rather, they have essential components that the system can instantiate and run as needed
    Altra citazione sui Processi e cicli di vita:
    The Android system tries to maintain an application process for as long as possible, but eventually it will need to remove old processes when memory runs low. To determine which processes to keep and which to kill, Android places each process into an "importance hierarchy" based on the components running in it and the state of those components. Processes with the lowest importance are eliminated first, then those with the next lowest, and so on. There are five levels in the hierarchy. The following list presents them in order of importance:

    A foreground process is one that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions hold:
    It is running an activity that the user is interacting with (the Activity object's onResume() method has been called).
    It hosts a service that's bound to the activity that the user is interacting with.
    It has a Service object that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()).
    It has a BroadcastReceiver object that's executing its onReceive() method.
    Only a few foreground processes will exist at any given time. They are killed only as a last resort — if memory is so low that they cannot all continue to run. Generally, at that point, the device has reached a memory paging state, so killing some foreground processes is required to keep the user interface responsive.
    A visible process is one that doesn't have any foreground components, but still can affect what the user sees on screen. A process is considered to be visible if either of the following conditions holds:
    It hosts an activity that is not in the foreground, but is still visible to the user (its onPause() method has been called). This may occur, for example, if the foreground activity is a dialog that allows the previous activity to be seen behind it.
    It hosts a service that's bound to a visible activity.
    A visible process is considered extremely important and will not be killed unless doing so is required to keep all foreground processes running.
    A service process is one that is running a service that has been started with the startService() method and that does not fall into either of the two higher categories. Although service processes are not directly tied to anything the user sees, they are generally doing things that the user cares about (such as playing an mp3 in the background or downloading data on the network), so the system keeps them running unless there's not enough memory to retain them along with all foreground and visible processes.
    A background process is one holding an activity that's not currently visible to the user (the Activity object's onStop() method has been called). These processes have no direct impact on the user experience, and can be killed at any time to reclaim memory for a foreground, visible, or service process. Usually there are many background processes running, so they are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by the user is the last to be killed. If an activity implements its lifecycle methods correctly, and captures its current state, killing its process will not have a deleterious effect on the user experience.
    An empty process is one that doesn't hold any active application components. The only reason to keep such a process around is as a cache to improve startup time the next time a component needs to run in it. The system often kills these processes in order to balance overall system resources between process caches and the underlying kernel caches.
    Android ranks a process at the highest level it can, based upon the importance of the components currently active in the process. For example, if a process hosts a service and a visible activity, the process will be ranked as a visible process, not a service process.

    In addition, a process's ranking may be increased because other processes are dependent on it. A process that is serving another process can never be ranked lower than the process it is serving. For example, if a content provider in process A is serving a client in process B, or if a service in process A is bound to a component in process B, process A will always be considered at least as important as process B.

    Because a process running a service is ranked higher than one with background activities, an activity that initiates a long-running operation might do well to start a service for that operation, rather than simply spawn a thread — particularly if the operation will likely outlast the activity. Examples of this are playing music in the background and uploading a picture taken by the camera to a web site. Using a service guarantees that the operation will have at least "service process" priority, regardless of what happens to the activity. As noted in the Broadcast receiver lifecycle section earlier, this is the same reason that broadcast receivers should employ services rather than simply put time-consuming operations in a thread.
    A fronte di questo, diciamo che se nessuno ti ammazza l'applicazione android lavora bene.

    Qui casca l'asino mi pare di capire: infatti la tua richiesta è: come faccio a fare un'applicazione che, se killata da un qualsiasi task-killer, non mi uccida 'tutto' ma solo l'activity?

    In teoria è tutto sullo stesso processo.

    When the first of an application's components needs to be run, Android starts a Linux process for it with a single thread of execution. By default, all components of the application run in that process and thread.
    ma è anche vero che:

    However, you can arrange for components to run in other processes, and you can spawn additional threads for any process.
    to be continued...


    Google Nexus One USA
    ROM: CyanogenMod 6.1.1 - Android 2.2.1
    Radio: 5.12.00.08
    Recovery: Clockwork

    Sviluppatore di: Swapper per utenti root | Modus Operandi

    Ecco le mie app Android

  6. #5
    Senior Droid L'avatar di Azatoth


    Registrato dal
    Apr 2009
    Località
    Misinto (MI)
    Messaggi
    568

    Ringraziamenti
    1
    Ringraziato 38 volte in 28 Posts
    Predefinito

    infatti:

    Processes
    The process where a component runs is controlled by the manifest file. The component elements — <activity>, <service>, <receiver>, and <provider> — each have a process attribute that can specify a process where that component should run. These attributes can be set so that each component runs in its own process, or so that some components share a process while others do not. They can also be set so that components of different applications run in the same process — provided that the applications share the same Linux user ID and are signed by the same authorities. The <application> element also has a process attribute, for setting a default value that applies to all components.

    All components are instantiated in the main thread of the specified process, and system calls to the component are dispatched from that thread. Separate threads are not created for each instance. Consequently, methods that respond to those calls — methods like View.onKeyDown() that report user actions and the lifecycle notifications discussed later in the Component Lifecycles section — always run in the main thread of the process. This means that no component should perform long or blocking operations (such as networking operations or computation loops) when called by the system, since this will block any other components also in the process. You can spawn separate threads for long operations, as discussed under Threads, next.

    Android may decide to shut down a process at some point, when memory is low and required by other processes that are more immediately serving the user. Application components running in the process are consequently destroyed. A process is restarted for those components when there's again work for them to do.

    When deciding which processes to terminate, Android weighs their relative importance to the user. For example, it more readily shuts down a process with activities that are no longer visible on screen than a process with visible activities. The decision whether to terminate a process, therefore, depends on the state of the components running in that process. Those states are the subject of a later section, Component Lifecycles.
    Secondo me, specificando nel manifest che servizio, activity e receiver hanno un processo per ogni componente, sei a posto.
    l'unico problema sarà la comunicazione dei processi se hai il bind tra service e activity, alla stessa stregua dei classici problemi di cross threading.

    Spero di averti aiutato
    Ultima modifica di Azatoth; 19-03-10 alle 12:28


    Google Nexus One USA
    ROM: CyanogenMod 6.1.1 - Android 2.2.1
    Radio: 5.12.00.08
    Recovery: Clockwork

    Sviluppatore di: Swapper per utenti root | Modus Operandi

    Ecco le mie app Android

  7. #6
    Androidiano


    Registrato dal
    Jan 2010
    Messaggi
    138

    Ringraziamenti
    5
    Ringraziato 2 volte in 2 Posts
    Predefinito

    beh che dire sei stato infinitamente più chiaro di me su cosa sto facendo e la teoria per farlo :D:D:D
    pero purtroppo ritorniamo alla pratica e visto che facciamo citazioni cito anche io :

    android:process
    The name of the process where the service is to run. Normally, all components of an application run in the default process created for the application. It has the same name as the application package. The <application> element's process attribute can set a different default for all components. But component can override the default with its own process attribute, allowing you to spread your application across multiple processes.

    If the name assigned to this attribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the service runs in that process. If the process name begins with a lowercase character, the service will run in a global process of that name, provided that it has permission to do so. This allows components in different applications to share a process, reducing resource usage.
    Seguendo quanto scritto in documentazione aggiungo nel manifest alle voci application e activity un android:process e per service e receveir un altro.
    però non funge!!
    quello che scrivo e del tipo android:process="@string/main_process" e android:process="@string/service_process". A meno che non riesco a capire quanto citato sopra (cosa anche possibile) dovrebbero crearsi due global process con quei nomi.....
    Una cosa che ho notato, facendo sempre riferimento ai player musicali e che loro usano i ":" per i processi separati dal principale forse dovrei provare così anche se mi pare di aver capito, sempre da quanto citato, che mettere ":" all'inizio serve solo ad identificare se il process e privato o globale.
    che ne pensi??
    forse il problema è quando dice "provided that it has permission to do so" cioè che deve avere il permesso per farlo, però quanto meno dovrebbe lanciarmi una Security Exception no non farlo e basta...... ah mi sa che lo devo fa privato è basta!

    PS : fortunatamente non ho bisogno di bindare il servizio, mi serviva sapere solo se è avviato ma lo faccio con activitymanager eheh.
    Ultima modifica di serkejal; 19-03-10 alle 15:55

  8. #7
    Senior Droid L'avatar di Azatoth


    Registrato dal
    Apr 2009
    Località
    Misinto (MI)
    Messaggi
    568

    Ringraziamenti
    1
    Ringraziato 38 volte in 28 Posts
    Predefinito

    Quote Originariamente inviato da serkejal Visualizza il messaggio
    beh che dire sei stato infinitamente più chiaro di me su cosa sto facendo e la teoria per farlo
    pero purtroppo ritorniamo alla pratica e visto che facciamo citazioni cito anche io :



    Seguendo quanto scritto in documentazione aggiungo nel manifest alle voci application e activity un androidrocess e per service e receveir un altro.
    però non funge!!
    quello che scrivo e del tipo androidrocess="@string/main_process" e androidrocess="@string/service_process". A meno che non riesco a capire quanto citato sopra (cosa anche possibile) dovrebbero crearsi due global process con quei nomi.....
    Una cosa che ho notato, facendo sempre riferimento ai player musicali e che loro usano i ":" per i processi separati dal principale forse dovrei provare così anche se mi pare di aver capito, sempre da quanto citato, che mettere ":" all'inizio serve solo ad identificare se il process e privato o globale.
    che ne pensi??
    forse il problema è quando dice "provided that it has permission to do so" cioè che deve avere il permesso per farlo, però quanto meno dovrebbe lanciarmi una Security Exception no non farlo e basta...... ah mi sa che lo devo fa privato è basta!

    PS : fortunatamente non ho bisogno di bindare il servizio, mi serviva sapere solo se è avviato ma lo faccio con activitymanager eheh.
    si ma non con quei nomi, ma con il valore presente nelle stringhe associate a quei nomi :P.
    A parte questo, il resto è corretto:

    1) Se il nome inizia per ':', un nuovo processo, privato all'applicazione (cioè che solo lei può usare), partirà quando il servizio che lo usa parte.

    2) Se il nome inizia con una lettera minuscola, questo sarà globale (quindi altre applicazioni potranno usarlo). Non mi sembra il tuo caso.

    io farei come nel punto 1) evitando il discorso del processo globale perchè credo non ti servi.


    Google Nexus One USA
    ROM: CyanogenMod 6.1.1 - Android 2.2.1
    Radio: 5.12.00.08
    Recovery: Clockwork

    Sviluppatore di: Swapper per utenti root | Modus Operandi

    Ecco le mie app Android

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire risposte
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Torna su
Privacy Policy