原文地址:http://android.blog.51cto.com/268543/527314
作者:Icansoft
public class LocalService extends Service { private static final String TAG = "LocalService"; @Override public IBinder onBind(Intent intent) { Log.i(TAG, "onBind"); return null; } @Override public void onCreate() { Log.i(TAG, "onCreate"); super.onCreate(); } @Override public void onDestroy() { Log.i(TAG, "onDestroy"); super.onDestroy(); } @Override public void onStart(Intent intent, int startId) { Log.i(TAG, "onStart"); super.onStart(intent, startId); } }
public class ServiceActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.servicedemo); ((Button) findViewById(R.id.startLocalService)).setOnClickListener( new View.OnClickListener(){ @Override public void onClick(View view) { // TODO Auto-generated method stub startService(new Intent("com.demo.SERVICE_DEMO")); } }); ((Button) findViewById(R.id.stopLocalService)).setOnClickListener( new View.OnClickListener(){ @Override public void onClick(View view) { // TODO Auto-generated method stub stopService(new Intent("com.demo.SERVICE_DEMO")); } }); } }
<service android:name=".LocalService"> <intent-filter> <action android:name="com.demo.SERVICE_DEMO" /> <category android:name="android.intent.category.default" /> </intent-filter> </service>
/** * This is an example of implementing an application service that runs locally * in the same process as the application. The {@link LocalServiceController} * and {@link LocalServiceBinding} classes show how to interact with the * service. * * <p>Notice the use of the {@link NotificationManager} when interesting things * happen in the service. This is generally how background services should * interact with the user, rather than doing something more disruptive such as * calling startActivity(). */ public class LocalService extends Service { private NotificationManager mNM; /** * Class for clients to access. Because we know this service always * runs in the same process as its clients, we don't need to deal with * IPC. */ public class LocalBinder extends Binder { LocalService getService() { return LocalService.this; } } @Override public void onCreate() { mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); // Display a notification about us starting. We put an icon in the status bar. showNotification(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("LocalService", "Received start id " + startId + ": " + intent); // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; } @Override public void onDestroy() { // Cancel the persistent notification. mNM.cancel(R.string.local_service_started); // Tell the user we stopped. Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show(); } @Override public IBinder onBind(Intent intent) { return mBinder; } // This is the object that receives interactions from clients. See // RemoteService for a more complete example. private final IBinder mBinder = new LocalBinder(); /** * Show a notification while this service is running. */ private void showNotification() { // In this sample, we'll use the same text for the ticker and the expanded notification CharSequence text = getText(R.string.local_service_started); // Set the icon, scrolling text and timestamp Notification notification = new Notification(R.drawable.stat_sample, text, System.currentTimeMillis()); // The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, LocalServiceController.class), 0); // Set the info for the views that show in the notification panel. notification.setLatestEventInfo(this, getText(R.string.local_service_label), text, contentIntent); // Send the notification. // We use a layout id because it is a unique number. We use it later to cancel. mNM.notify(R.string.local_service_started, notification); } }
/** * <p>Example of binding and unbinding to the {@link LocalService}. * This demonstrates the implementation of a service which the client will * bind to, receiving an object through which it can communicate with the service.</p> */ public class LocalServiceBinding extends Activity { private boolean mIsBound; private LocalService mBoundService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.local_service_binding); // Watch for button clicks. Button button = (Button)findViewById(R.id.bind); button.setOnClickListener(mBindListener); button = (Button)findViewById(R.id.unbind); button.setOnClickListener(mUnbindListener); } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. mBoundService = ((LocalService.LocalBinder)service).getService(); // Tell the user about this for our demo. Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected, Toast.LENGTH_SHORT).show(); } public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. // Because it is running in our same process, we should never // see this happen. mBoundService = null; Toast.makeText(LocalServiceBinding.this, R.string.local_service_disconnected, Toast.LENGTH_SHORT).show(); } }; private OnClickListener mBindListener = new OnClickListener() { public void onClick(View v) { // Establish a connection with the service. We use an explicit // class name because we want a specific service implementation that // we know will be running in our own process (and thus won't be // supporting component replacement by other applications). bindService(new Intent(LocalServiceBinding.this, LocalService.class), mConnection, Context.BIND_AUTO_CREATE); mIsBound = true; } }; private OnClickListener mUnbindListener = new OnClickListener() { public void onClick(View v) { if (mIsBound) { // Detach our existing connection. unbindService(mConnection); mIsBound = false; } } }; }
<service android:name=".app.LocalService" /> <activity android:name=".app.LocalServiceBinding" android:label="@string/activity_local_service_binding"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.SAMPLE_CODE" /> </intent-filter> </activity>