1 /* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.example.android.apis.app; 18 19 // Need the following import to get access to the app resources, since this 20 // class is in a sub-package. 21 import com.example.android.apis.R; 22 23 import android.app.Activity; 24 import android.content.ComponentName; 25 import android.content.Intent; 26 import android.os.Bundle; 27 import android.view.View; 28 import android.view.View.OnClickListener; 29 import android.widget.Button; 30 31 32 /** 33 * <p>Example of explicitly starting and stopping the {@link LocalService}. 34 * This demonstrates the implementation of a service that runs in the same 35 * process as the rest of the application, which is explicitly started and stopped 36 * as desired.</p> 37 */ 38 public class LocalServiceController extends Activity { 39 @Override onCreate(Bundle savedInstanceState)40 protected void onCreate(Bundle savedInstanceState) { 41 super.onCreate(savedInstanceState); 42 43 setContentView(R.layout.local_service_controller); 44 45 // Watch for button clicks. 46 Button button = (Button)findViewById(R.id.start); 47 button.setOnClickListener(mStartListener); 48 button = (Button)findViewById(R.id.stop); 49 button.setOnClickListener(mStopListener); 50 } 51 52 private OnClickListener mStartListener = new OnClickListener() { 53 public void onClick(View v) 54 { 55 // Make sure the service is started. It will continue running 56 // until someone calls stopService(). The Intent we use to find 57 // the service explicitly specifies our service component, because 58 // we want it running in our own process and don't want other 59 // applications to replace it. 60 startService(new Intent(LocalServiceController.this, 61 LocalService.class)); 62 } 63 }; 64 65 private OnClickListener mStopListener = new OnClickListener() { 66 public void onClick(View v) 67 { 68 // Cancel a previous call to startService(). Note that the 69 // service will not actually stop at this point if there are 70 // still bound clients. 71 stopService(new Intent(LocalServiceController.this, 72 LocalService.class)); 73 } 74 }; 75 } 76 77