首页 > 系统 > Android > 正文

Anroid四大组件service之本地服务的示例代码

2019-10-22 18:25:15
字体:
来源:转载
供稿:网友

服务是Android四大组件之一,与Activity一样,代表可执行程序。但Service不像Activity有可操作的用户界面,它是一直在后台运行。用通俗易懂点的话来说:

如果某个应用要在运行时向用户呈现可操作的信息就应该选择Activity,如果不是就选择Service。

Service的生命周期如下:

Service只会被创建一次,也只会被销毁一次。那么,如何创建本地服务呢?

实现代码如下:

package temp.com.android/285863.html">androidserivce;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.SystemClock;import android.support.annotation.Nullable;import android.util.Log;/** * Created by Administrator on 2017/8/18. */public class Myservice extends Service {  @Override  public void onCreate() {    Log.i("test", "服务被创建");    super.onCreate();  }  @Override  public int onStartCommand(Intent intent, int flags, int startId) {    Log.i("test", "服务被启动");    new Thread(new myRunnable(startId)).start();    return super.onStartCommand(intent, flags, startId);  }  @Override  public void onDestroy() {    Log.i("test", "服务被销毁");    super.onDestroy();  }  @Nullable  @Override  public IBinder onBind(Intent intent) {    return null;  }  class myRunnable implements Runnable {    int startId;    public myRunnable(int startId) {      this.startId = startId;    }    @Override    public void run() {      for (int i = 0; i < 10; i++) {        SystemClock.sleep(1000);        Log.i("test", i + "");       }      //停止服务      //stopSelf();      stopSelf(startId);      //当用无参数的停止服务时,将会销毁第一次所启动的服务;      //当用带参数的停止服务时,将会销毁最末次所启动的服务;    }  }}

要声明服务,就必须在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的子类。它使用工作线程逐一处理所有启动请求。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VEVB武林网。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表