首页 > 代码库 > android service

android service

service开发的步骤:

     1.继承Service类

     2.在AndroidManifest.xml文件中的<application>节点里对服务进行配置:<service android:name=".SMSService" />
     3.服务不能自己运行,需要通过调用Context.startService()或Context.bindService()方法启动服务

public class MainActivity extends Activity implements OnClickListener, ServiceConnection {    private Button btnstartservice,btnstopservice,btnbindservice,btnunbindservice;    private Intent intentservice;    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                intentservice=new Intent(this,MyService.class);                btnstartservice=(Button) findViewById(R.id.btnstartservice);        btnstopservice=(Button) findViewById(R.id.btnstopservice);        btnbindservice=(Button) findViewById(R.id.btnbindservice);        btnunbindservice=(Button) findViewById(R.id.btnunbindservice);        btnstartservice.setOnClickListener(this);        btnstopservice.setOnClickListener(this);        btnbindservice.setOnClickListener(this);        btnunbindservice.setOnClickListener(this);                    }    @Override    public void onClick(View v) {                switch (v.getId()) {        case R.id.btnstartservice:            startService(intentservice);            break;        case R.id.btnstopservice:            stopService(intentservice);            break;        case R.id.btnbindservice:            bindService(intentservice, this,Context.BIND_AUTO_CREATE);            break;        case R.id.btnunbindservice:            unbindService(this);            break;        }            }    @Override    public void onServiceConnected(ComponentName arg0, IBinder arg1) {                System.out.println("onserviceconnected");    }    @Override    public void onServiceDisconnected(ComponentName arg0) {                System.out.println("onservicedisconnected");    }        }
public class MyService extends Service {    /*     * startservice退出是服务还在后台进行     * bindservice退出时服务停止     * bindservice作用是进行通信     *      */    public IBinder onBind(Intent intent) {            System.out.println("onBind...");        //return null;        return echoserviceBind;            }    public class serviceBind extends Binder    {            }    private serviceBind echoserviceBind=new serviceBind();            public void onCreate() {        System.out.println("onCreate..");        super.onCreate();            }        public void onDestroy() {        System.out.println("onDestroy..");        super.onDestroy();    }}

 

android service