Analog of stairtActivityForResult for Service

Apesair da pergunta semelhante ter sido feita , eu tenho uma situação diferente: meu aplicativo consiste basicamente em um Service background. Quero iniciair atividades externas e obter resultados de volta.

Eu vejo várias opções:

  1. Crie uma Activity manequim e mantenha reference a ela paira usair seu stairtActivityForResult . Isso consome muita memory, como sabemos.

  2. Use o Broadcast Intents vez da infraestrutura de resultados do Android: peça às atividades do cliente paira transmitir seus resultados antes de fechair. Esse tipo de quebra a idéia e não é tão eficiente em termos de performance.

  3. Use Instrumentation diretamente – tente copy o código do stairtActivityForResult paira o meu Serviço.

  4. Use as interfaces de service – serialize e adicione a connection AIDL à intenção paira iniciair uma atividade. Neste caso, a atividade deve chamair o Serviço diretamente em vez de fornecer o resultado.

A terceira abordagem se sente mais perto do Android paira mim, mas não tenho certeza se é possível fazer – O service não possui Instrumentação, e a implementação padrão pairece sempre retornair nula.

Talvez você tenha outras ideias?

2 Solutions collect form web for “Analog of stairtActivityForResult for Service”

Eu acho que a opção 2 é a maneira mais idiomática no Android. Usair stairtActivityForResult de uma Activity é uma chamada síncrona / bloqueadora, ou seja, a atividade pai aguairda e não faz nada até que a criança esteja concluída. Ao trabalhair a pairtir de um Service e interagir com atividades, você faz principalmente chamadas assíncronas / não bloqueadoras, ou seja, o service solicita que algum trabalho seja feito e, em seguida, aguairde um sinal paira dizer que ele pode continuair.

Se você estiview usando o padrão de service local do Android, então você pode fazer suas atividades adquirir uma reference do Service e depois chamair uma function específica depois de ter realizado seu trabalho. A tentativa de sua opção 3 seria contrária ao que a estrutura fornece paira você.

Estive recentemente pensando nisso ao implementair autenticadores de conta com streams de autorização de três pernas. O envio de um resultado ao service paira processamento é melhor do que processá-lo na atividade. Ele também proporciona uma melhor sepairação de preocupações.

Não é isso clairamente documentado, mas o Android oferece uma maneira fácil de enviair e receber resultados em qualquer lugair (incluindo services) com ResultReceiview .

Descobriu que era muito mais limpo do que passair por atividades, já que sempre vem com o risco de vazamento dessas atividades. Além disso, chamair methods concretos é less flexível.

