Local Service Sample & Remote Messenger Service Sample

来源:互联网 发布:淘宝天猫2015双十一 编辑:程序博客网 时间:2024/06/13 15:22

1.Local Service Sample

 

我在其中的关键步骤加上了打印信息,根据这些log我们可以更好的理解Service和Client是如何联系上的

 

AndroidManifest.xml

 

[java] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.fly.localservice" android:versionCode="1"  
  4.     android:versionName="1.0">  
  5.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  6.         <atcivity android:name="Hello">  
  7.         <intent-filter>  
  8.                   
  9.                 <category android:name="android.intent.category.LAUNCHER" />  
  10.             </intent-filter>  
  11.         </atcivity>  
  12.         <activity android:name="LocalServiceActivities">  
  13.             <intent-filter>  
  14.                 <action android:name="android.intent.action.MAIN" />  
  15.                 <category android:name="android.intent.category.LAUNCHER" />  
  16.             </intent-filter>  
  17.         </activity>  
  18.         <service android:name="LocalService">  
  19.             <intent-filter>  
  20.                 <action android:name="com.fly.localservice" />  
  21.             </intent-filter>  
  22.         </service>  
  23.     </application>  
  24.     <uses-sdk android:minSdkVersion="7" />  

 

LocalService.java

通过LocalBinder类,Client可以通过 在 onServiceConnected 方法 获得Service对象

 

 

 

[java] view plaincopy
  1. package com.fly.localservice;  
  2. import android.app.Notification;  
  3. import android.app.NotificationManager;  
  4. import android.app.PendingIntent;  
  5. import android.app.Service;  
  6. import android.content.Intent;  
  7. import android.os.Binder;  
  8. import android.os.IBinder;  
  9. import android.util.Log;  
  10. import android.widget.Toast;  
  11. public class LocalService extends Service {  
  12.     private final static String TAG = "U0fly LocalService ====>";  
  13.     private NotificationManager mNM;  
  14.     /** 
  15.      * Class for clients to access.  Because we know this service always 
  16.      * runs in the same process as its clients, we don't need to deal with 
  17.      * IPC. 
  18.      */  
  19.     public class LocalBinder extends Binder {  
  20.         LocalService getService() {  
  21.             Log.d(TAG, "getService");  
  22.             return LocalService.this;  
  23.         }  
  24.     }  
  25.     @Override  
  26.     public void onCreate() {  
  27.         Log.d(TAG, "onCreate");  
  28.         mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);  
  29.         // Display a notification about us starting.  We put an icon in the status bar.  
  30.         showNotification();  
  31.     }  
  32.     @Override  
  33.     public int onStartCommand(Intent intent, int flags, int startId) {  
  34.         Log.i("LocalService""Received start id " + startId + ": " + intent);  
  35.         // We want this service to continue running until it is explicitly  
  36.         // stopped, so return sticky.  
  37.         return START_STICKY;  
  38.     }  
  39.     @Override  
  40.     public void onDestroy() {  
  41.         Log.d(TAG, "onDestroy");  
  42.         // Cancel the persistent notification.  
  43.         mNM.cancel(R.string.local_service_started);  
  44.         // Tell the user we stopped.  
  45.         Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();  
  46.     }  
  47.     @Override  
  48.     public IBinder onBind(Intent intent) {  
  49.         Log.d(TAG, "onBind");  
  50.         return mBinder;  
  51.     }  
  52.     // This is the object that receives interactions from clients.  See  
  53.     // RemoteService for a more complete example.  
  54.     private final IBinder mBinder = new LocalBinder();  
  55.     /** 
  56.      * Show a notification while this service is running. 
  57.      */  
  58.     private void showNotification() {  
  59.         // In this sample, we'll use the same text for the ticker and the expanded notification  
  60.         CharSequence text = getText(R.string.local_service_started);  
  61.         // Set the icon, scrolling text and timestamp  
  62.         Notification notification = new Notification(R.drawable.icon, text,  
  63.                 System.currentTimeMillis());  
  64.         // The PendingIntent to launch our activity if the user selects this notification  
  65.   /*******************************************************/  
  66.         //i don't know this error ???????  
  67.     /*******************************************************/     
  68. /*        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
  69.                  new Intent(this, LocalServiceActivities.Controller.class), 0);*/  
  70.               
  71.         /*it is just a test !!!!!!*/  
  72.           
  73.         PendingIntent contentIntent = PendingIntent.getActivity(this0,  
  74.                 new Intent(this, Hello.class), 0);  
  75.           
  76.           
  77.           
  78.         // Set the info for the views that show in the notification panel.  
  79.         notification.setLatestEventInfo(this, getText(R.string.local_service_label),  
  80.                        text, contentIntent);  
  81.         // Send the notification.  
  82.         // We use a layout id because it is a unique number.  We use it later to cancel.  
  83.         mNM.notify(R.string.local_service_started, notification);  
  84.     }  
  85. }  

 

