Recipe Creating a Self Contained Service

The steps to create a self-contained service associated with a single component are

1. Create a class to extend Service. (In Eclipse, this can be done by right-clicking the project, choosing New ^ Class and specifying android.app.Service as the super class.)

2. Declare the service in the AndroidManifest.xml file by adding a variation of the following (this should be done automatically with the previous Eclipse step): <service android:name=".myService"></service>

3. Override the onCreate() and onDestroy() methods. (In Eclipse, this can be done by right-clicking on the class file, choosing Source ^ Override/Implement Methods..., and checking the onCreate() and onDestroy() methods.) These contain the functionality of the service when it is started and stopped.

4. Override the onBind() method for cases when a new component binds to this service after it has already been created.

5. Activate the service from an external trigger.The service cannot run by itself, but instead needs to be activated by a separate component or trigger in some way. For example, a component can create an intent to start or stop the service using startService() or stopService() as needed.

To illustrate the previous, a simple service is shown in Listing 3.10 to use the play_music() function from the first recipe in this chapter. Note the following:

■ A Toast is used to show when the service is started or stopped.

■ The onBind() method is overridden, but not used. (This can be extended as needed.)

■ A thread still needs to be created for playing music to not block the UI.

■ The service does not stop when the activity is destroyed (for example, by changing the screen orientation) or when the activity is paused (for example, when pressing the home button).This shows the service, although launched by the activity, runs as its own entity.

Listing 3.10 src/com/cookbook/simple_service/SimpleService.java package com.cookbook.simple_service;

import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; import android.widget.Toast;

public class SimpleService extends Service {

@Override public IBinder onBind(Intent arg0) { return null;

boolean paused = false;

@Override public void onCreate() { super.onCreate();

Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();

paused = false;

Thread initBkgdThread = new Thread(new Runnable() { public void run() { play_music();

initBkgdThread.start();

@Override public void onDestroy() { super.onDestroy();

Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();

paused = true;

int[] notes = {R.raw.c5, R.raw.b4, R.raw.a4, R.raw.g4}; int NOTE_DURATION = 400; //millisec MediaPlayer m_mediaPlayer; private void play_music() {

//check to ensure main activity not paused if(!paused) {

if(m_mediaPlayer != null) {m_mediaPlayer.release();} m_mediaPlayer = MediaPlayer.create(this, notes[ii%4]); m_mediaPlayer.start(); try {

Thread.sleep(NOTE_DURATION); } catch (InterruptedException e) { e.printStackTrace();

The AndroidManifest.xml now has both the activity and service declared, as shown in Listing 3.11.

Listing 3.11 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.cookbook.simple_service" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon"

android:label="@string/app_name"> <activity android:name=".SimpleActivity"

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=".SimpleService"></service>

</application>

<uses-sdk android:minSdkVersion="3" /> </manifest>

The example activity that sets up the UI to trigger the start and stop of this service is shown in Listing 3.12, and the associated layout file is shown in Listing 3.13 for the two buttons.

Listing 3.12 src/com/cookbook/simple_service/SimpleActivity.java package com.cookbook.simple_service;

import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button;

public class SimpleActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

Button startButton = (Button) findViewById(R.id.Button01); startButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view){

startService(new Intent(SimpleActivity.this,

SimpleService.class));

Button stopButton = (Button)findViewById(R.id.Button02);

stopButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v){

stopService(new Intent(SimpleActivity.this,

SimpleService.class));

Listing 3.13 res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />

<Button android:text="Do it" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <Button android:text="Stop it" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

</LinearLayout>

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook


Post a comment