게시판 즐겨찾기
편집
드래그 앤 드롭으로
즐겨찾기 아이콘 위치 수정이 가능합니다.
[질문글]안녕하십니까 선생님들 와이파이 다이렉트 관련해서 질문드리고자..
게시물ID : programmer_21905짧은주소 복사하기
작성자 : 글쓴이멍청이
추천 : 0
조회수 : 763회
댓글수 : 8개
등록시간 : 2017/12/22 21:17:53
옵션
  • 창작글
  • 본인삭제금지
합니다.

와이파이 다이렉트 오픈소스를 약간 수정해서 하려는데 대체 왜 가상 핸드폰에서 열리지 않는지 알 수가 없기에 바쁘시겠지만

질문해봅니다..

사용 툴은 안드로이드 스튜디오이고 와이파이 다이렉트로 휴대폰 두대가 서로 송수신 하려고 합니다.

소스는

WiFiDirectActivity,MyBroadCastReceiver, MyPhone, PeerListFragment 입니다.

WiFiDirectActivity

package com.cookandroid.mydirecttest1;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager;
import android.provider.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.net.wifi.p2p.WifiP2pManager.*;
import android.widget.Toast;

public class WiFiDirectActivity extends AppCompatActivity
        implements ChannelListener,PeerListFragment.DeviceActionListener {
    public static final String TAG = "wifidirectdemo";
    private WifiP2pManager manager;
    private boolean isWifiP2pEnabled = false;
    private boolean retryChannel = false;

    private final IntentFilter intentFilter = new IntentFilter();
    private WifiP2pManager.Channel channel;
    private BroadcastReceiver receiver = null;

    public void SetIsWifiEnabled(boolean isWifiP2pEnabled){
        this.isWifiP2pEnabled = isWifiP2pEnabled;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

        manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        channel = manager.initialize(this, getMainLooper(), null);
    }

    @Override
    protected void onPause() {
        super.onPause();
        receiver = new MyBroadCastReceiver(manager, channel, this);
        registerReceiver(receiver,intentFilter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        unregisterReceiver(receiver);
    }

    public void resetData(){
        MyPhone fragment1 = (MyPhone)getFragmentManager().findFragmentById(R.id.frag_MyPhone);
        PeerListFragment fragment2 = (PeerListFragment)getFragmentManager().findFragmentById(R.id.frag_List);
        if (fragment2 != null){
            fragment2.clearPeers();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.action_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.item_enable:
                if (manager != null && channel != null){
                    startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                }else{
                    Log.e(TAG, "channel or manager is null");
                }
                return true;
            case R.id.item_search:
                if (!isWifiP2pEnabled){
                    Toast.makeText(WiFiDirectActivity.this, "Enable P2P from action bar button above or system settings",
                            Toast.LENGTH_SHORT).show();
                    return true;
                }
                final PeerListFragment fragment = (PeerListFragment) getFragmentManager()
                        .findFragmentById(R.id.frag_List);
                fragment.onInitiateDiscovery();
                manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

                    @Override
                    public void onSuccess() {
                        Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int reasonCode) {
                        Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
                                Toast.LENGTH_SHORT).show();
                    }
                });
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }


    @Override
    public void onChannelDisconnected() {
        if (manager != null && !retryChannel) {
            Toast.makeText(this, "Channel lost. Trying again", Toast.LENGTH_LONG).show();
            resetData();
            retryChannel = true;
            manager.initialize(this, getMainLooper(), this);
        } else {
            Toast.makeText(this,
                    "Severe! Channel is probably lost premanently. Try Disable/Re-Enable P2P.",
                    Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void showDetails(WifiP2pDevice device) {

    }

    @Override
    public void cancelDisconnect() {
        if (manager != null) {
            final PeerListFragment fragment = (PeerListFragment) getFragmentManager()
                    .findFragmentById(R.id.frag_List);
            if (fragment.getDevice() == null
                    || fragment.getDevice().status == WifiP2pDevice.CONNECTED) {
                disconnect();
            } else if (fragment.getDevice().status == WifiP2pDevice.AVAILABLE
                    || fragment.getDevice().status == WifiP2pDevice.INVITED) {

                manager.cancelConnect(channel, new ActionListener() {

                    @Override
                    public void onSuccess() {
                        Toast.makeText(WiFiDirectActivity.this, "Aborting connection",
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int reasonCode) {
                        Toast.makeText(WiFiDirectActivity.this,
                                "Connect abort request failed. Reason Code: " + reasonCode,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

    @Override
    public void connect(WifiP2pConfig config) {
        manager.connect(channel, config, new ActionListener() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFailure(int i) {
                Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void disconnect() {
        //연결종료 부분;
    }
}

MyBroadCastReceiver

package com.cookandroid.mydirecttest1;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.*;
import android.util.Log;

public class MyBroadCastReceiver extends BroadcastReceiver {
    private WifiP2pManager manager;
    private Channel channel;
    private WiFiDirectActivity activity;

    public MyBroadCastReceiver(WifiP2pManager manager, Channel channel, WiFiDirectActivity wiFiDirectActivity) {
        super();
        this.manager = manager;
        this.channel = channel;
        this.activity = wiFiDirectActivity;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {

            // UI update to indicate wifi p2p status.
            //Wi-Fi P2P 상태를 나타내는 UI 업데이트.
            int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
            if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
                // Wifi Direct mode is enabled
                //Wi-Fi Direct 모드가 사용 설정되어 있습니다.
                activity.SetIsWifiEnabled(true);
            } else {
                activity.SetIsWifiEnabled(false);
                activity.resetData();

            }
            Log.d(WiFiDirectActivity.TAG, "P2P state changed - " + state);
        } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {

            /*request available peers from the wifi p2p manager. This is an
            asynchronous call and the calling activity is notified with a
            callback on PeerListListener.onPeersAvailable()*/
            /*wifi P2P 관리자로부터 사용 가능한 피어를 요청하십시오.
              이것은 비동기 호출이며 호출하는 활동은 PeerListListener.onPeersAvailable()에서
              콜백으로 통지됩니다.*/
            if (manager != null) {
                manager.requestPeers(channel, (PeerListListener) activity.getFragmentManager()
                        .findFragmentById(R.id.frag_List));
            }
            Log.d(WiFiDirectActivity.TAG, "P2P peers changed");
        } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {

            if (manager == null) {
                return;
            }

            NetworkInfo networkInfo = (NetworkInfo) intent
                    .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

            if (networkInfo.isConnected()) {

                /*we are connected with the other device, request connection info to find group owner IP*/
                /*우리는 다른 장치와 연결되어 그룹 소유자 IP를 찾기 위해 연결 정보를 요청합니다.*/

                PeerListFragment fragment = (PeerListFragment) activity
                        .getFragmentManager().findFragmentById(R.id.frag_List);
                manager.requestConnectionInfo(channel, fragment);
            } else {
                // It's a disconnect
                //연결 끊긴 부분임.
                activity.resetData();
            }
        } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
            //기기가 변경될 경우에 어떻게 할 것인지.
            MyPhone fragment = (MyPhone) activity.getFragmentManager()
                    .findFragmentById(R.id.frag_MyPhone);
            fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
                    WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));

        }
    }
}

MyPhone

package com.cookandroid.mydirecttest1;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MyPhone extends Fragment {
    private View mContentView = null;
    private WifiP2pDevice device;
    private WifiP2pInfo info;
    ProgressDialog progressDialog = null;

    public WifiP2pDevice getDevice(){
        return device;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.fragment_my_phone, container, false);
        return mContentView;
    }
    private static String getDeviceStatus(int deviceStatus) {
        Log.d(WiFiDirectActivity.TAG, "Peer status :" + deviceStatus);
        switch (deviceStatus) {
            case WifiP2pDevice.AVAILABLE:
                return "Available";
            case WifiP2pDevice.INVITED:
                return "Invited";
            case WifiP2pDevice.CONNECTED:
                return "Connected";
            case WifiP2pDevice.FAILED:
                return "Failed";
            case WifiP2pDevice.UNAVAILABLE:
                return "Unavailable";
            default:
                return "Unknown";

        }
    }
    public void updateThisDevice(WifiP2pDevice device) {
        this.device = device;
        TextView view = (TextView) mContentView.findViewById(R.id.myPhone_Name);
        view.setText(device.deviceName);
        view = (TextView) mContentView.findViewById(R.id.my_Phone_State);
        view.setText(getDeviceStatus(device.status));
    }

}


PeerListFragment

package com.cookandroid.mydirecttest1;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.app.ListFragment;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.*;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class PeerListFragment extends ListFragment implements PeerListListener,ConnectionInfoListener {
    private List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
    ProgressDialog progressDialog = null;
    View mContentView = null;
    private WifiP2pDevice device;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        this.setListAdapter(new WiFiPeerListAdapter(getActivity(),R.layout.list_item, peers));
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.fragment_peer_list, container, false);

        return mContentView;
    }

    public WifiP2pDevice getDevice(){
        return device;
    }
    private static String getDeviceStatus(int deviceStatus) {
        Log.d(WiFiDirectActivity.TAG, "peer status : " + deviceStatus);
        switch (deviceStatus){
            case WifiP2pDevice.AVAILABLE:
                return "Available";
            case WifiP2pDevice.INVITED:
                return "Invited";
            case WifiP2pDevice.CONNECTED:
                return "Connected";
            case WifiP2pDevice.FAILED:
                return "Failed";
            case WifiP2pDevice.UNAVAILABLE:
                return "Unavailable";
            default:
                return "Unknown";
        }
    }
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        WifiP2pDevice device = (WifiP2pDevice)getListAdapter().getItem(position);
    }

    @Override
    public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {

    }//화면이동

    private class WiFiPeerListAdapter extends ArrayAdapter<WifiP2pDevice>{
        private List<WifiP2pDevice> items;

        public WiFiPeerListAdapter(Context con, int TextViewResourceId,
                                   List<WifiP2pDevice> object){
            super(con, TextViewResourceId, object);
            items = object;
        }
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            View v = convertView;
            Button btnConnect;

            if (v == null){
                LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.list_item, null);
            }
            final WifiP2pDevice device = items.get(position);
            if (device !=null) {
                TextView top = (TextView)v.findViewById(R.id.txPhone_Name);
                TextView bottom = (TextView)v.findViewById(R.id.txPhone_state);
                if (top != null){
                    top.setText(device.deviceName);
                }
                if (bottom != null){
                    bottom.setText(getDeviceStatus(device.status));
                }
            }
            btnConnect = (Button)v.findViewById(R.id.btnConnect);
            btnConnect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    WifiP2pDevice device1 =new WifiP2pDevice();
                    WifiP2pConfig config = new WifiP2pConfig();
                    config.deviceAddress = device1.deviceAddress;
                    config.wps.setup = WpsInfo.PBC;
                    if (progressDialog != null && progressDialog.isShowing()){
                        progressDialog.dismiss();

                    }
                    progressDialog = progressDialog.show(getActivity(),"Press back to cancel",
                            "Connecting to : " + device1.deviceAddress,true,true);
                    ((DeviceActionListener)getActivity()).connect(config);
                }//onClick;
            });
            return v;
        }
    }


    @Override
    public void onPeersAvailable(WifiP2pDeviceList peerList) {
        if (progressDialog != null&& progressDialog.isShowing()){
            progressDialog.dismiss();
        }
        peers.clear();
        peers.addAll(peerList.getDeviceList());
        ((WiFiPeerListAdapter)getListAdapter()).notifyDataSetChanged();
        if(peers.size() == 0){
            Log.d(WiFiDirectActivity.TAG, "No devices Found");
            return;
        }
    }

    public void clearPeers() {
        peers.clear();
        ((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();
    }
    public void onInitiateDiscovery() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        progressDialog = ProgressDialog.show(getActivity(), "Press back to cancel", "finding peers", true,
                true, new DialogInterface.OnCancelListener() {

                    @Override
                    public void onCancel(DialogInterface dialog) {

                    }
                });
    }


    public interface DeviceActionListener {

        void showDetails(WifiP2pDevice device);

        void cancelDisconnect();

        void connect(WifiP2pConfig config);

        void disconnect();
    }
}
전체 추천리스트 보기
새로운 댓글이 없습니다.
새로운 댓글 확인하기
글쓰기
◀뒤로가기
PC버전
맨위로▲
공지 운영 자료창고 청소년보호