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(); } }

Android Service Note --- Local Service Sample Remote Messenger Service Sample相关推荐

  1. 【Android 进程保活】应用进程拉活 ( 系统 Service 机制拉活 | Service 组件 onStartCommand 方法分析 | 源码资源 )

    文章目录 一. Service 组件 onStartCommand 方法分析 1. onStartCommand 函数返回值分析 2. onStartCommand 函数 START_STICKY_C ...

  2. 【Android 安全】DEX 加密 ( Application 替换 | 分析 Service 组件中调用 getApplication() 获取的 Application 是否替换成功 )

    文章目录 一. Service 中的 getApplication() 方法分析 二. ActivityThread 中的 H 处理 CREATE_SERVICE 消息 三. ActivityThre ...

  3. 降本增效利器!趣头条Spark Remote Shuffle Service最佳实践

    王振华,趣头条大数据总监,趣头条大数据负责人 曹佳清,趣头条大数据离线团队高级研发工程师,曾就职于饿了么大数据INF团队负责存储层和计算层组件研发,目前负责趣头条大数据计算层组件Spark的建设 范振 ...

  4. android Service oncreate 在UI线程 何时用service,何时用thread

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha 服务的生命周期 各个方法 都是在主线程中的. 这里的操作可以导致主线程阻塞. 这些方法, ...

  5. 【Android 进程保活】提升进程优先级 ( 使用前台 Service 提高应用进程优先级 | 启动相同 id 的第二个前台 Service 关闭通知 )

    文章目录 一. 前台 Service 通知问题 二. 设置 startForeground id 参数为 0 三. 启动相同 id 的第二个前台 Service 关闭通知 1. 前台服务 1 2. 关 ...

  6. 【Android 进程保活】提升进程优先级 ( 使用前台 Service 提高应用进程优先级 | 效果展示 | 源码资源 )

    文章目录 一. 使用前台 Service 提高应用进程优先级 1. 前台 Service 代码 2. 前台 Service 代码 3. 启动服务 二.效果展示 三.源码资源 一. 使用前台 Servi ...

  7. Android Studio开发基础之启动Service,并通过从Activity向Service传递数据

    本实例演示启动Service,并通过从Activity向Service传递数据,新建一个Service,并敲如下代码: package com.example.lhb.startservice;imp ...

  8. android 启动服务同时传递数据,Android Studio开发基础之起动Service,并通过从Activity向Service传递数据...

    Android Studio开发基础之启动Service,并通过从Activity向Service传递数据 本实例演示启动Service,并通过从Activity向Service传递数据,新建一个Se ...

  9. android多个activity绑定一个service,8.1.2 绑定Activity和Service

    8.1.2  绑定Activity和Service 本节的例子代码所在的工程目录是src\ch08\ch08_serviceactivity 如果使用8.1.1节介绍的方法启动服务,并且未调用stop ...

最新文章

  1. 让你的silverlight更炫(三):让BusyIndicator更炫
  2. 实例分析C语言中strlen和sizeof的区别
  3. JavaScript解析顺序和变量作用域
  4. python实现微信自动发信息_Python实现智慧-定期向微信女友发送消息,python,智给,定时,发消息...
  5. 将数据传入重定向网页
  6. 面试中get和post的区别
  7. 西游记里学化学,请收下我的膝盖~ | 今日最佳
  8. checkbox 最多选两项
  9. 02 | 日志系统:一条SQL更新语句是如何执行的? 笔记(转)
  10. 导入其他用户的EFS证书
  11. JavaWeb网络考试系统
  12. 小程序手写板电子签名
  13. python天涯帖子_Python爬虫实战(二):爬取天涯帖子(只看楼主)
  14. 解决笔记本电脑有线耳机插入无反应的情况
  15. oracle导出导入同义词,oracle同义词语句备份
  16. 关于所谓U盘有占用空间,却看不到文件的一些看法
  17. 企业金融App评测系列——微众银行以App构筑企业金融服务新生态,成为企业的随身数字银行
  18. 哔哩哔哩2020校园招聘技术类笔试卷(二)
  19. (2022年12月最新)SpringBoot远程代码执行whitelabel error page SpEL RCE漏洞复现
  20. 等保培训.04.主机系统安全测评

热门文章

  1. 从事医院计算机网络管理工作,浅谈医院计算机网络安全管理工作.doc
  2. 毕设demo丨您有一份会议系统App项目请查收!
  3. 机械臂动力学建模(4)- Lagrangian拉格朗日算法
  4. 华章7-8月份新书简介(2017年)
  5. SWT/JFace 同一个Label组件中显示不同的字体和字体颜色
  6. 用pygame写一款RPG游戏
  7. USB驱动之USB网络共享
  8. 神经网络简介--激活函数、网络架构、生物模型解释
  9. 多彩m618plus评测_Delux多彩M618Plus垂直鼠标晒单 使用体验_什么值得买
  10. python-语音识别