Service-初识

1.什么是Service?

Service作为Android四大组件(activity、service、content provider、broadcast receiver)之一,在每一个应用程序中都扮演着非常重要的角色。它主要用于在后台处理一些耗时的逻辑,或者去执行某些需要长期运行的任务,并且不提供用户界面,服务能被其它应用程序的组件启动,即使用户切换到另外的应用时还能保持后台运行。必要的时候我们甚至可以在程序退出的情况下,让Service在后台继续保持运行状态。

2.Service有哪些应用场景

可以处理网络传输、音乐播放、下载,执行文件I/O、或者与content provider进行交互
3.StartService方式启动Service应该如何做(启动和停止及生命周期)
实现步骤:

  1. 创建一个类继承Service,并实现它的onBind方法和onStartCommand方法并改写
  2. 在manifests文件里注册该Service
 <service android:name=".MyService" />
  1. 通过其他程序启动,常见的为Activity

Demo
MyService.java

package com.example.fpl.week3application;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

public class MyService extends Service {
    String TAG="MyService";

    private int num;

    @Override
    public IBinder onBind(Intent intent) {

        Log.e(TAG," onBind......");
        return null;
    }

    @Override
    public void onCreate() {
        Log.e(TAG,"onCreate......");
        super.onCreate();


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        String name=intent.getStringExtra("name");

        Log.e(TAG,"onStartCommand......"+name);




        new Thread(new Runnable() {
            @Override
            public void run() {

              //  Log.e(TAG,Thread.currentThread().getName());

                while (num<100){
                    Log.e(TAG, String.valueOf(num));
                    num++;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }


            }
        }).start();
        return super.onStartCommand(intent, flags, startId);


    }

    @Override
    public void onDestroy() {
        Log.e(TAG,"onDestroy......");

        super.onDestroy();




    }
}

MyActivity.java

package com.example.fpl.week3application;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button button;
    private Button button2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bindID();

    }

    private void bindID() {
        button=findViewById(R.id.Servicestart_BTN);
        button2=findViewById(R.id.Servicestop_BTN);

        button2.setOnClickListener(this);
        button.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case  R.id.Servicestart_BTN:

                Intent intent=new Intent(this,MyService.class);
                intent.putExtra("name","隆记");

                //通过startService启动
                startService(intent);

                break;

            case  R.id.Servicestop_BTN:

                Intent intent2=new Intent(this,MyService.class);
               //关闭Service
                stopService(intent2);

                break;
                default:
                    break;
        }

    }

    @Override
    protected void onDestroy() {
        Log.e("MainActivity","onDestory......");
        Intent intent2=new Intent(this,MyService.class);
        stopService(intent2);
        super.onDestroy();



    }
}

优点:使用简单,
缺点:线程开启后不受控制,
引入BindService

4.bindService方式启动Service如何做(绑定和解绑及生命周期)

这里要引入Binder,通过Binder绑定Service,起到控制Service的作用,当连接中断时Service也被销毁;

demo

package com.example.fpl.week3application;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.util.Log;

public class SecondService extends Service {

    private int count=0;

     //Binder类实例化对象
    private MyBinder binder=new MyBinder();
     //继承Binder
    public  class MyBinder extends Binder{

        public SecondService getServices(){
            return  SecondService.this;

        }
    }

    @Nullable
    //返回binder
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("执行onBind方法...");
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {

        System.out.println("执行onUnBind方法...");
        return true;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        System.out.println("执行onCreate方法");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        System.out.println("执行onStartCommand方法");
        //三种返回值(仅限使用startService方法启动时有效果)
        //START_STICKY,服务被异常杀掉后,会重启服务
        //START_NOT_STICKY,服务被异常杀掉后,不会重启服务
        //START_REDELIVER_INTENT,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        System.out.println("rebind");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("执行onDestroy方法");
    }

    public void ff(){

        new Thread(new Runnable() {
            @Override
            public void run() {

                while (count<100){
                    try {
                        Thread.sleep(1000);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count++;
                    Log.e("Second", String.valueOf(count));
                }


            }
        }).start();

       /* class MyThread extends Thread{
            @Override
            public void run() {



                while (count<100){
                    try {
                        Thread.sleep(1000);
                        System.out.print(Thread.currentThread().getName()+"*******"+Thread.currentThread().getId());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count++;
                    System.out.print(count);
                }


                super.run();
            }
        }*/
    }




}
package com.example.fpl.week3application;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class SecondMainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button button;
    private Button button1;
    private Intent intent; 

    //通过ServiceConnection连接
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            SecondService ms = ((SecondService.MyBinder) service).getServices();
            //调用Service方法
            ms.ff();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("connected");


        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second_main);

       // intent=new Intent(this,SecondService.class);


        bindID();
    }

    private void bindID() {


        button=findViewById(R.id.ServicestartSec_BTN);
        button1=findViewById(R.id.ServicestopSec_BTN);

        button.setOnClickListener(this);
        button1.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ServicestartSec_BTN:
                intent=new Intent(this,SecondService.class);
                //bindService启动
                bindService(intent,connection, Service.BIND_AUTO_CREATE);



                break;
            case R.id.ServicestopSec_BTN:
                unbindService(connection);
                break;
                default:
                    break;
        }
    }
}

5.IntentService有什么不同

和一般的Service最主要的不同是:
- 它里面的方法(onHandleIntent)能直接在里面进行耗时程序操作,不用开任何子线程;
- 它只能通过startService的方式启动

6.IntentSercive怎么做,注意事项;

  1. 新建一个类继承IntentService
  2. 实现里面的方法,构造方法和onHandleIntent方法,并按需求重写onHandleIntent方法
  3. 通过其他的程序比如Activity启动;

注意事项:要在manifests文件里注册该Service,注册时一般会报错只需在Service文件里添加该段代码:

 public  DemoService(){
        super("DemoService");
    }

demo

package com.example.fpl.week3application;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;

public class ThirdService extends IntentService {

    private int num;
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */

    public  ThirdService(){
        super("ThirdService");
    }
    public ThirdService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        while (num<100){
            Log.e("Second", String.valueOf(num));
            num++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值