服务是Android四大组件之一,与Activity一样,代表可执行程序。但Service不像Activity有可操作的用户界面,它是一直在后台运行。用通俗易懂点的话来说:
如果某个应用要在运行时向用户呈现可操作的信息就应该选择Activity,如果不是就选择Service。
Service的生命周期如下:
Service只会被创建一次,也只会被销毁一次。那么,如何创建本地服务呢?
实现代码如下:
要声明服务,就必须在manifests中进行配置
<manifest ... > ... <application ... > <service android:name=".Myservice" android:exported="true"/> ... </application> </manifest>android:exported="true" 设置了这个属性就表示别人也可以使用你的服务。
还有一个需要注意的小点,在Myservice中可以看见我启动时用了一个子线程去帮我实现工作,那么我为什么没有直接把for循环的那段代码写在onStartCommand方法中呢,是因为写在onStartCommand中将会报ANR程序无响应的错误。就是当你所有的事情都去交给主线程做时,就会造成主线程内存溢出,它就会炸了。这个时候也可以用IntentService来取代Service。
package temp.com.androidserivce;import android.app.IntentService;import android.content.Intent;import android.os.SystemClock;import android.util.Log;/** * Created by Administrator on 2017/8/18. */public class MyService2 extends IntentService { public MyService2() { super(""); } public MyService2(String name) { super(name); } @Override protected void onHandleIntent(Intent intent) { for (int i = 0; i <10 ; i++) { SystemClock.sleep(1000); Log.i("test",i+""); } }}使用这个相对而言会比较简单。IntentService是Service的子类。它使用工作线程逐一处理所有启动请求。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。