Service概念及用途:
Android中的服务,它与Activity不同,它是不能与用户交互的,不能自己启动的,运行在后台的程序,如果我们退出应用时,Service进程并没有结束,它仍然在后台运行,那我们什么时候会用到Service呢?比如我们播放音乐的时候,有可能想边听音乐边干些其他事情,当我们退出播放音乐的应用,如果不用Service,我们就听不到歌了,所以这时候就得用到Service了,又比如当我们一个应用的数据是通过网络获取的,不同时间(一段时间)的数据是不同的这时候我们可以用Service在后台定时更新,而不用每打开应用的时候在去获取。
Service生命周期 :
Android Service的生命周期并不像Activity那么复杂,它只继承了onCreate(),onStart(),onDestroy()三个方法,当我们第一次启动Service时,先后调用了onCreate(),onStart()这两个方法,当停止Service时,则执行onDestroy()方法,这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法。
Service与Activity通信:
Service后端的数据最终还是要呈现在前端Activity之上的,因为启动Service时,系统会重新开启一个新的进程,这就涉及到不同进程间通信的问题了(AIDL),当我们想获取启动的Service实例时,我们可以用到bindService和unBindService方法,它们分别执行了Service中IBinder()和onUnbind()方法。
1、添加一个类,在MainActivity所在包之下
<Button android:id="@+id/startservice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="startService" />
<Button android:id="@+id/stopservice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="stopService" />
<Button android:id="@+id/bindservice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="bindService" />
<Button android:id="@+id/unbindservice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="unbindService" />
startServiceButton = (Button) findViewById(R.id.startservice); stopServiceButton = (Button) findViewById(R.id.stopservice); bindServiceButton = (Button) findViewById(R.id.bindservice); unbindServiceButton = (Button) findViewById(R.id.unbindservice);
startServiceButton.setOnClickListener(this); stopServiceButton.setOnClickListener(this); bindServiceButton.setOnClickListener(this); unbindServiceButton.setOnClickListener(this); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupViews(); } @Override public void onClick(View v) { if (v == startServiceButton) { Intent i = new Intent(MainActivity.this, LService.class); mContext.startService(i); } else if (v == stopServiceButton) { Intent i = new Intent(MainActivity.this, LService.class); mContext.stopService(i); } else if (v == bindServiceButton) { Intent i = new Intent(MainActivity.this, LService.class); mContext.bindService(i, mServiceConnection, BIND_AUTO_CREATE); } else { mContext.unbindService(mServiceConnection); } } }
<service android:name=".LService" android:exported="true" > </service>
5、运行程序
点击startService此时调用程序设置里面可以看到Running Service有一个LService
先点击startService,再依次点击bindService和unbindService
新闻热点
疑难解答