码迷,mamicode.com
首页 > 其他好文 > 详细

service的使用

时间:2015-11-21 14:23:55      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

package com.example.yabushan.hello3;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

//服务类 public class MyService extends Service { public MyService() { } @Override public IBinder onBind(Intent intent) { System.out.println("服务绑定"); return new Binder(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { new Thread(){ @Override public void run() { super.run(); while (true){ System.out.println("服务启动"); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); return super.onStartCommand(intent, flags, startId); } }

  

package com.example.yabushan.hello3;

import android.app.Activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;


public class MainActivity extends Activity implements View.OnClickListener, ServiceConnection {

    Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_layout);
        intent=new Intent(MainActivity.this,MyService.class);
                findViewById(R.id.startService).setOnClickListener(this);
                findViewById(R.id.stopService).setOnClickListener(this);
                findViewById(R.id.bindService).setOnClickListener(this);
                findViewById(R.id.unbindService).setOnClickListener(this);

        }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.startService:
                startService(intent);break;
            case R.id.stopService:
                stopService(intent);break;
            case R.id.bindService://绑定服务需要实现下面的两个方法
                bindService(intent,this, Context.BIND_AUTO_CREATE);
            case R.id.unbindService:
                unbindService(this);


        }

    }
   
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        System.out.println("服务绑定成功");

    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
}

  

service的使用

标签:

原文地址:http://www.cnblogs.com/yabushan/p/4983594.html

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