_049_Android_Service

服务: 长期可以在后台运行的;没有界面的,;运行在 当前的进程空间中。

编写服务的步骤:

第一步:继承一个service 类 , 那么就写了 一个服务

第二步: 到 清单文件中进行配置

第三步:启动服务, 关闭服务

直接 开启服务,在服务中去干 超时的事, 会引发 应用程序 ANR (application not responding), 导致这种问题,是因为在主线程中干了耗时的事儿.。Service 是运行在主线程中,主线程中 是不允许干耗时的事的。

Activity(默认的是 5 秒钟应用程序无响应那么 就会报 ANR ),

service (默认的是 10 秒钟应用程序无响应, 那么就会报ANR)

QuickStartService .java 

/*
Activity:是有用户界面的组件;
Service:是没有界面的activity,运行在main线程中;
*/

public class QuickStartService extends Service {

    private boolean flag;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }



    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("onCreate 服务被创建了"+Thread.currentThread().getName());
        
      /*
       //这样做因为超时而爆出ANR,可以建一个线程去完成耗时的任务
        while (true){
            System.out.println("监听usb口是否插入了u盘设备");
            SystemClock.sleep(2000);
        }*/

      /*建一个线程去完成耗时的任务*/
      new Thread(){
          @Override
          public void run() {
              flag=true;
              while (flag) {
                  System.out.println("监听usb口是否插入了u盘设备");
                  SystemClock.sleep(2000);
              }
          }
      }.start();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    //服务收到了开启的指令
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("服务收到了开启的指令");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        flag=false;
        System.out.println("onCreate 服务被销毁了");
    }
}

MainActivity.java 

 //开启服务
    public void start(View view) {
        Intent intent = new Intent();
        intent.setClass(this,QuickStartService.class);
        startService(intent);
    }

    //关闭服务
    public void stop(View view) {
        Intent intent = new Intent();
        intent.setClass(this,QuickStartService.class);
        stopService(intent);
    }

 AndroidManifest.xml

<service android:name=".QuickStartService"></service>

 

 

 

 

猜你喜欢

转载自blog.csdn.net/poiuyppp/article/details/84197357
今日推荐