Local Service Sample & Remote Messenger Service Sample
来源:互联网 发布:淘宝天猫2015双十一 编辑:程序博客网 时间:2024/06/13 15:22
1.Local Service Sample
我在其中的关键步骤加上了打印信息,根据这些log我们可以更好的理解Service和Client是如何联系上的
AndroidManifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.fly.localservice" android:versionCode="1"
- android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <atcivity android:name="Hello">
- <intent-filter>
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </atcivity>
- <activity android:name="LocalServiceActivities">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <service android:name="LocalService">
- <intent-filter>
- <action android:name="com.fly.localservice" />
- </intent-filter>
- </service>
- </application>
- <uses-sdk android:minSdkVersion="7" />
LocalService.java
通过LocalBinder类,Client可以通过 在 onServiceConnected 方法 获得Service对象
- package com.fly.localservice;
- import android.app.Notification;
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.app.Service;
- import android.content.Intent;
- import android.os.Binder;
- import android.os.IBinder;
- import android.util.Log;
- import android.widget.Toast;
- public class LocalService extends Service {
- private final static String TAG = "U0fly LocalService ====>";
- 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() {
- Log.d(TAG, "getService");
- return LocalService.this;
- }
- }
- @Override
- public void onCreate() {
- Log.d(TAG, "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() {
- Log.d(TAG, "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) {
- Log.d(TAG, "onBind");
- 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.icon, text,
- System.currentTimeMillis());
- // The PendingIntent to launch our activity if the user selects this notification
- /*******************************************************/
- //i don't know this error ???????
- /*******************************************************/
- /* PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
- new Intent(this, LocalServiceActivities.Controller.class), 0);*/
- /*it is just a test !!!!!!*/
- PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
- new Intent(this, Hello.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);
- }
- }
LocalServiceActivities.java
mBoundService = ((LocalService.LocalBinder)service).getService();
通过 bindService(new Intent("com.fly.localservice"), mConnection,Context.BIND_AUTO_CREATE);
可以将两者联系上
- package com.fly.localservice;
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.content.ServiceConnection;
- import android.os.Bundle;
- import android.os.IBinder;
- import android.util.Log;
- import android.widget.Toast;
- public class LocalServiceActivities extends Activity {
- private final static String TAG = "U0fly LocalServiceActivities ====>";
- private LocalService mBoundService;
- private boolean mIsBound;
- private ServiceConnection mConnection = new ServiceConnection() {
- public void onServiceConnected(ComponentName className, IBinder service) {
- Log.d(TAG, "onServiceConnected");
- // 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(mBoundService, R.string.local_service_connected,
- Toast.LENGTH_SHORT).show();
- }
- public void onServiceDisconnected(ComponentName className) {
- Log.d(TAG, "onServiceDisconnected");
- // 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(mBoundService, R.string.local_service_disconnected,
- Toast.LENGTH_SHORT).show();
- }
- };
- void doBindService() {
- Log.d(TAG, "doBindService");
- // 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).
- //this method can not work!!!!!!!!!!!!!!!!!!!!!!!??????????????????
- /* bindService(new Intent(mBoundService, LocalService.class), mConnection,
- Context.BIND_AUTO_CREATE);*/
- /***************************************************/
- /*or use this method below, it is ok !!!!!!!!!!*/
- bindService(new Intent("com.fly.localservice"), mConnection,
- Context.BIND_AUTO_CREATE);
- /****************************************************/
- mIsBound = true;
- }
- void doUnbindService() {
- Log.d(TAG, "doUnbindService");
- if (mIsBound) {
- // Detach our existing connection.
- unbindService(mConnection);
- mIsBound = false;
- }
- }
- @Override
- protected void onDestroy() {
- Log.d(TAG, "onDestroy");
- super.onDestroy();
- doUnbindService();
- }
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Log.d(TAG, "onCreate");
- this.doBindService();
- }
- }
测试结果:
上面我们只是看清了整个大体流程,并没有在Service中做些什么,
So 我们可以用另外一个Activity通过 startService 和 stopService 来 启动 和关闭 Service
让我们更加主动和智能一些,:-)
- package com.fly.localservice;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class Hello extends Activity implements OnClickListener {
- private final static String TAG = "U0fly Hello ==>";
- private Button Btn1, Btn2;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.hellolayout);
- initUI();
- }
- private void initUI() {
- // TODO Auto-generated method stub
- Btn1 = (Button) findViewById(R.id.Button01);
- Btn2 = (Button) findViewById(R.id.Button02);
- Btn1.setOnClickListener(this);
- Btn2.setOnClickListener(this);
- }
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- switch (v.getId()) {
- case R.id.Button01:
- this.startService(new Intent(this, LocalService.class));
- break;
- case R.id.Button02:
- this.stopService(new Intent(this, LocalService.class));
- break;
- }
- }
- }
点击startService, 开启服务,点击stopService,关闭服务
2.RemoteMessengerServiceSample
Service 和 Client 还可以通过handleMessage 互相发送消息
AndroidManifest.xml
添加 android:process=":remote" 可以让服务在远程进程中运行
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.fly.RemoteMessengerServiceSample"
- android:versionCode="1"
- android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".MyActivity"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <service android:name="MessengerService" android:process=":remote">
- <intent-filter>
- <action android:name="com.fly.RemoteMessengerServiceSample"/>
- </intent-filter>
- </service>
- </application>
- <uses-sdk android:minSdkVersion="7" />
- </manifest>
MessengerService.java
- package com.fly.RemoteMessengerServiceSample;
- import java.util.ArrayList;
- import android.app.Notification;
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.app.Service;
- import android.content.Intent;
- import android.os.Handler;
- import android.os.IBinder;
- import android.os.Message;
- import android.os.Messenger;
- import android.os.RemoteException;
- import android.util.Log;
- import android.widget.Toast;
- public class MessengerService extends Service {
- private final static String TAG = "U0fly MessengerService ===>";
- /** For showing and hiding our notification. */
- NotificationManager mNM;
- /** Keeps track of all current registered clients. */
- ArrayList<Messenger> mClients = new ArrayList<Messenger>();
- /** Holds last value set by a client. */
- int mValue = 0;
- /**
- * Command to the service to register a client, receiving callbacks
- * from the service. The Message's replyTo field must be a Messenger of
- * the client where callbacks should be sent.
- */
- static final int MSG_REGISTER_CLIENT = 1;
- /**
- * Command to the service to unregister a client, ot stop receiving callbacks
- * from the service. The Message's replyTo field must be a Messenger of
- * the client as previously given with MSG_REGISTER_CLIENT.
- */
- static final int MSG_UNREGISTER_CLIENT = 2;
- /**
- * Command to service to set a new value. This can be sent to the
- * service to supply a new value, and will be sent by the service to
- * any registered clients with the new value.
- */
- static final int MSG_SET_VALUE = 3;
- /**
- * Handler of incoming messages from clients.
- */
- class IncomingHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_REGISTER_CLIENT:
- mClients.add(msg.replyTo);
- break;
- case MSG_UNREGISTER_CLIENT:
- mClients.remove(msg.replyTo);
- break;
- case MSG_SET_VALUE:
- mValue = msg.arg1;
- for (int i=mClients.size()-1; i>=0; i--) {
- try {
- mClients.get(i).send(Message.obtain(null,
- MSG_SET_VALUE, mValue, 0));
- } catch (RemoteException e) {
- // The client is dead. Remove it from the list;
- // we are going through the list from back to front
- // so this is safe to do inside the loop.
- mClients.remove(i);
- }
- }
- break;
- default:
- super.handleMessage(msg);
- }
- }
- }
- /**
- * Target we publish for clients to send messages to IncomingHandler.
- */
- final Messenger mMessenger = new Messenger(new IncomingHandler());
- @Override
- public void onCreate() {
- Log.d(TAG, "onCreate");
- //this will make error ????? why ?????
- mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
- Log.d(TAG, "onCreate111");
- // Display a notification about us starting.
- showNotification();
- Log.d(TAG, "onCreate222");
- }
- @Override
- public void onDestroy() {
- Log.d(TAG, "onDestroy");
- // Cancel the persistent notification.
- mNM.cancel(R.string.remote_service_started);
- // Tell the user we stopped.
- Toast.makeText(this, R.string.remote_service_stopped, Toast.LENGTH_SHORT).show();
- }
- /**
- * When binding to the service, we return an interface to our messenger
- * for sending messages to the service.
- */
- @Override
- public IBinder onBind(Intent intent) {
- Log.d(TAG, "onBind");
- return mMessenger.getBinder();
- }
- /**
- * 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.remote_service_started);
- // Set the icon, scrolling text and timestamp
- Notification notification = new Notification(R.drawable.icon, text,
- System.currentTimeMillis());
- // The PendingIntent to launch our activity if the user selects this notification
- /* PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
- new Intent(this, Controller.class), 0);
- */
- PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
- new Intent(this, Hello.class), 0);
- // Set the info for the views that show in the notification panel.
- notification.setLatestEventInfo(this, getText(R.string.remote_service_label),
- text, contentIntent);
- // Send the notification.
- // We use a string id because it is a unique number. We use it later to cancel.
- mNM.notify(R.string.remote_service_started, notification);
- }
- }
MyActivity.java
- package com.fly.RemoteMessengerServiceSample;
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.content.ServiceConnection;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.IBinder;
- import android.os.Message;
- import android.os.Messenger;
- import android.os.RemoteException;
- import android.util.Log;
- import android.widget.TextView;
- public class MyActivity extends Activity {
- private final static String TAG = "U0fly MyActivity ===>";
- /** Messenger for communicating with service. */
- Messenger mService = null;
- /** Flag indicating whether we have called bind on the service. */
- boolean mIsBound;
- /** Some text view we are using to show state information. */
- TextView mCallbackText;
- /**
- * Handler of incoming messages from service.
- */
- class IncomingHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MessengerService.MSG_SET_VALUE:
- mCallbackText.setText("Received from service: " + msg.arg1);
- break;
- default:
- super.handleMessage(msg);
- }
- }
- }
- /**
- * Target we publish for clients to send messages to IncomingHandler.
- */
- final Messenger mMessenger = new Messenger(new IncomingHandler());
- /**
- * Class for interacting with the main interface of the service.
- */
- private ServiceConnection mConnection = new ServiceConnection() {
- public void onServiceConnected(ComponentName className, IBinder service) {
- Log.d(TAG, "onServiceConnected");
- // 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. We are communicating with our
- // service through an IDL interface, so get a client-side
- // representation of that from the raw service object.
- mService = new Messenger(service);
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- mCallbackText.setText("Attached.");
- // We want to monitor the service for as long as we are
- // connected to it.
- try {
- Message msg = Message.obtain(null,
- MessengerService.MSG_REGISTER_CLIENT);
- msg.replyTo = mMessenger;
- mService.send(msg);
- // Give it some value as an example.
- /* msg = Message.obtain(null, MessengerService.MSG_SET_VALUE,
- this.hashCode(), 0);*/
- /*****just a test by fly*****/
- msg = Message.obtain(null, MessengerService.MSG_SET_VALUE,
- 3, 0);
- mService.send(msg);
- } catch (RemoteException e) {
- // In this case the service has crashed before we could even
- // do anything with it; we can count on soon being
- // disconnected (and then reconnected if it can be restarted)
- // so there is no need to do anything here.
- }
- // As part of the sample, tell the user what happened.
- /*
- * Toast.makeText(mService, R.string.remote_service_connected,
- * Toast.LENGTH_SHORT).show();
- */
- }
- public void onServiceDisconnected(ComponentName className) {
- Log.d(TAG, "onServiceDisconnected");
- // This is called when the connection with the service has been
- // unexpectedly disconnected -- that is, its process crashed.
- mService = null;
- mCallbackText.setText("Disconnected.");
- // As part of the sample, tell the user what happened.
- /*
- * Toast.makeText(mService, R.string.remote_service_disconnected,
- * Toast.LENGTH_SHORT).show();
- */
- }
- };
- void doBindService() {
- Log.d(TAG, "doBindService");
- // Establish a connection with the service. We use an explicit
- // class name because there is no reason to be able to let other
- // applications replace our component.
- bindService(new Intent("com.fly.RemoteMessengerServiceSample"),
- mConnection, Context.BIND_AUTO_CREATE);
- Log.d(TAG, "doBindService 111");
- mIsBound = true;
- Log.d(TAG, "doBindService 222");
- mCallbackText.setText("Binding.");
- }
- void doUnbindService() {
- Log.d(TAG, "doUnbindService");
- if (mIsBound) {
- // If we have received the service, and hence registered with
- // it, then now is the time to unregister.
- if (mService != null) {
- try {
- Message msg = Message.obtain(null,
- MessengerService.MSG_UNREGISTER_CLIENT);
- msg.replyTo = mMessenger;
- mService.send(msg);
- } catch (RemoteException e) {
- // There is nothing special we need to do if the service
- // has crashed.
- }
- }
- // Detach our existing connection.
- unbindService(mConnection);
- mIsBound = false;
- mCallbackText.setText("Unbinding.");
- }
- }
- @Override
- protected void onDestroy() {
- Log.d(TAG, "onDestroy");
- super.onDestroy();
- doUnbindService();
- }
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Log.d(TAG, "onCreate");
- mCallbackText = (TextView)findViewById(R.id.textview);
- this.doBindService();
- }
- }
- Local Service Sample & Remote Messenger Service Sample
- Android 学习笔记 Service (二) Remote Service Sample
- Simple Windows Service Sample
- Simple Windows Service Sample
- Indexing Service simple sample
- Android service sample (2015.12.3)
- local service and remote service(AIDL Service)
- Local Service and Remote Service[Android]
- SQLServer2005 Reporting Service - AdventureWork Sample Report配置
- Local image preview sample
- Remote Service 和 Local App的交互
- 彻底搞懂AIDL,local service和remote service
- sample
- !!!sample
- sample
- soapui中文操作手册(七)----Web Service Sample Project
- soapui中文操作手册(七)----Web Service Sample Project
- Android - local storage & UserTable sample
- 迪米特法则
- java泛型与类型擦除
- 热备份 所有数据文件损坏的恢复
- GCC源代码阅读
- html 输入控件限制
- Local Service Sample & Remote Messenger Service Sample
- GCC精彩之旅
- 后台的验证码不显示本地正常
- GCC Inline ASM GCC内联汇编
- GCC编译的背后( 预处理和编译 汇编和链接 )
- 这几天写了个LZW压缩算法
- gcc教程(转)
- 浏览器闪动效果(标题+内容)
- gcc 使用教程