• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2009 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 import android.app.Activity;
20 import android.app.Notification;
21 import android.app.NotificationManager;
22 import android.app.PendingIntent;
23 import android.app.Service;
24 import android.content.Intent;
25 import android.os.Bundle;
26 import android.os.IBinder;
27 import android.util.Log;
28 import android.view.View;
29 import android.view.View.OnClickListener;
30 import android.widget.Button;
31 
32 import java.lang.reflect.InvocationTargetException;
33 import java.lang.reflect.Method;
34 
35 // Need the following import to get access to the app resources, since this
36 // class is in a sub-package.
37 import com.example.android.apis.R;
38 
39 /**
40  * This is an example of implementing an application service that can
41  * run in the "foreground".  It shows how to code this to work well by using
42  * the improved Android 2.0 APIs when available and otherwise falling back
43  * to the original APIs.  Yes: you can take this exact code, compile it
44  * against the Android 2.0 SDK, and it will against everything down to
45  * Android 1.0.
46  */
47 public class ForegroundService extends Service {
48     static final String ACTION_FOREGROUND = "com.example.android.apis.FOREGROUND";
49     static final String ACTION_BACKGROUND = "com.example.android.apis.BACKGROUND";
50 
51  // BEGIN_INCLUDE(foreground_compatibility)
52     private static final Class[] mStartForegroundSignature = new Class[] {
53         int.class, Notification.class};
54     private static final Class[] mStopForegroundSignature = new Class[] {
55         boolean.class};
56 
57     private NotificationManager mNM;
58     private Method mStartForeground;
59     private Method mStopForeground;
60     private Object[] mStartForegroundArgs = new Object[2];
61     private Object[] mStopForegroundArgs = new Object[1];
62 
63     /**
64      * This is a wrapper around the new startForeground method, using the older
65      * APIs if it is not available.
66      */
startForegroundCompat(int id, Notification notification)67     void startForegroundCompat(int id, Notification notification) {
68         // If we have the new startForeground API, then use it.
69         if (mStartForeground != null) {
70             mStartForegroundArgs[0] = Integer.valueOf(id);
71             mStartForegroundArgs[1] = notification;
72             try {
73                 mStartForeground.invoke(this, mStartForegroundArgs);
74             } catch (InvocationTargetException e) {
75                 // Should not happen.
76                 Log.w("ApiDemos", "Unable to invoke startForeground", e);
77             } catch (IllegalAccessException e) {
78                 // Should not happen.
79                 Log.w("ApiDemos", "Unable to invoke startForeground", e);
80             }
81             return;
82         }
83 
84         // Fall back on the old API.
85         setForeground(true);
86         mNM.notify(id, notification);
87     }
88 
89     /**
90      * This is a wrapper around the new stopForeground method, using the older
91      * APIs if it is not available.
92      */
stopForegroundCompat(int id)93     void stopForegroundCompat(int id) {
94         // If we have the new stopForeground API, then use it.
95         if (mStopForeground != null) {
96             mStopForegroundArgs[0] = Boolean.TRUE;
97             try {
98                 mStopForeground.invoke(this, mStopForegroundArgs);
99             } catch (InvocationTargetException e) {
100                 // Should not happen.
101                 Log.w("ApiDemos", "Unable to invoke stopForeground", e);
102             } catch (IllegalAccessException e) {
103                 // Should not happen.
104                 Log.w("ApiDemos", "Unable to invoke stopForeground", e);
105             }
106             return;
107         }
108 
109         // Fall back on the old API.  Note to cancel BEFORE changing the
110         // foreground state, since we could be killed at that point.
111         mNM.cancel(id);
112         setForeground(false);
113     }
114 
115     @Override
onCreate()116     public void onCreate() {
117         mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
118         try {
119             mStartForeground = getClass().getMethod("startForeground",
120                     mStartForegroundSignature);
121             mStopForeground = getClass().getMethod("stopForeground",
122                     mStopForegroundSignature);
123         } catch (NoSuchMethodException e) {
124             // Running on an older platform.
125             mStartForeground = mStopForeground = null;
126         }
127     }
128 
129     @Override
onDestroy()130     public void onDestroy() {
131         // Make sure our notification is gone.
132         stopForegroundCompat(R.string.foreground_service_started);
133     }
134 // END_INCLUDE(foreground_compatibility)
135 
136 // BEGIN_INCLUDE(start_compatibility)
137     // This is the old onStart method that will be called on the pre-2.0
138     // platform.  On 2.0 or later we override onStartCommand() so this
139     // method will not be called.
140     @Override
onStart(Intent intent, int startId)141     public void onStart(Intent intent, int startId) {
142         handleCommand(intent);
143     }
144 
145     @Override
onStartCommand(Intent intent, int flags, int startId)146     public int onStartCommand(Intent intent, int flags, int startId) {
147         handleCommand(intent);
148         // We want this service to continue running until it is explicitly
149         // stopped, so return sticky.
150         return START_STICKY;
151     }
152 // END_INCLUDE(start_compatibility)
153 
handleCommand(Intent intent)154     void handleCommand(Intent intent) {
155         if (ACTION_FOREGROUND.equals(intent.getAction())) {
156             // In this sample, we'll use the same text for the ticker and the expanded notification
157             CharSequence text = getText(R.string.foreground_service_started);
158 
159             // Set the icon, scrolling text and timestamp
160             Notification notification = new Notification(R.drawable.stat_sample, text,
161                     System.currentTimeMillis());
162 
163             // The PendingIntent to launch our activity if the user selects this notification
164             PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
165                     new Intent(this, Controller.class), 0);
166 
167             // Set the info for the views that show in the notification panel.
168             notification.setLatestEventInfo(this, getText(R.string.local_service_label),
169                            text, contentIntent);
170 
171             startForegroundCompat(R.string.foreground_service_started, notification);
172 
173         } else if (ACTION_BACKGROUND.equals(intent.getAction())) {
174             stopForegroundCompat(R.string.foreground_service_started);
175         }
176     }
177 
178     @Override
onBind(Intent intent)179     public IBinder onBind(Intent intent) {
180         return null;
181     }
182 
183     // ----------------------------------------------------------------------
184 
185     /**
186      * <p>Example of explicitly starting and stopping the {@link ForegroundService}.
187      *
188      * <p>Note that this is implemented as an inner class only keep the sample
189      * all together; typically this code would appear in some separate class.
190      */
191     public static class Controller extends Activity {
192         @Override
onCreate(Bundle savedInstanceState)193         protected void onCreate(Bundle savedInstanceState) {
194             super.onCreate(savedInstanceState);
195 
196             setContentView(R.layout.foreground_service_controller);
197 
198             // Watch for button clicks.
199             Button button = (Button)findViewById(R.id.start_foreground);
200             button.setOnClickListener(mForegroundListener);
201             button = (Button)findViewById(R.id.start_background);
202             button.setOnClickListener(mBackgroundListener);
203             button = (Button)findViewById(R.id.stop);
204             button.setOnClickListener(mStopListener);
205         }
206 
207         private OnClickListener mForegroundListener = new OnClickListener() {
208             public void onClick(View v) {
209                 Intent intent = new Intent(ForegroundService.ACTION_FOREGROUND);
210                 intent.setClass(Controller.this, ForegroundService.class);
211                 startService(intent);
212             }
213         };
214 
215         private OnClickListener mBackgroundListener = new OnClickListener() {
216             public void onClick(View v) {
217                 Intent intent = new Intent(ForegroundService.ACTION_BACKGROUND);
218                 intent.setClass(Controller.this, ForegroundService.class);
219                 startService(intent);
220             }
221         };
222 
223         private OnClickListener mStopListener = new OnClickListener() {
224             public void onClick(View v) {
225                 stopService(new Intent(Controller.this,
226                         ForegroundService.class));
227             }
228         };
229     }
230 }
231