bind服务/Activity调用Service方法

package com.example.test23_bindservice;


import com.example.test23_bindservice.BindService.MyBinder;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;


public class MainActivity extends Activity {
private MyConnection conn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onDestroy() {
super.onDestroy();
//把Service关闭,解除跟当前Activity的绑定
unbindService(conn);
}
public void start(View v){
Intent service = new Intent(this,BindService.class);
//通过bind方法实现service方法
conn = new MyConnection();
//使用bindService开启的服务
//参数1:包含要启动个Service
//参数2:ServiceConnection接口,通过它可以接受到服务开启或者结束的消息
//参数3:开启服务是操作的选项,一般传入BIND_AUTO_CREATE,自动创建Service
bindService(service, conn, BIND_AUTO_CREATE);
}
public void stop(View v){
//使用bindService开启的服务要用unbindService来停止
unbindService(conn);
}
public void callServiceMethod(View v){
BindService service = new BindService();
service.showToast("hello");

}
private class MyConnection implements  ServiceConnection{
private MyBinder myBinder;
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//只有当Service的onBind方法返回值不为null,才会调用此方法
Log.e("TAG", "onServiceConnected");
myBinder = (MyBinder) service;
}


@Override
public void onServiceDisconnected(ComponentName name) {
//服务正常退出的时候不会调用此方法
Log.e("TAG", "onServiceDisconnected");

}

}

}




BindService类

package com.example.test23_bindservice;


import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;


public class BindService extends Service{


@Override
public IBinder onBind(Intent intent) {
Log.e("TAG", "onBind");
return new MyBinder();
}
@Override
public void onCreate() {
Log.e("TAG", "onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("TAG", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e("TAG", "onDestroy");
super.onDestroy();
}

public void showToast(String s){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT);

}
public class MyBinder extends Binder{
public void callShowToast(String s){
showToast(s);
}
public void showToast2(String s){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT);
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值