LocalServiceActivities.java

 

 

mBoundService = ((LocalService.LocalBinder)service).getService();

通过 bindService(new Intent("com.fly.localservice"), mConnection,Context.BIND_AUTO_CREATE);

可以将两者联系上

 

[java] view plaincopy
  1. package com.fly.localservice;  
  2. import android.app.Activity;  
  3. import android.content.ComponentName;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.content.ServiceConnection;  
  7. import android.os.Bundle;  
  8. import android.os.IBinder;  
  9. import android.util.Log;  
  10. import android.widget.Toast;  
  11. public class LocalServiceActivities extends Activity {  
  12.     private final static String TAG = "U0fly LocalServiceActivities ====>";  
  13.     private LocalService mBoundService;  
  14.     private boolean mIsBound;  
  15.       
  16.     private ServiceConnection mConnection = new ServiceConnection() {  
  17.           
  18.         public void onServiceConnected(ComponentName className, IBinder service) {  
  19.             Log.d(TAG, "onServiceConnected");  
  20.             // This is called when the connection with the service has been  
  21.             // established, giving us the service object we can use to  
  22.             // interact with the service.  Because we have bound to a explicit  
  23.             // service that we know is running in our own process, we can  
  24.             // cast its IBinder to a concrete class and directly access it.  
  25.             mBoundService = ((LocalService.LocalBinder)service).getService();  
  26.             // Tell the user about this for our demo.  
  27.             Toast.makeText(mBoundService, R.string.local_service_connected,  
  28.                     Toast.LENGTH_SHORT).show();  
  29.              
  30.         }  
  31.         public void onServiceDisconnected(ComponentName className) {  
  32.             Log.d(TAG, "onServiceDisconnected");  
  33.             // This is called when the connection with the service has been  
  34.             // unexpectedly disconnected -- that is, its process crashed.  
  35.             // Because it is running in our same process, we should never  
  36.             // see this happen.  
  37.             mBoundService = null;  
  38.             Toast.makeText(mBoundService, R.string.local_service_disconnected,  
  39.                     Toast.LENGTH_SHORT).show();  
  40.         }  
  41.     };  
  42.     void doBindService() {  
  43.          Log.d(TAG, "doBindService");  
  44.         // Establish a connection with the service.  We use an explicit  
  45.         // class name because we want a specific service implementation that  
  46.         // we know will be running in our own process (and thus won't be  
  47.         // supporting component replacement by other applications).  
  48.            
  49.         //this method can not work!!!!!!!!!!!!!!!!!!!!!!!??????????????????   
  50.            
  51.     /*  bindService(new Intent(mBoundService, LocalService.class), mConnection, 
  52.                 Context.BIND_AUTO_CREATE);*/  
  53.           
  54.         /***************************************************/  
  55.         /*or use this method below, it is ok !!!!!!!!!!*/  
  56.           
  57.         bindService(new Intent("com.fly.localservice"), mConnection,  
  58.                 Context.BIND_AUTO_CREATE);  
  59.         /****************************************************/  
  60.         mIsBound = true;  
  61.     }  
  62.     void doUnbindService() {  
  63.          Log.d(TAG, "doUnbindService");  
  64.         if (mIsBound) {  
  65.             // Detach our existing connection.  
  66.             unbindService(mConnection);  
  67.             mIsBound = false;  
  68.         }  
  69.     }  
  70.     @Override  
  71.     protected void onDestroy() {  
  72.         Log.d(TAG, "onDestroy");  
  73.         super.onDestroy();  
  74.         doUnbindService();  
  75.     }  
  76.       
  77.     /** Called when the activity is first created. */  
  78.     @Override  
  79.     public void onCreate(Bundle savedInstanceState) {  
  80.         super.onCreate(savedInstanceState);  
  81.         setContentView(R.layout.main);  
  82.          
  83.         Log.d(TAG, "onCreate");  
  84.         this.doBindService();  
  85.           
  86.           
  87.     }  
  88. }  

 

