码迷,mamicode.com
首页 > 移动开发 > 详细

android service

时间:2015-01-08 23:59:35      阅读:423      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/linhong/p/4212024.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!