Sei sulla pagina 1di 33

Development

Android Working in the background

Services
Run without a dedicated UI Execute in the main thread of the applica?ons process Higher priority than inac?ve Ac?vi?es Can assure that your applica?on con?nue to run and respond to events even when the applica?on is not in ac?ve use

Services
For applica?ons that run in the background
Responding to events Polling for data Upda?ng Content Providers

Services
Services has got no UI Start , stop and controlled from other applica?on components
Other services Ac?vi?es Broadcast receivers

Service Controls
Start and stop using intents Binding a Service to an Ac?vity

Coding
Public class MyService extends { public void onCreate() { //Ac?ons to perform when service is CREATED } public iBinder onBind(Intent intent) { //Replace with service binding implementa?on return null; } public void onStart(Intent intent, int startId) { //Ac?ons to perform when service is started } }

Service

ASer crea?on
Remember to register in the Manifest le
Using the service tag E.g.
<service android:enabled=true android:name=.MyService></service>

Start a service
Call startService() to start a service
Implicit Explicit E.g. startService(new Intent(MyService.MY_ACTION)); startService(new Intent(this, MyService.class));

Stop a service
Use stopService, passing an Intent that denes the Service to stop
E.g. ComponentName service = startService( new Intent(this, myWorld.class)); stopService(new Intent(this, service.getClass());

Example
1 Ac?vity 1 broadcast receiver 1 service
B.R

Update

Broadcast
Ac?vity

Control

Service

Example : Ac?vity
Global variables
TextView txtMsg; Bubon btnStartService; Bubon btnStopService; ComponentName service; Intent intentMyService; BroadcastReceiver receiver;

Example : Ac?vity
Get references
intentMyService = new Intent(this, myServiceRunner.class); btnStopService = (Bubon) ndViewById(R.id.btnStopService); btnStartService = (Bubon) ndViewById(R.id.btnStartService); txtMsg = (TextView) ndViewById(R.id.txtMsg);

Example : Ac?vity
btnStartService.setOnClickListener(new OnClickListener() { public void onClick(View v) {
try {
service = startService(intentMyService); txtMsg.setText("MyService started - (see DDMS Log)");

} });

} catch (Excep?on e) { e.printStackTrace(); }

Example : Ac?vity
btnStopService.setOnClickListener(new OnClickListener() { public void onClick(View v) {
try {
stopService(new Intent(intentMyService) ); txtMsg.setText("ASer stopping Service: \n" + service.getClassName());

} catch (Excep?on e) { e.printStackTrace(); }

} });

Example : Ac?vity
IntentFilter mainFilter = new IntentFilter("liren.ac?on.GOSERVICE3"); receiver = new MyMainLocalReceiver(); registerReceiver(receiver, mainFilter);

Example : Ac?vity
protected void onDestroy() { super.onDestroy(); try { stopService(intentMyService); unregisterReceiver(receiver); } catch (Excep?on e) { Log.e ("MAIN3-DESTROY>>>", e.getMessage() ); } Log.e ("MAIN3-DESTROY>>>" , "Adios" ); } //onDestroy

Example : Broadcast receiver


public class MyMainLocalReceiver extends BroadcastReceiver { @Override public void onReceive(Context localContext, Intent callerIntent) {
String serviceData = callerIntent.getStringExtra("serviceData"); Log.e ("MAIN>>>", serviceData + " -receiving data " + SystemClock.elapsedRealKme() ); String now = "\n" + serviceData + " --- " + new Date().toLocaleString(); txtMsg.append(now);

} }//MyMainLocalReceiver

Example : Service
public class myServiceRunner extends Service {
boolean isRunning = true; public IBinder onBind(Intent arg0) {} public void onStart(Intent intent, int startId) { } public void onDestroy() { }

public void onCreate() { }

}//myServiceRunner.java

Example : Service
public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { super.onCreate(); }

public void onStart(Intent intent, int startId) {

Example : Service

super.onStart(intent, startId); Log.e ("<<myServiceRunner-onStart>>", "I am alive-3!"); // we place the slow work of the service in its own thread // so the caller is not hung up wai?ng for us Thread triggerService = new Thread ( new Runnable() {

});

triggerService.start(); }//onStart

Thread triggerService = new Thread ( new Runnable() {


long star?ngTime = System.currentTimeMillis(); long ?cs = 0; public void run() { . }

Example : Service

});

Example : Service
public void run() { for(int i=0; (i< 120) & isRunning; i++)
{
//at most 10 minutes

try {

}//run

}//For

} catch (Excep?on e) { e.printStackTrace(); }

Example : Service
//at most 10 minutes

try {

//fake that you are very busy here ?cs = System.currentTimeMillis() - starKngTime; Intent myFilteredResponse = new Intent ("liren.ac?on.GOSERVICE3"); String msg = i + " value: " + ?cs; myFilteredResponse.putExtra("serviceData", msg); sendBroadcast(myFilteredResponse); Thread.sleep(1000); //ve seconds

Example : Service
public void onDestroy() {
super.onDestroy(); Log.e ("<<myServiceRunner-onDestroy>>", "I am dead-3"); isRunning = false;

} //onDestroy

Result

Binding Ac?vi?es to services


Ac?vity will maintain a reference to the service instance itself Allowing ac?vity to make method calls on the running service as you would with other class

Coding
Implement the following onBind to the service
Private nal Ibinder binder = new MyBinder(); Public IBinder onBind(Intent intent) { return binder } Public class MYBinder extends Binder{ MyService getService(){ return MyService.this; } }

The missing link


The connec?on between Service and Ac?vity is represented as a ServiceConnec?on Implement a new ServiceConnec?on Override the onServiceConnected and onServiceDisconnected to get reference to the Service instance once a connec?on has been established.

Coding
Private MyService serviceBinder; Private ServiceConnec?on mConnec?on = new ServiceConnec?on(){ public void onServiceConnected (ComponentName className, Ibinder service) { //Called when the connec?on is made serviceBinder = ((MyService.MyBinder)service).getService(); } public void onServiceDisconnected(ComponentName className) { //Received when the service unexpectedly disconnects serviceBinder = null; } }

Coding
Public void onCreate(Bundle icicle) { super.onCreate(icicle); Intent bindIntent = new Intent(MyAc?vity.this, MyService.Class); bindService(bindIntent, mConnec?on, Context.Bind_AUTO_CREATE); }

Binding Ac?vi?es to services


Once bounded, all of the service public methods and proper?es are available through the serviceBinder object

UI tools
Android provides several techniques for applica?on components to communicate with users without an Ac?vity providing a direct UI
Toasts No?ca?ons

Potrebbero piacerti anche