测试结果:

 

上面我们只是看清了整个大体流程,并没有在Service中做些什么,

 

So 我们可以用另外一个Activity通过 startService 和 stopService 来 启动 和关闭 Service

 

让我们更加主动和智能一些,:-)

 

[java] view plaincopy
  1. package com.fly.localservice;  
  2. import android.app.Activity;  
  3. import android.content.Intent;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.widget.Button;  
  8. public class Hello extends Activity implements OnClickListener {  
  9.     private final static String TAG = "U0fly Hello ==>";  
  10.     private Button Btn1, Btn2;  
  11.     /** Called when the activity is first created. */  
  12.     @Override  
  13.     public void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.hellolayout);  
  16.         initUI();  
  17.     }  
  18.     private void initUI() {  
  19.         // TODO Auto-generated method stub  
  20.         Btn1 = (Button) findViewById(R.id.Button01);  
  21.         Btn2 = (Button) findViewById(R.id.Button02);  
  22.         Btn1.setOnClickListener(this);  
  23.         Btn2.setOnClickListener(this);  
  24.     }  
  25.     @Override  
  26.     public void onClick(View v) {  
  27.         // TODO Auto-generated method stub  
  28.         switch (v.getId()) {  
  29.         case R.id.Button01:  
  30.             this.startService(new Intent(this, LocalService.class));  
  31.             break;  
  32.         case R.id.Button02:  
  33.             this.stopService(new Intent(this, LocalService.class));  
  34.             break;  
  35.         }  
  36.     }  
  37. }  

 

 

点击startService, 开启服务,点击stopService,关闭服务

 

 

 

 

 

2.RemoteMessengerServiceSample

 

Service 和 Client 还可以通过handleMessage 互相发送消息

 

AndroidManifest.xml

 

添加 android:process=":remote" 可以让服务在远程进程中运行

 

[xhtml] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="com.fly.RemoteMessengerServiceSample"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.         <activity android:name=".MyActivity"  
  8.                   android:label="@string/app_name">  
  9.             <intent-filter>  
  10.                 <action android:name="android.intent.action.MAIN" />  
  11.                 <category android:name="android.intent.category.LAUNCHER" />  
  12.             </intent-filter>  
  13.         </activity>  
  14.         <service android:name="MessengerService" android:process=":remote">  
  15.             <intent-filter>  
  16.                 <action android:name="com.fly.RemoteMessengerServiceSample"/>  
  17.             </intent-filter>  
  18.         </service>  
  19.     </application>  
  20.     <uses-sdk android:minSdkVersion="7" />  
  21. </manifest>   

 

 

MessengerService.java

 

