为什么我的统一android插件不起作用?

时间:2018-09-03 02:33:28

标签: android unity3d wifi-direct

我想在unity应用中直接使用wifi,所以我制作了一个用于unity的android插件,android代码正确并且可以正常工作,但是我似乎不知道如何在unity中使用它,我什至无法调用返回字符串的方法来自MainActivity 如果有人知道做错了什么,请帮助

我的Android代码:

公共类MainActivity扩展了AppCompatActivity {

// variables
Button btnOnOff,btnDiscover,btnSend;
ListView listView;
TextView readMsgBox,connectionStatus;
EditText writeMsg;
WifiManager wifiManager;
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] deviceNameArray;
WifiP2pDevice[] deviceArray;
static final int MESSAGE_READ=1;
ServerClass serverClass;
ClientClass clientClass;
SendReceive sendReceive;

// wifi methods
public void enableWifi(){
    wifiManager.setWifiEnabled(true);
}
public void discoverThePeers(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.i(TAG,"Discovery Started");
            }
            @Override
            public void onFailure(int reason) {
                Log.i(TAG,"Discovery Starting Failed");
            }
        });
    }
}
public void connectTo(int position){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        final WifiP2pDevice device = deviceArray[position];
        WifiP2pConfig config = null;
        config = new WifiP2pConfig();
        config.deviceAddress=device.deviceAddress;

        mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(getApplicationContext(),"connected to : "+device.deviceName, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int reason) {
                Toast.makeText(getApplicationContext(),"could not connect to : "+device.deviceName, Toast.LENGTH_SHORT).show();
            }
        });
    }


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initialWork();
    exqListener();
}

// its an Awake() method
private void initialWork(){
    btnOnOff=(Button) findViewById(R.id.onOff);
    btnDiscover=(Button) findViewById(R.id.discover);
    btnSend=(Button) findViewById(R.id.sendButton);
    listView=(ListView) findViewById(R.id.peerListView);
    readMsgBox=(TextView) findViewById(R.id.readMsg);
    connectionStatus=(TextView) findViewById(R.id.connectionStatus);
    writeMsg=(EditText) findViewById(R.id.writeMsg);

    wifiManager=(WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    mChannel = mManager.initialize(this,getMainLooper(),null);

    mReceiver=new WifiDirectBroadcastReceiver(mManager,mChannel,this);

    mIntentFilter=new IntentFilter();
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}

Handler handler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what){
            case MESSAGE_READ:
                byte[] readbuff = (byte[]) msg.obj;
                String tempMsg = new String(readbuff,0,msg.arg1);
                readMsgBox.setText(tempMsg);
                break;
        }
        return true;
    }
});

// enables/disables wifi
private void exqListener(){
    btnOnOff.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(wifiManager.isWifiEnabled()){
                wifiManager.setWifiEnabled(false);
                btnOnOff.setText("Enable Wifi");
            }else{
                wifiManager.setWifiEnabled(true);
                btnOnOff.setText("Disable Wifi");
            }
        }
    });

    btnDiscover.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
                @Override
                public void onSuccess() {
                    connectionStatus.setText("Discovery Started");
                }
                @Override
                public void onFailure(int reason) {
                    connectionStatus.setText("Discovery Starting Failed");
                }
            });
        }
    });

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final WifiP2pDevice device = deviceArray[position];
            WifiP2pConfig config = new WifiP2pConfig();
            config.deviceAddress=device.deviceAddress;

            mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
                @Override
                public void onSuccess() {
                    Toast.makeText(getApplicationContext(),"connected to : "+device.deviceName, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int reason) {
                    Toast.makeText(getApplicationContext(),"could not connect to : "+device.deviceName, Toast.LENGTH_SHORT).show();
                }
            });
        }
    });

    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String msg=writeMsg.getText().toString();
            sendReceive.write(msg.getBytes());
        }
    });
}

public void clickForWifi(){
    if(wifiManager.isWifiEnabled()){
        wifiManager.setWifiEnabled(false);
        btnOnOff.setText("Enable Wifi");
    }else{
        wifiManager.setWifiEnabled(true);
        btnOnOff.setText("Disable Wifi");
    }
}

WifiP2pManager.PeerListListener peerListListener = new  WifiP2pManager.PeerListListener(){
    @Override
    public void onPeersAvailable(WifiP2pDeviceList peerList) {
        if(!peerList.getDeviceList().equals((peers))){
            peers.clear();
            peers.addAll(peerList.getDeviceList());
            deviceNameArray=new String[peerList.getDeviceList().size()];
            deviceArray=new WifiP2pDevice[peerList.getDeviceList().size()];
            int index=0;
            for(WifiP2pDevice device : peerList.getDeviceList()){
                deviceNameArray[index]=device.deviceName;
                deviceArray[index]=device;
                index++;
            }
            ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,deviceNameArray);
            listView.setAdapter(adapter);
        }
        if(peers.size()==0){

            return;
        }
    }
};

WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener(){
    @Override
    public void onConnectionInfoAvailable(WifiP2pInfo info) {
        final InetAddress groupOwnerAdress=info.groupOwnerAddress;

        if(info.groupFormed && info.isGroupOwner){
            connectionStatus.setText("connection state : Host");
            serverClass=new ServerClass();
            serverClass.start();
        }else if(info.groupFormed){
            connectionStatus.setText("connection state : Client");
            clientClass=new ClientClass(groupOwnerAdress);
            clientClass.start();
        }
    }
};

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(mReceiver,mIntentFilter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mReceiver);
}

// SERVER
public class ServerClass extends Thread{
    Socket socket;
    ServerSocket serverSocket;

    @Override
    public void run() {
        try {
            serverSocket=new ServerSocket(8888);
            socket=serverSocket.accept();
            sendReceive=new SendReceive(socket);
            sendReceive.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// SEND RECEIVE
private class SendReceive extends Thread{
    private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;

    public SendReceive(Socket skt){
        this.socket=skt;
        try {
            inputStream=socket.getInputStream();
            outputStream=socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        byte[] buffer = new byte[1024];
        int bytes;
        while(socket!=null){
            try {
                bytes=inputStream.read(buffer);
                if(bytes>0){
                    handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void write(byte[] bytes){
        try {
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// CLIENT
public class ClientClass extends Thread{
    Socket socket;
    String hostAdd;

    public ClientClass(InetAddress hostAdress){
        hostAdd=hostAdress.getHostAddress();
        socket=new Socket();
    }

    @Override
    public void run() {
        try {
            socket.connect(new InetSocketAddress(hostAdd,8888),500);
            sendReceive=new SendReceive(socket);
            sendReceive.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}

我的统一代码:

private void Start()
{
    TextMesh textMesh = GetComponent<TextMesh>();
    AndroidJavaClass mainAct = new AndroidJavaClass("androidproject.alientechlab.com.unityplugin.MainActivity");
    textMesh.text = mainAct.Call<string>("GetTextFromPlugin");
}

0 个答案:

没有答案