Service - usando Binder - mas vinculado |
Top Previous Next |
Este exemplo é igual ao anterior, mas tem uma conexão Binder para ver o valor que o service está contando na tela da activity. Tela da Activity Logcat Contador.java package com.servicoes;
public interface Contador { public int count(); }
ExemploServico.java
import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log;
public class ExemploServico extends Service implements Runnable {
private static final int MAX = 10; private static final String LOG = "servico"; protected int count; private boolean ativo;
@Override public IBinder onBind(Intent arg0) { return null; // nao queremos interagir com o servico }
@Override public void onCreate() { Log.i(LOG, "ExemploServico.onCreate()"); ativo = true; // delega para uma thread new Thread(this).start(); // olha lá a implementacao do Runnable }
@Override public void onStart(Intent intent, int startId) { Log.w(LOG, "ExemploServico.onStart()"); }
@Override public void onDestroy() { // ao encerrar altera a flag para thread parar ativo = false; Log.e(LOG, "ExemploServico.onDestroy()"); }
// runnable public void run() { while (ativo && count < MAX) { fazAlgumaCoisa(); Log.i(LOG, "Executando. count=" + count); count++; } Log.i(LOG, "ExemploServico.Fim"); // auto-encerra o servico quando chegar a 10 stopSelf(); }
private void fazAlgumaCoisa() { try { Thread.sleep(1000); // simula processamento } catch (InterruptedException e) { e.printStackTrace(); } } }
ServicoComConexao.java
import android.content.Intent; import android.os.Binder; import android.os.IBinder;
public class ServicoComConexao extends ExemploServico implements Contador {
private IBinder conexao = new LocalBinder();
// implementacao de uma classe interna que retorna o nosso servico public class LocalBinder extends Binder { public Contador getContador() { // retorna o servico SimpleBindService para Activity acessar os médotos internos return ServicoComConexao.this; } }
@Override public IBinder onBind(Intent it) { return conexao; }
public int count() { return count; }
} ServicosActivity.java
import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast;
import com.servicoes.ServicoComConexao.LocalBinder;
public class ServicosActivity extends Activity implements OnClickListener, ServiceConnection {
private Button btStart, btStop, btAtual; private Contador contador; private ServiceConnection conexao;
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
conexao = this;
btStart = (Button)findViewById(R.id.btStart); btAtual = (Button)findViewById(R.id.btAtual); btStop = (Button)findViewById(R.id.btStop);
btStart.setOnClickListener(this); btAtual.setOnClickListener(this); btStop.setOnClickListener(this); }
public void onClick(View v) {
if (v.getId() == R.id.btStart) { Log.w("Atividade", "start clicked"); Class classeServico = ServicoComConexao.class; bindService(new Intent(ServicosActivity.this, classeServico), conexao, Context.BIND_AUTO_CREATE); }
if (v.getId() == R.id.btStop) { Log.e("Atividade", "STOP clicked"); unbindService(conexao); }
if (v.getId() == R.id.btAtual) { int count = contador.count(); Log.e("Atividade", "get COUNT " + count); Toast.makeText(this, "contador = " + count, Toast.LENGTH_SHORT).show(); } }
protected void onDestroy() { Log.e("Atividade", "onDestroy()"); super.onDestroy(); }
public void onServiceConnected(ComponentName className, IBinder service) { LocalBinder binder = (LocalBinder)service; contador = binder.getContador(); }
public void onServiceDisconnected(ComponentName arg0) { contador = null; } }
main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Serviços" />
<Button android:id="@+id/btStart" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start" />
<Button android:id="@+id/btAtual" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Ver a contagem atual" />
<Button android:id="@+id/btStop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop" /> </LinearLayout>
manifest
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.servicoes" android:versionCode="1" android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".ServicosActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
<service android:name=".ExemploServico" > <intent-filter> <action android:name="SERVICE_1" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </service>
<service android:name=".ServicoComConexao" /> </application>
</manifest>
Observação Para impedir isso, você deve juntar criar o servico com startService e só depois usar o binService
|