[java] view plaincopy
  1. package com.fly.RemoteMessengerServiceSample;  
  2. import java.util.ArrayList;  
  3. import android.app.Notification;  
  4. import android.app.NotificationManager;  
  5. import android.app.PendingIntent;  
  6. import android.app.Service;  
  7. import android.content.Intent;  
  8. import android.os.Handler;  
  9. import android.os.IBinder;  
  10. import android.os.Message;  
  11. import android.os.Messenger;  
  12. import android.os.RemoteException;  
  13. import android.util.Log;  
  14. import android.widget.Toast;  
  15. public class MessengerService extends Service {  
  16.     
  17.     private final static String TAG = "U0fly MessengerService ===>";  
  18.       
  19.     /** For showing and hiding our notification. */  
  20.       NotificationManager mNM;  
  21.     /** Keeps track of all current registered clients. */  
  22.     ArrayList<Messenger> mClients = new ArrayList<Messenger>();  
  23.     /** Holds last value set by a client. */  
  24.     int mValue = 0;  
  25.     /** 
  26.      * Command to the service to register a client, receiving callbacks 
  27.      * from the service.  The Message's replyTo field must be a Messenger of 
  28.      * the client where callbacks should be sent. 
  29.      */  
  30.     static final int MSG_REGISTER_CLIENT = 1;  
  31.     /** 
  32.      * Command to the service to unregister a client, ot stop receiving callbacks 
  33.      * from the service.  The Message's replyTo field must be a Messenger of 
  34.      * the client as previously given with MSG_REGISTER_CLIENT. 
  35.      */  
  36.     static final int MSG_UNREGISTER_CLIENT = 2;  
  37.     /** 
  38.      * Command to service to set a new value.  This can be sent to the 
  39.      * service to supply a new value, and will be sent by the service to 
  40.      * any registered clients with the new value. 
  41.      */  
  42.     static final int MSG_SET_VALUE = 3;  
  43.     /** 
  44.      * Handler of incoming messages from clients. 
  45.      */  
  46.     class IncomingHandler extends Handler {  
  47.         @Override  
  48.         public void handleMessage(Message msg) {  
  49.             switch (msg.what) {  
  50.                 case MSG_REGISTER_CLIENT:  
  51.                     mClients.add(msg.replyTo);  
  52.                     break;  
  53.                 case MSG_UNREGISTER_CLIENT:  
  54.                     mClients.remove(msg.replyTo);  
  55.                     break;  
  56.                 case MSG_SET_VALUE:  
  57.                     mValue = msg.arg1;  
  58.                     for (int i=mClients.size()-1; i>=0; i--) {  
  59.                         try {  
  60.                             mClients.get(i).send(Message.obtain(null,  
  61.                                     MSG_SET_VALUE, mValue, 0));  
  62.                         } catch (RemoteException e) {  
  63.                             // The client is dead.  Remove it from the list;  
  64.                             // we are going through the list from back to front  
  65.                             // so this is safe to do inside the loop.  
  66.                             mClients.remove(i);  
  67.                         }  
  68.                     }  
  69.                     break;  
  70.                 default:  
  71.                     super.handleMessage(msg);  
  72.             }  
  73.         }  
  74.     }  
  75.     /** 
  76.      * Target we publish for clients to send messages to IncomingHandler. 
  77.      */  
  78.     final Messenger mMessenger = new Messenger(new IncomingHandler());  
  79.     @Override  
  80.     public void onCreate() {  
  81.         Log.d(TAG, "onCreate");  
  82.          
  83.         //this will make error ????? why ?????   
  84.         mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);  
  85.         Log.d(TAG, "onCreate111");  
  86.         // Display a notification about us starting.  
  87.         showNotification();  
  88.         Log.d(TAG, "onCreate222");  
  89.     }  
  90.     @Override  
  91.     public void onDestroy() {  
  92.         Log.d(TAG, "onDestroy");  
  93.         // Cancel the persistent notification.  
  94.        mNM.cancel(R.string.remote_service_started);  
  95.         // Tell the user we stopped.  
  96.         Toast.makeText(this, R.string.remote_service_stopped, Toast.LENGTH_SHORT).show();  
  97.     }  
  98.     /** 
  99.      * When binding to the service, we return an interface to our messenger 
  100.      * for sending messages to the service. 
  101.      */  
  102.     @Override  
  103.     public IBinder onBind(Intent intent) {  
  104.         Log.d(TAG, "onBind");  
  105.         return mMessenger.getBinder();  
  106.     }  
  107.     /** 
  108.      * Show a notification while this service is running. 
  109.      */  
  110.     private void showNotification() {  
  111.         // In this sample, we'll use the same text for the ticker and the expanded notification  
  112.         CharSequence text = getText(R.string.remote_service_started);  
  113.         // Set the icon, scrolling text and timestamp  
  114.         Notification notification = new Notification(R.drawable.icon, text,  
  115.                 System.currentTimeMillis());  
  116.         // The PendingIntent to launch our activity if the user selects this notification  
  117.        /* PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
  118.                 new Intent(this, Controller.class), 0); 
  119. */  
  120.         PendingIntent contentIntent = PendingIntent.getActivity(this0,  
  121.                 new Intent(this, Hello.class), 0);  
  122.           
  123.         // Set the info for the views that show in the notification panel.  
  124.         notification.setLatestEventInfo(this, getText(R.string.remote_service_label),  
  125.                        text, contentIntent);  
  126.         // Send the notification.  
  127.         // We use a string id because it is a unique number.  We use it later to cancel.  
  128.         mNM.notify(R.string.remote_service_started, notification);  
  129.     }  
  130. }  

 

