Android 四大组件之一Service

来源:互联网 发布:保利地产工资待遇知乎 编辑:程序博客网 时间:2024/05/16 11:37

1、Service介绍

service 主要用于后台运行,不可见,没有界面。运行于主线程,不能用于耗时的操作(可以另外开启一个线程),如实现下载,音乐,地理定位等。

2、Service使用方法

分为两种:

1: 通过startService()开启服务
这种开启方法不便于实现和主Activity实现数据交换。

2: 通过startService()开启服务
可以很方便的实现数据交互(个人觉得这样才有更大的用处)。

3、第一种方式

Intent intent1 = new Intent(ScrollingActivity.this,MyService.class);startService(intent1);//这种方式很简单

4、重点介绍第二种方式

步骤:

1、继承service类实现自己的service类;2、在自己的服务类中,定义内部类MyBinder,继承Binder类,在该类中返回自定义的service对象;3、在自定义的Service中的onBind()中返回new MyBinder();4、在主Activity中通过ServiceConnection来得到一个自定义的service实例;5、通过bindService(Intent,ServiceConnection,int);6、之后就可以通过获取的service实例使用Service的数据和方法啦。

4.1、自定义Service

自定义的Service名字为 MyService:

public class MyService extends Service {    private String Tag = "houyafei" ;    public MyService() {    }    @Override    public void onCreate() {        super.onCreate();        Log.i(Tag, "-----------onCreate()");    }    @Override    public void onDestroy() {        super.onDestroy();        Log.i(Tag, "-----------onDestroy() ");    }    @Override    public boolean onUnbind(Intent intent) {        Log.i(Tag,"-----------onUnbind(Intent intent)");        return super.onUnbind(intent);    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.i(Tag,"-----------onStartCommand()");        return super.onStartCommand(intent, flags, startId);    }    /**     * 定义Binder类---------------以下部分必须添加,固定------     */    public class MyBinder extends Binder{        public  MyService getService(){            return MyService.this;        }    }    @Override    public IBinder onBind(Intent intent) {        Log.i(Tag,"-----------onBind(Intent intent)");        return new MyBinder();    }//-------------------------------以上部分固定------------------------------   /**     * 用于外部调用的 方法      * --------------------------自己添加的部分-------------------------------     */    public void play(){        Log.i(Tag,"-----------play()");    }    public void pause(){        Log.i(Tag,"-----------pause()");    }    public void previous(){        Log.i(Tag,"-----------previous()");    }    public void next(){        Log.i(Tag,"-----------next()");    }}

4.2、在manifest.xml文件中声明service

        <service            android:name=".MyService"            android:enabled="true"            android:exported="true"></service>

mainfest中的声明标签的含义

4.3、activity中调用 MyService

//------------------第一步--------------------    //获得Services    private MyService myService ;    //Service连接对象    private ServiceConnection connection = null;//------------------第二步--------------------    //实例化ServiceConnection         connection = new ServiceConnection() {        //启动Service,成功连接后会调用该方法            @Override                //通过IBinder对象返回自定义的Service类               myService =  ((MyService.MyBinder)service).getService();            }    //启动源跟Service连接意外丢失,怎会调用该方法            @Override            public void onServiceDisconnected(ComponentName name) {            }    //------------------第三步--绑定------------------  intent2 = new Intent(ScrollingActivity.this,MyService.class); bindService(intent2, connection, Service.BIND_AUTO_CREATE);      //------------------第四步---解绑-----------------       unbindService(connection);       myService = null ;

完整的代码:

public class ScrollingActivity extends AppCompatActivity {    private Intent intent1 ;    private Intent intent2 ;    //获得Services    private MyService myService ;    private ServiceConnection connection = null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_scrolling);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        connection = new ServiceConnection() {            @Override            public void onServiceConnected(ComponentName name, IBinder service) {                //通过IBinder对象返回自定义的Service类               myService =  ((MyService.MyBinder)service).getService();            }            @Override            public void onServiceDisconnected(ComponentName name) {            }        };    }    public void doClick(View view){        switch(view.getId()){            case R.id.start:                intent1 = new Intent(ScrollingActivity.this,MyService.class);                startService(intent1);                break;            case R.id.stop:                stopService(intent1);                break;            case R.id.bund:                intent2 = new Intent(ScrollingActivity.this,MyService.class);                bindService(intent2, connection, Service.BIND_AUTO_CREATE);                break;            case R.id.unbundle:                unbindService(connection);                if(myService!=null){                    myService = null ;                }                break;            case R.id.next:                if(myService!=null){                    myService.next();                }                break;            case R.id.previous:                if(myService!=null){                    myService.previous();                }                break;        }    }    @Override    protected void onDestroy() {        super.onDestroy();        unbindService(connection);//        解绑定之后将service赋值为null,解绑定的意思是 service的声明周期不再和activity一样,//        但绑定的时候 MyBindService的service已经被实例化,解绑定并不影响service的值,解绑定的同时//        将 service赋值为null 将可以实现你想要的效果。//        解绑定属于正常杀死service,所以不会调用onServiceDisconnected方法。        if(myService!=null){            myService = null ;        }    }}

5、一些问题

1:unbindService(connection) 只能执行一次,否则会报错;
2:解绑后myService = null ;否则话Service中的方法还能运行,因为绑定的时候Service已经被实例化了。

0 0