Service - exemplo simples |
Top Previous Next |
Tela da activity Resultado do serviço em ação ServicosActivity.java
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button;
public class ServicosActivity extends Activity implements OnClickListener {
Button btStart, btStop; Intent intencao;
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
intencao = new Intent("SERVICE_1");
btStart = (Button)findViewById(R.id.btStart); btStop = (Button)findViewById(R.id.btStop);
btStart.setOnClickListener(this); btStop.setOnClickListener(this); }
public void onClick(View v) {
if (v.getId() == R.id.btStart) { Log.w("Atividade", "start clicked"); startService(intencao); }
if (v.getId() == R.id.btStop) { Log.e("Atividade", "STOP clicked"); stopService(intencao); } }
protected void onDestroy() { Log.e("Atividade", "onDestroy()"); super.onDestroy(); } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <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/btStop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop" />
</LinearLayout>
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(); } } }
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> </application>
</manifest>
Observações
Desta forma como foi montado o exemplo, o serviço continua rodando após a morte da Activity, mas não se "comunicam" - não estão vinculados |