温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Service的基本操作

发布时间:2020-07-31 03:27:29 来源:网络 阅读:339 作者:清甘茶 栏目:开发技术

    Service的基本操作,启动service的方式有两种,一种是context.startService,暂停的service是stopService,这种方式service与主activity没有关联,不能单纯的进行数据交互(可以考虑使用广播,进行交互),另一种方式binderService,这种方式返回的是一个binder对象,

    binderService(Intent service,ServiceConnection conn,int flag):第一个参数是intent对象,第二个是链接对象,第三个是否自动创建service,0是不自动创建,BINDER_AUTO_CREATE

public class MyService extends Service {


public MyService() {

}

public int count = 0 ;

public MyBinder binder = new MyBinder();


public class MyBinder extends Binder {

// 创建一个集成Binder类的对象,activity调用service的时候返回一个Binder对象给activity

public int getCount(){

count = 10 ;

return count ;

}

}


@Override

public IBinder onBind(Intent arg0) {

// 必须实现的方法

return binder;

}


@Override

public void onCreate() {

// 每次创建的时候执行一次,

System.out.println("onCreate");

super.onCreate();

}


@Override

public int onStartCommand(Intent intent, int flags, int startId) {

// service每次运行的时候执行

System.out.println("onStartCommand");

return super.onStartCommand(intent, flags, startId);

}


@Override

public void onDestroy() {

// 销毁的之后执行

System.out.println("onDestroy");

super.onDestroy();

}

}

    

public class MainActivity extends Activity implements OnClickListener {


private Button start, stop, get;

MyService.MyBinder binder;

private ServiceConnection conn = new ServiceConnection() {


@Override

public void onServiceDisconnected(ComponentName name) {

// 链接断开的时候进行掉用

System.out.println("service链接断开");

}


@Override

public void onServiceConnected(ComponentName name, IBinder service) {

// 进行链接的时候进行调用

System.out.println("service链接成功");

binder = (MyService.MyBinder) service;

}

};


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

start = (Button) findViewById(R.id.start);

stop = (Button) findViewById(R.id.stop);

get = (Button) findViewById(R.id.get);


this.start.setOnClickListener(this);

this.stop.setOnClickListener(this);

this.get.setOnClickListener(this);

}


@Override

public void onClick(View view) {


switch (view.getId()) {

case R.id.start:

// 第二种启动方式

Intent in = new Intent(MainActivity.this, MyService.class);

bindService(in, conn, Service.BIND_AUTO_CREATE);


// 第一种启动方式,activity关闭的时候service也会随着关闭

// Intent in = new Intent(MainActivity.this,MyService.class) ;

// MainActivity.this.startService(in) ;

break;

case R.id.stop:

// 第二种关闭方式

unbindService(conn);

// 第一种启动方式,activity关闭的时候service也会随着关闭

// Intent in2 = new Intent(MainActivity.this,MyService.class) ;

// MainActivity.this.stopService(in2) ;

break;

case R.id.get:

// 获取状态

System.out

.println("=====service返回的值======>>>>" + binder.getCount());

break;

default:

break;

}

}

}


附件:http://down.51cto.com/data/2365688
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI