Android四大组件之一Service介绍-android学习之旅(十二)

来源:互联网 发布:linux分页显示命令 编辑:程序博客网 时间:2024/06/03 12:30

基本概念:

service是android四大组件之一,运行在后台执行耗时操作,并不提供用户界面。其他组件如acticity可以通过startService启动该组件,也可以通过bindService启动并把绑定该组件进行通信。

使用场景

后台下载文件,以及播放音乐等

注意

service运行在主线程中,他不会创建属于自己的线程,也不是运行在独立的线程中,所以在使用的时候,需要自己创建线程,而不应该直接使用,这样会造成ANR错误。

service的两种形式

started service
其他组件如activity等通过stratService等启动该组件,拥有独立的生命周期,不依赖启动他的组件。
bound service
其他组件为了与service建立一个长时间的连接通过bindService来建立连接。并能与之交互(发送请求,接受响应)。它的生命周期依赖绑定他的组件,一但解除绑定就会消亡。

两个service的代码:

package peng.liu.testview;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class MyService extends Service {    public MyService() {    }    @Override    public void onCreate() {        super.onCreate();        ServiceClass sc = new ServiceClass();        sc.start();    }    private class ServiceClass extends Thread{        @Override        public void run() {            super.run();            for (int i = 0;i< 1000;i++){                System.out.println("hello"+i);                try {                    Thread.sleep(1000);                }catch (Exception e){                    e.printStackTrace();                }            }        }    }    @Override    public IBinder onBind(Intent intent) {        // TODO: Return the communication channel to the service.        throw new UnsupportedOperationException("Not yet implemented");    }}

另外一个service是

package peng.liu.testview;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import java.util.Random;public class MyService2 extends Service {    public MyService2() {    }    //第一步实现binder子类    public class LiuBinder extends Binder {        //创建一个公共方法,返回service实例        public MyService2 getService(){            return MyService2.this;        }    }    //onBind方法返回一个LiuBinder    private LiuBinder binder = new LiuBinder();    @Override    public IBinder onBind(Intent intent) {        return binder;    }    //创建自定义的业务方法,必须是公共的    public int getRandom(){        Random random = new Random();        return random.nextInt(100);    }    @Override    public void onDestroy() {        super.onDestroy();        System.out.println("service done");    }}

主类的代码:

package peng.liu.testview;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.IntentFilter;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.view.View;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity implements View.OnClickListener{    private Button send,reg,unReg;    private MyService2 service;    boolean isBound;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        findViewById(R.id.send).setOnClickListener(this);        findViewById(R.id.reg).setOnClickListener(this);        findViewById(R.id.unReg).setOnClickListener(this);    }    @Override    public void onClick(View view) {        switch (view.getId()){            case R.id.send:                startService(new Intent(MainActivity.this,MyService.class));            break;            case R.id.reg:                Intent intent = new Intent(MainActivity.this,MyService2.class);                bindService(intent,conn,BIND_AUTO_CREATE);        }        Toast.makeText(MainActivity.this,"随机数是"+service.getRandom(),Toast.LENGTH_LONG).show();    }    @Override    protected void onDestroy() {        super.onDestroy();        unbindService(conn);    }    private ServiceConnection conn = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {            MyService2.LiuBinder binder = (MyService2.LiuBinder)iBinder;            service = binder.getService();            isBound = true;        }        @Override        public void onServiceDisconnected(ComponentName componentName) {            isBound = false;        }    };}

注册service代码:

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