MyActivity.java

 

[java] view plaincopy
  1. package com.fly.RemoteMessengerServiceSample;  
  2. import android.app.Activity;  
  3. import android.content.ComponentName;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.content.ServiceConnection;  
  7. import android.os.Bundle;  
  8. import android.os.Handler;  
  9. import android.os.IBinder;  
  10. import android.os.Message;  
  11. import android.os.Messenger;  
  12. import android.os.RemoteException;  
  13. import android.util.Log;  
  14. import android.widget.TextView;  
  15. public class MyActivity extends Activity {  
  16.     private final static String TAG = "U0fly MyActivity ===>";  
  17.     /** Messenger for communicating with service. */  
  18.     Messenger mService = null;  
  19.     /** Flag indicating whether we have called bind on the service. */  
  20.     boolean mIsBound;  
  21.     /** Some text view we are using to show state information. */  
  22.     TextView mCallbackText;  
  23.   
  24.       
  25.     /** 
  26.      * Handler of incoming messages from service. 
  27.      */  
  28.     class IncomingHandler extends Handler {  
  29.         @Override  
  30.         public void handleMessage(Message msg) {  
  31.             switch (msg.what) {  
  32.             case MessengerService.MSG_SET_VALUE:  
  33.                 mCallbackText.setText("Received from service: " + msg.arg1);  
  34.                 break;  
  35.             default:  
  36.                 super.handleMessage(msg);  
  37.             }  
  38.         }  
  39.     }  
  40.     /** 
  41.      * Target we publish for clients to send messages to IncomingHandler. 
  42.      */  
  43.     final Messenger mMessenger = new Messenger(new IncomingHandler());  
  44.     /** 
  45.      * Class for interacting with the main interface of the service. 
  46.      */  
  47.     private ServiceConnection mConnection = new ServiceConnection() {  
  48.         public void onServiceConnected(ComponentName className, IBinder service) {  
  49.             Log.d(TAG, "onServiceConnected");  
  50.             // This is called when the connection with the service has been  
  51.             // established, giving us the service object we can use to  
  52.             // interact with the service. We are communicating with our  
  53.             // service through an IDL interface, so get a client-side  
  54.             // representation of that from the raw service object.  
  55.             mService = new Messenger(service);  
  56.             try {  
  57.                 Thread.sleep(3000);  
  58.             } catch (InterruptedException e) {  
  59.                 // TODO Auto-generated catch block  
  60.                 e.printStackTrace();  
  61.             }  
  62.             mCallbackText.setText("Attached.");  
  63.               
  64.             // We want to monitor the service for as long as we are  
  65.             // connected to it.  
  66.             try {  
  67.                 Message msg = Message.obtain(null,  
  68.                         MessengerService.MSG_REGISTER_CLIENT);  
  69.                 msg.replyTo = mMessenger;  
  70.                 mService.send(msg);  
  71.                   
  72.                   
  73.                 // Give it some value as an example.  
  74.             /*  msg = Message.obtain(null, MessengerService.MSG_SET_VALUE, 
  75.                         this.hashCode(), 0);*/  
  76.                   
  77.                 /*****just a test by fly*****/  
  78.                 msg = Message.obtain(null, MessengerService.MSG_SET_VALUE,  
  79.                         30);  
  80.                   
  81.                   
  82.                   
  83.                 mService.send(msg);  
  84.             } catch (RemoteException e) {  
  85.                 // In this case the service has crashed before we could even  
  86.                 // do anything with it; we can count on soon being  
  87.                 // disconnected (and then reconnected if it can be restarted)  
  88.                 // so there is no need to do anything here.  
  89.             }  
  90.             // As part of the sample, tell the user what happened.  
  91.             /* 
  92.              * Toast.makeText(mService, R.string.remote_service_connected, 
  93.              * Toast.LENGTH_SHORT).show(); 
  94.              */  
  95.         }  
  96.         public void onServiceDisconnected(ComponentName className) {  
  97.             Log.d(TAG, "onServiceDisconnected");  
  98.             // This is called when the connection with the service has been  
  99.             // unexpectedly disconnected -- that is, its process crashed.  
  100.             mService = null;  
  101.             mCallbackText.setText("Disconnected.");  
  102.             // As part of the sample, tell the user what happened.  
  103.             /* 
  104.              * Toast.makeText(mService, R.string.remote_service_disconnected, 
  105.              * Toast.LENGTH_SHORT).show(); 
  106.              */  
  107.         }  
  108.     };  
  109.     void doBindService() {  
  110.         Log.d(TAG, "doBindService");  
  111.         // Establish a connection with the service. We use an explicit  
  112.         // class name because there is no reason to be able to let other  
  113.         // applications replace our component.  
  114.         bindService(new Intent("com.fly.RemoteMessengerServiceSample"),  
  115.                 mConnection, Context.BIND_AUTO_CREATE);  
  116.         Log.d(TAG, "doBindService 111");  
  117.         mIsBound = true;  
  118.         Log.d(TAG, "doBindService 222");  
  119.         mCallbackText.setText("Binding.");  
  120.     }  
  121.     void doUnbindService() {  
  122.         Log.d(TAG, "doUnbindService");  
  123.         if (mIsBound) {  
  124.             // If we have received the service, and hence registered with  
  125.             // it, then now is the time to unregister.  
  126.             if (mService != null) {  
  127.                 try {  
  128.                     Message msg = Message.obtain(null,  
  129.                             MessengerService.MSG_UNREGISTER_CLIENT);  
  130.                     msg.replyTo = mMessenger;  
  131.                     mService.send(msg);  
  132.                 } catch (RemoteException e) {  
  133.                     // There is nothing special we need to do if the service  
  134.                     // has crashed.  
  135.                 }  
  136.             }  
  137.             // Detach our existing connection.  
  138.             unbindService(mConnection);  
  139.             mIsBound = false;  
  140.             mCallbackText.setText("Unbinding.");  
  141.         }  
  142.     }  
  143.       
  144.     @Override  
  145.     protected void onDestroy() {  
  146.         Log.d(TAG, "onDestroy");  
  147.         super.onDestroy();  
  148.         doUnbindService();  
  149.     }  
  150.       
  151.     /** Called when the activity is first created. */  
  152.     @Override  
  153.     public void onCreate(Bundle savedInstanceState) {  
  154.         super.onCreate(savedInstanceState);  
  155.         setContentView(R.layout.main);  
  156.         Log.d(TAG, "onCreate");  
  157.         mCallbackText = (TextView)findViewById(R.id.textview);  
  158.           
  159.         this.doBindService();  
  160.     }  
  161. }  

原创粉丝点击