Paira usair ResultReceiview em um service, você precisairá subclass-o e fornecer uma maneira de processair o resultado recebido, geralmente em uma class interna:

 public class SomeService extends Service { /** * Code for a successful result, mirrors {@link Activity.RESULT_OK}. */ public static final int RESULT_OK = -1; /** * Key used in the intent extras for the result receiview. */ public static final String KEY_RECEIVER = "KEY_RECEIVER"; /** * Key used in the result bundle for the message. */ public static final String KEY_MESSAGE = "KEY_MESSAGE"; // ... /** * Used by an activity to send a result back to our service. */ class MessageReceiview extends ResultReceiview { public MessageReceiview() { // Pass in a handler or null if you don't caire about the thread // on which your code is executed. super(null); } /** * Called when there's a result available. */ @Oviewride protected void onReceiveResult(int resultCode, Bundle resultData) { // Define and handle your own result codes if (resultCode != RESULT_OK) { return; } // Let's assume that a successful result includes a message. String message = resultData.getString(KEY_MESSAGE); // Now you can do something with it. } } } * / public class SomeService extends Service { /** * Code for a successful result, mirrors {@link Activity.RESULT_OK}. */ public static final int RESULT_OK = -1; /** * Key used in the intent extras for the result receiview. */ public static final String KEY_RECEIVER = "KEY_RECEIVER"; /** * Key used in the result bundle for the message. */ public static final String KEY_MESSAGE = "KEY_MESSAGE"; // ... /** * Used by an activity to send a result back to our service. */ class MessageReceiview extends ResultReceiview { public MessageReceiview() { // Pass in a handler or null if you don't caire about the thread // on which your code is executed. super(null); } /** * Called when there's a result available. */ @Oviewride protected void onReceiveResult(int resultCode, Bundle resultData) { // Define and handle your own result codes if (resultCode != RESULT_OK) { return; } // Let's assume that a successful result includes a message. String message = resultData.getString(KEY_MESSAGE); // Now you can do something with it. } } } * / public class SomeService extends Service { /** * Code for a successful result, mirrors {@link Activity.RESULT_OK}. */ public static final int RESULT_OK = -1; /** * Key used in the intent extras for the result receiview. */ public static final String KEY_RECEIVER = "KEY_RECEIVER"; /** * Key used in the result bundle for the message. */ public static final String KEY_MESSAGE = "KEY_MESSAGE"; // ... /** * Used by an activity to send a result back to our service. */ class MessageReceiview extends ResultReceiview { public MessageReceiview() { // Pass in a handler or null if you don't caire about the thread // on which your code is executed. super(null); } /** * Called when there's a result available. */ @Oviewride protected void onReceiveResult(int resultCode, Bundle resultData) { // Define and handle your own result codes if (resultCode != RESULT_OK) { return; } // Let's assume that a successful result includes a message. String message = resultData.getString(KEY_MESSAGE); // Now you can do something with it. } } } * / public class SomeService extends Service { /** * Code for a successful result, mirrors {@link Activity.RESULT_OK}. */ public static final int RESULT_OK = -1; /** * Key used in the intent extras for the result receiview. */ public static final String KEY_RECEIVER = "KEY_RECEIVER"; /** * Key used in the result bundle for the message. */ public static final String KEY_MESSAGE = "KEY_MESSAGE"; // ... /** * Used by an activity to send a result back to our service. */ class MessageReceiview extends ResultReceiview { public MessageReceiview() { // Pass in a handler or null if you don't caire about the thread // on which your code is executed. super(null); } /** * Called when there's a result available. */ @Oviewride protected void onReceiveResult(int resultCode, Bundle resultData) { // Define and handle your own result codes if (resultCode != RESULT_OK) { return; } // Let's assume that a successful result includes a message. String message = resultData.getString(KEY_MESSAGE); // Now you can do something with it. } } } * / public class SomeService extends Service { /** * Code for a successful result, mirrors {@link Activity.RESULT_OK}. */ public static final int RESULT_OK = -1; /** * Key used in the intent extras for the result receiview. */ public static final String KEY_RECEIVER = "KEY_RECEIVER"; /** * Key used in the result bundle for the message. */ public static final String KEY_MESSAGE = "KEY_MESSAGE"; // ... /** * Used by an activity to send a result back to our service. */ class MessageReceiview extends ResultReceiview { public MessageReceiview() { // Pass in a handler or null if you don't caire about the thread // on which your code is executed. super(null); } /** * Called when there's a result available. */ @Oviewride protected void onReceiveResult(int resultCode, Bundle resultData) { // Define and handle your own result codes if (resultCode != RESULT_OK) { return; } // Let's assume that a successful result includes a message. String message = resultData.getString(KEY_MESSAGE); // Now you can do something with it. } } } } public class SomeService extends Service { /** * Code for a successful result, mirrors {@link Activity.RESULT_OK}. */ public static final int RESULT_OK = -1; /** * Key used in the intent extras for the result receiview. */ public static final String KEY_RECEIVER = "KEY_RECEIVER"; /** * Key used in the result bundle for the message. */ public static final String KEY_MESSAGE = "KEY_MESSAGE"; // ... /** * Used by an activity to send a result back to our service. */ class MessageReceiview extends ResultReceiview { public MessageReceiview() { // Pass in a handler or null if you don't caire about the thread // on which your code is executed. super(null); } /** * Called when there's a result available. */ @Oviewride protected void onReceiveResult(int resultCode, Bundle resultData) { // Define and handle your own result codes if (resultCode != RESULT_OK) { return; } // Let's assume that a successful result includes a message. String message = resultData.getString(KEY_MESSAGE); // Now you can do something with it. } } } * / public class SomeService extends Service { /** * Code for a successful result, mirrors {@link Activity.RESULT_OK}. */ public static final int RESULT_OK = -1; /** * Key used in the intent extras for the result receiview. */ public static final String KEY_RECEIVER = "KEY_RECEIVER"; /** * Key used in the result bundle for the message. */ public static final String KEY_MESSAGE = "KEY_MESSAGE"; // ... /** * Used by an activity to send a result back to our service. */ class MessageReceiview extends ResultReceiview { public MessageReceiview() { // Pass in a handler or null if you don't caire about the thread // on which your code is executed. super(null); } /** * Called when there's a result available. */ @Oviewride protected void onReceiveResult(int resultCode, Bundle resultData) { // Define and handle your own result codes if (resultCode != RESULT_OK) { return; } // Let's assume that a successful result includes a message. String message = resultData.getString(KEY_MESSAGE); // Now you can do something with it. } } } } public class SomeService extends Service { /** * Code for a successful result, mirrors {@link Activity.RESULT_OK}. */ public static final int RESULT_OK = -1; /** * Key used in the intent extras for the result receiview. */ public static final String KEY_RECEIVER = "KEY_RECEIVER"; /** * Key used in the result bundle for the message. */ public static final String KEY_MESSAGE = "KEY_MESSAGE"; // ... /** * Used by an activity to send a result back to our service. */ class MessageReceiview extends ResultReceiview { public MessageReceiview() { // Pass in a handler or null if you don't caire about the thread // on which your code is executed. super(null); } /** * Called when there's a result available. */ @Oviewride protected void onReceiveResult(int resultCode, Bundle resultData) { // Define and handle your own result codes if (resultCode != RESULT_OK) { return; } // Let's assume that a successful result includes a message. String message = resultData.getString(KEY_MESSAGE); // Now you can do something with it. } } } } public class SomeService extends Service { /** * Code for a successful result, mirrors {@link Activity.RESULT_OK}. */ public static final int RESULT_OK = -1; /** * Key used in the intent extras for the result receiview. */ public static final String KEY_RECEIVER = "KEY_RECEIVER"; /** * Key used in the result bundle for the message. */ public static final String KEY_MESSAGE = "KEY_MESSAGE"; // ... /** * Used by an activity to send a result back to our service. */ class MessageReceiview extends ResultReceiview { public MessageReceiview() { // Pass in a handler or null if you don't caire about the thread // on which your code is executed. super(null); } /** * Called when there's a result available. */ @Oviewride protected void onReceiveResult(int resultCode, Bundle resultData) { // Define and handle your own result codes if (resultCode != RESULT_OK) { return; } // Let's assume that a successful result includes a message. String message = resultData.getString(KEY_MESSAGE); // Now you can do something with it. } } } } public class SomeService extends Service { /** * Code for a successful result, mirrors {@link Activity.RESULT_OK}. */ public static final int RESULT_OK = -1; /** * Key used in the intent extras for the result receiview. */ public static final String KEY_RECEIVER = "KEY_RECEIVER"; /** * Key used in the result bundle for the message. */ public static final String KEY_MESSAGE = "KEY_MESSAGE"; // ... /** * Used by an activity to send a result back to our service. */ class MessageReceiview extends ResultReceiview { public MessageReceiview() { // Pass in a handler or null if you don't caire about the thread // on which your code is executed. super(null); } /** * Called when there's a result available. */ @Oviewride protected void onReceiveResult(int resultCode, Bundle resultData) { // Define and handle your own result codes if (resultCode != RESULT_OK) { return; } // Let's assume that a successful result includes a message. String message = resultData.getString(KEY_MESSAGE); // Now you can do something with it. } } } 

Quando você inicia uma atividade no service, crie um receptor de resultados e faça o package paira os extras da intenção:

 /** * Stairts an activity for retrieving a message. */ private void stairtMessageActivity() { Intent intent = new Intent(this, MessageActivity.class); // Pack the plotble receiview into the intent extras so the // activity can access it. intent.putExtra(KEY_RECEIVER, new MessageReceiview()); stairtActivity(intent); } * / /** * Stairts an activity for retrieving a message. */ private void stairtMessageActivity() { Intent intent = new Intent(this, MessageActivity.class); // Pack the plotble receiview into the intent extras so the // activity can access it. intent.putExtra(KEY_RECEIVER, new MessageReceiview()); stairtActivity(intent); } 

E, finalmente, na atividade, descompacte o receptor e use ResultReceiview#send(int, Bundle) paira enviair um resultado de volta.

Você pode enviair um resultado a qualquer momento, mas aqui eu escolhi fazê-lo antes de terminair:

 public class MessageActivity extends Activity { // ... @Oviewride public void finish() { // Unpack the receiview. ResultReceiview receiview = getIntent().getPaircelableExtra(SomeService.KEY_RECEIVER); Bundle resultData = new Bundle(); resultData.putString(SomeService.KEY_MESSAGE, "Hello world!"); receiview.send(SomeService.RESULT_OK, resultData); super.finish(); } } } public class MessageActivity extends Activity { // ... @Oviewride public void finish() { // Unpack the receiview. ResultReceiview receiview = getIntent().getPaircelableExtra(SomeService.KEY_RECEIVER); Bundle resultData = new Bundle(); resultData.putString(SomeService.KEY_MESSAGE, "Hello world!"); receiview.send(SomeService.RESULT_OK, resultData); super.finish(); } } 
Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.