Presentation is loading. Please wait.

Presentation is loading. Please wait.

Developing Android Services

Similar presentations


Presentation on theme: "Developing Android Services"— Presentation transcript:

1 Developing Android Services
Chapter 12

2 Objectives Creating a service that runs in the background
Performing long-running tasks in a separate thread Performing repeated tasks in a service Having an activity and a service to communicate

3 Android Service Application component that runs (in background) without needing to interact with the user, e.g., playing background music, logging geographical coordinates, etc. => no need to present a UI to the user Three types Foreground: perform a task that is noticeable to the user (e.g., playing an audio track). Background: perform a task that isn’t directly noticed by the user (e.g., compacting storage) Bound: bound to an app component (e.g., activity); stop when no longer bound.

4 In-Class: Message Later App*
App to send a message later using IntentService IntentService: simple way of creating a background service running in a new thread id=phoneEdit id=delayEdit id=msgEdit id=sendButton Steps Create a project named “Message Later”. Download layout from the course website. Create an IntentService named “MessageIntentService”. Code the intent service. Start the intent service from activity. *Dangerous permission required: android.permission.SEND_SMS

5 Message Later App (Cont.)
Create a new IntentService named MessageIntentService. New > Service > Service (IntentService) (1) Uncheck the checkbox labeled “include helper start method?” (2) 1 2 Manifest: uncheck <application ... <service android:name=".MessageIntentService" android:exported="false" /> </application>

6 public class MessageIntentService extends IntentService {
public MessageIntentService() { super("MessageIntentService"); } @Override protected void onHandleIntent(Intent intent) { String phone = intent.getStringExtra("phone"); String msg = intent.getStringExtra("message"); int delay = Integer.parseInt(intent.getStringExtra("delay")); try { Thread.sleep(delay * 1000); } catch (InterruptedException e) { SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phone, null, msg, null, null); MessageIntentService // starting a service Intent intent = new Intent(this, MessageIntentService.class); intent.putExtra("phone", …)); intent.putExtra("delay", …); intent.putExtra("message", …); startService(intent); MainActivity

7 Runtime Permission Request
public class MainActivity extends AppCompatActivity { private static final int REQUEST_SMS_PERMISSION = 100; protected void onCreate(Bundle savedInstanceState) { ... requestSmsPermission(); } private void requestSmsPermission() { String smsPermission = Manifest.permission.SEND_SMS; int grant = ContextCompat.checkSelfPermission(this, smsPermission); if (grant != PackageManager.PERMISSION_GRANTED) { String[] permissions = new String[] { smsPermission }; ActivityCompat.requestPermissions(this, permissions, REQUEST_SMS_PERMISSION); @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_SMS_PERMISSION) { showToast(grantResults[0] == PackageManager.PERMISSION_GRANTED ? "Permission granted!" : "Permission not granted!"); private void showToast(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); }

8 Extra: Notification Service
Improve the app to display a notification when the requested message has been sent. Use the built-in notification service of Android (see page 94 “Displaying Notifications” in Chapter 3).

9 Creating Service As a subclass of android.app.Service
Override key framework methods including: int onStartCommand(Intent i, int flags, int startId) IBind onBind(Intent i) void onCreate() void onDestroy() Declare the service in AndroidManifest.xml*, e.g., <service android:name=".MyService"/> *Done automatically with Android Studio: New >> Service >> Service or Service (IntentService).

10 int onStartCommand(Intent intent, int flags, int startId)
Called when the service is started by startService() startId: unique Id generated by system flags: additional info supplied by the system Return START_STICKY to make the service continue to run until explicitly stopped (<-> START_NOT_STICKY). call stopSelf() or stopService() to stop the service IBind onBind(Intent intent) Enable to bind an activity (by calling bindService()) to a service so as to access public elements such as fields and methods void onCreate() Called when the service is first created void onDestroy() Called when the service is stopped by calling stopService()

11 Starting/Stopping Service
startService(new Intent(getBaseContext(), MyService.class)); startService(new Intent("edu.utep.cs.cs4330.MyService")); Need to make the service available to other applications <service android:name=".MyService"> <intent-filter> <action android:name="edu.utep.cs.cs4330.MyService"/> </intent-filter> </service> By default, service runs on the same thread that starts it (e.g., UI thread). stopService(new Intent(getBaseContext(), MyService.class));

12 Service Lifecycle

13 Long-Running Tasks In Service
Perform in a new thread, but why? How? Thread class AsyncTask<Params, Progress, Result> class void onPreExecute() Invoked on the UI thread before doInBackground void doInBackground(Params...) Invoked on the background thread after onPreExecute void onProgressUpdate(Progress...) Invoked on UI thread after a call to publishProgress(Progress...) void onPostExecute(Result) Invoked on the UI thread after the background task finishes

14 Repeated Tasks In Service
Performing repeated tasks in a service, e.g., alarm clock service that runs persistently in the background Use the java.util.Timer class providing several methods such as void scheduleAtFixedRate(TimerTask task, long delay, long period) new java.util.Timer().scheduleAtFixedRate( new java.util.TimerTask() { public void run() { /* ... */ } }, 0, // no delay 1000); // at every sec To cancel, call the Timer.cancel() method.

15 IntentService Subclass of Service to execute an asynchronous task on a new thread Automatically stop the service when completed (i.e., no need to call the stopSelf() method) Just need to override: protected void onHandleIntent(Intent i) that performs a task on a new thread Also need to add the service to manifest, e.g., <service android:name=".MyIntentService"/> IntentService onHandleIntent(Intent) Service onCreate() onStartCommand() onDestroy()

16 Service-Activity Communication
Use the BroadCastReceiver In service: Intent broadcastIntent = new Intent(); broadcastIntent.setAction("MyAction"); getBaseContext().sendBroadcast(broadcastIntent); In activity: IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("MyAction"); registerReceiver(new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { ... } }, intentFilter);

17 Binding Activities To Services
For an activity to access public members of a service Use the bindService() method in Activities Override the onBind() method in Services Refer to API document of the Service class

18 Side: Service vs. Thread
Use Thread if: Work needs to be performed outside the main (UI) thread, but only while the user is interacting with the user. E.g., playing some music, but only while the activity is running. Thread will sleep if the device sleeps; Service can perform operations even if the device goes to sleep. Thread: music will play only if the app is active and screen display is on. Service: music will play even if the app is paused or screen display is off.

19 In-Class (Pair): Music Service
Create a service that, given a music file URL, plays the music as a background service. MediaPlayer player = new MediaPlayer(); player.setDataSource(url); // “ player.prepare(); player.start(); When the playback is completed, the service should notify to the activity to display a toast message indicating the completion of the playback. setOnCompletionListener(MediaPlayer.OnCompletionListener)

20 Music Service URL 1: startService(i) <<activity>>
MusicPlayer <<service>> MusicService 2. play the requested URL 3. broadcast an intent (done) Intent <<broadcast receiver>> 4. Receive and toast (done)


Download ppt "Developing Android Services"

Similar presentations


Ads by Google