爱玺玺

爱玺玺的生活日记本。wx:lb87626

接口的使用貌似都需要向上转型成接口类型,然后就可以使用private类里面的方法了

接口的使用貌似都需要向上转型成接口类型,然后就可以使用private类里面的方法了。

private类里面的方法和属性不能被其它类访问。

但是将这个类继承一个接口,这个接口里面定义了它需要让其它类访问的方法。

这里直接new个接口应该是不行的。因为其它类也可以实现这个接口。

但是也许可以将自己这个类new一个对象,然后向上转型?有空做个实验。private能不能new一个对象向上转型成接口。

package com.example.bindservicetest;


public interface ITest {

   //暴露出TestService里面的方法出来,给其它类使用

   public void diaoyongfangfa();

}


package com.example.bindservicetest;


import android.app.Service;

import android.content.Intent;

import android.os.Binder;

import android.os.IBinder;

import android.view.View;

import android.widget.Toast;


public class TestService extends Service{


@Override

public IBinder onBind(Intent arg0) {

// TODO Auto-generated method stub

return new MyBinder();

}

    public void methodService(){

    Toast.makeText(getApplicationContext(), "服务service里面的方法", 1).show();

    }

    //定义中间人对象

    private class MyBinder extends Binder implements ITest{

    //在binder里面的方法调用外部类的方法,然后可以给其它到类调用

    public void diaoyongfangfa(){

    methodService();

    }

    }

}


package com.example.bindservicetest;

import android.support.v7.app.ActionBarActivity;

import android.content.ComponentName;

import android.content.Intent;

import android.content.ServiceConnection;

import android.os.Bundle;

import android.os.IBinder;

import android.view.View;



public class MainActivity extends ActionBarActivity {

    private MyConn conn;

    private ITest myBinder;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    Intent intent=new Intent(this,TestService.class);

    //绑定服务,第二个参数是个接口,用来监听连接服务状态,绑定连接

    //第三个参数flag,BIND_AUTO_CREATE自动创建,用来干什么的暂时不知道

    //这个对象是自定义类,实现的接口,用来连接服务,并获取服务里面IBinder

    conn=new MyConn();

    bindService(intent, conn, BIND_AUTO_CREATE);

    }

    //调用服务里面方法

    public void click(View view){

         myBinder.diaoyongfangfa();

    }

    //当activity销毁的时候解绑服务,这里是解绑那么服务任然应该存在

    @Override

    protected void onDestroy() {

    // TODO Auto-generated method stub

    super.onDestroy();

    unbindService(conn);

    }

    //连接服务

    class MyConn implements ServiceConnection{

        //这里返回的就是服务里面的IBinder

@Override

public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

// TODO Auto-generated method stub

myBinder=(ITest) iBinder;

}

        

@Override

public void onServiceDisconnected(ComponentName arg0) {

// TODO Auto-generated method stub

}

   

    }

}


发表评论:

Powered By Z-BlogPHP 1.4 Deeplue Build 150101

Copyright Your WebSite.Some Rights Reserved.

蜀ICP备11021721号-5