0% found this document useful (0 votes)
58 views8 pages

Techbox Android 05 Service

The document describes code for two types of services in Android: a local service and a messenger service. The local service code shows how to create and bind to a service running in the same process as the client. The messenger service code shows how to create and bind to a service running in a remote process, communicating with it using messages. The client code for each service type is also provided, showing how to bind, unbind, and interact with the services.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views8 pages

Techbox Android 05 Service

The document describes code for two types of services in Android: a local service and a messenger service. The local service code shows how to create and bind to a service running in the same process as the client. The messenger service code shows how to create and bind to a service running in a remote process, communicating with it using messages. The client code for each service type is also provided, showing how to bind, unbind, and interact with the services.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Projeto TechBox | Service

Service
Projeto TechBox | Service

Cdigo do Service
public class LocalService extends Service {
private NotificationManager mNM;

private int NOTIFICATION =


R.string.local_service_started;

public class LocalBinder extends Binder {


LocalService getService() {
return LocalService.this;
}
}

@Override
public void onCreate() {
mNM =
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
}

@Override
public int onStartCommand(Intent intent, int flags, int
startId) {
Log.i("LocalService", "Received start id " +
startId + ": " + intent);
return START_STICKY;
}

@Override
public void onDestroy() {
mNM.cancel(NOTIFICATION);
Toast.makeText(this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}

@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

private final IBinder mBinder = new LocalBinder();

private void showNotification() {


CharSequence text =
getText(R.string.local_service_started);
Projeto TechBox | Service

Notification notification = new


Notification(R.drawable.stat_sample, text,
System.currentTimeMillis());
PendingIntent contentIntent =
PendingIntent.getActivity(this, 0, new Intent(this,
LocalServiceActivities.Controller.class), 0);
notification.setLatestEventInfo(this,
getText(R.string.local_service_label), text, contentIntent);
mNM.notify(NOTIFICATION, notification);
}
}

Cdigo do Cliente
private LocalService mBoundService;

private ServiceConnection mConnection = new


ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {

mBoundService =
((LocalService.LocalBinder)service).getService();

Toast.makeText(Binding.this,
R.string.local_service_connected,
Toast.LENGTH_SHORT).show();
}

public void onServiceDisconnected(ComponentName


className) {
mBoundService = null;
Toast.makeText(Binding.this,
R.string.local_service_disconnected,
Toast.LENGTH_SHORT).show();
}
};

void doBindService() {
bindService(new Intent(Binding.this,
LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}

void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
Projeto TechBox | Service

}
}

@Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}

Exerccio 1: Criar e Executar o Service do exemplo


acima.

Messenger Service
Um exemplo de Service que usa um Messenger como cliente.
public class MessengerService extends Service {
NotificationManager mNM;
ArrayList<Messenger> mClients = new
ArrayList<Messenger>();
int mValue = 0;

static final int MSG_REGISTER_CLIENT = 1;


static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_SET_VALUE = 3;

class IncomingHandler extends Handler {


@Override
public void handleMessage(Message msg) {
switch (msg.what) {

case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
break;

case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;

case MSG_SET_VALUE:
mValue = msg.arg1;
Projeto TechBox | Service

for (int i=mClients.size()-1; i>=0; i--)


{
try {

mClients.get(i).send(Message.obtain(null, MSG_SET_VALUE,
mValue, 0));
} catch (RemoteException e) {
mClients.remove(i);
}
}
break;

default:
super.handleMessage(msg);
}
}
}

final Messenger mMessenger = new Messenger(new


IncomingHandler());

@Override
public void onCreate() {
mNM =
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
}

@Override
public void onDestroy() {
mNM.cancel(R.string.remote_service_started);
Toast.makeText(this,
R.string.remote_service_stopped, Toast.LENGTH_SHORT).show();
}

@Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}

private void showNotification() {


CharSequence text =
getText(R.string.remote_service_started);
Notification notification = new
Notification(R.drawable.stat_sample, text,
System.currentTimeMillis());
Projeto TechBox | Service

PendingIntent contentIntent =
PendingIntent.getActivity(this, 0, new Intent(this,
Controller.class), 0);
notification.setLatestEventInfo(this,
getText(R.string.remote_service_label), text,
contentIntent);
mNM.notify(R.string.remote_service_started,
notification);
}
}

Para fazer o Service rodar num processo remoto deve-se


usar android:process na tag do Manifest:

<service android:name=".app.MessengerService"
android:process=": remote" />

O nome "remote" no fixo. Pode ser usado qualquer outro nome.

Messenger mService = null;


boolean mIsBound;
TextView mCallbackText;

class IncomingHandler extends Handler {


@Override
public void handleMessage(Message msg) {
switch (msg.what) {

case MessengerService.MSG_SET_VALUE:
mCallbackText.setText("Received from
service: " + msg.arg1);
break;
default:
super.handleMessage(msg);
}
}
}

final Messenger mMessenger = new Messenger(new


IncomingHandler());
Projeto TechBox | Service

private ServiceConnection mConnection = new


ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
mService = new Messenger(service);
mCallbackText.setText("Attached.");

try {
Message msg = Message.obtain(null,
MessengerService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);

msg = Message.obtain(null,
MessengerService.MSG_SET_VALUE, this.hashCode(), 0);
mService.send(msg);
} catch (RemoteException e) {
}

Toast.makeText(Binding.this,
R.string.remote_service_connected,
Toast.LENGTH_SHORT).show();
}

public void onServiceDisconnected(ComponentName


className) {
mService = null;
mCallbackText.setText("Disconnected.");

Toast.makeText(Binding.this,
R.string.remote_service_disconnected,
Toast.LENGTH_SHORT).show();
}
};

void doBindService() {
bindService(new Intent(Binding.this,
MessengerService.class), mConnection,
Context.BIND_AUTO_CREATE);
mIsBound = true;
mCallbackText.setText("Binding.");
}

void doUnbindService() {
if (mIsBound) {
if (mService != null) {
try {
Projeto TechBox | Service

Message msg = Message.obtain(null,


MessengerService.MSG_UNREGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
}
}

unbindService(mConnection);
mIsBound = false;
mCallbackText.setText("Unbinding.");
}
}

Exerccio 2: Criar e Executar o Service do exemplo


acima.

You might also like