1. 程式人生 > >Android WiFi直連並完成圖片雙向傳送

Android WiFi直連並完成圖片雙向傳送

之前做了個WiFi直連的小應用,忙於之前沒時間整理,趁著週末有空整理一下。

        WiFi直連可以在不通過網路或熱點的情況下,直接與周圍的裝置進行連線並進行資訊交換。WiFi直連是在Android 4.0(API level 14)或更高的版本中才加入的新功能。本文主要介紹通過Wi-Fi Direct查詢附近的裝置,實現連線並完成圖片的傳送。一般包括如下幾個步驟:

• 在AndroidManifest檔案中宣告相關許可權

• 建立對等網路管理器(WifiP2pManager),註冊相關廣播監聽WiFi直連狀態

• 建立MyAdapter,用於顯示搜尋到的對等點列表,監聽點選連線事件

• 開始對對等點的搜尋,獲取對等點列表

• 連線一個對等點

• 判斷一方為組擁有者(GroupOwner),提交接收圖片的非同步任務

• 呼叫系統圖庫選擇圖片,開啟後臺服務將其傳送

• 分別設作為組擁有者,完成圖片的互發

整體的流程圖如下:


接下來進行分部說明

在AndroidManifest檔案中宣告相關許可權

<uses-sdk android:minSdkVersion="14" />

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
WiFi直連是在api level 14及更高的版本才能使用,所以要宣告android:minSdkVersion="14"

建立對等網路管理器(WifiP2pManager),註冊相關廣播監聽WiFi直連狀態

     使用WiFi直連,需要監聽如下動作:

  WIFI_P2P_STATE_CHANGED_ACTION — 表明Wi-Fi對等網路(P2P)是否已經啟用
  WIFI_P2P_PEERS_CHANGED_ACTION — 表明可用的對等點的列表發生了改變
  WIFI_P2P_CONNECTION_CHANGED_ACTION — 表明Wi-Fi對等網路的連線狀態發生了改變
  WIFI_P2P_THIS_DEVICE_CHANGED_ACTION — 表明該裝置的配置資訊發生了改變
private BroadcastReceiver mReceiver;
private IntentFilter mFilter;
private void initIntentFilter() {
        mFilter = new IntentFilter();
        mFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        mFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        mFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        mFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    }

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

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mFilter);
    }
    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }
廣播接收
public class WifiDirectBroadcastReceiver extends BroadcastReceiver {

    private WifiP2pManager mManager;
    private WifiP2pManager.Channel mChannel;
    private Activity mActivity;
    private WifiP2pManager.PeerListListener mPeerListListener;
    private WifiP2pManager.ConnectionInfoListener mInfoListener;

    public WifiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel, Activity activity,
                                       WifiP2pManager.PeerListListener peerListListener,
                                       WifiP2pManager.ConnectionInfoListener infoListener
    ) {
        this.mManager = manager;
        this.mChannel = channel;
        this.mPeerListListener = peerListListener;
        this.mActivity = activity;
        this.mInfoListener = infoListener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        /*check if the wifi is enable*/
        if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
            int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
        }
        /*get the list*/
        else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
            mManager.requestPeers(mChannel, mPeerListListener);
        } /*Respond to new connection or disconnections*/
        else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
            if (mManager == null) {
                return;
            }
            NetworkInfo networkInfo = (NetworkInfo) intent
                    .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

            if (networkInfo.isConnected()) {
                mManager.requestConnectionInfo(mChannel, mInfoListener);
            } else {return;
            }
        }
        /*Respond to this device's wifi state changing*/
        else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {

        }
    }
}

建立MyAdapter,用於顯示接下來搜尋到的對等點列表,監聽點選連線事件

  繼承RecyclerView.Adapter,實現獲取對等點列表的顯示和響應事件
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder> {

    private List<HashMap<String, String>> mList;
    /*
    * 設定回撥介面,實現點選
    * */
    public interface OnItemClickListener {
        void OnItemClick(View view, int position);
    }

    public OnItemClickListener mOnItemClickListener;

    public void SetOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public MyAdapter(List<HashMap<String, String>> list) {
        super();
        this.mList = list;
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(parent.getContext());

        View view = inflater.inflate(R.layout.card_item,
                parent, false);
        MyHolder myHolder = new MyHolder(view);
        return myHolder;
    }

    @Override
    public void onBindViewHolder(final MyHolder holder, final int position) {

        holder.tvname.setText(mList.get(position).get("name"));
        holder.tvaddress.setText(mList.get(position).get("address"));

        if (mOnItemClickListener != null) {

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnItemClickListener.OnItemClick(holder.itemView, position);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    class MyHolder extends RecyclerView.ViewHolder {

        public TextView tvname;
        public TextView tvaddress;

        public MyHolder(View View) {
            super(View);
            tvname = (TextView) View.findViewById(R.id.tv_name);
            tvaddress = (TextView) View.findViewById(R.id.tv_address);

        }
    }
}

開始對對等點的搜尋,獲取對等點列表

      首先在  方法中獲得了 的一個例項,呼叫它的 方法。這個方法返回一個 物件,並觸發WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION的廣播,把應用程式連線到Wi-Fi Direct框架中。

protected void onCreate(Bundle savedInstanceState) {
     ...
        mManager = (WifiP2pManager) getSystemService(WIFI_P2P_SERVICE);
        mChannel = mManager.initialize(this, Looper.myLooper(), null);
}
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
            //Register for WIFI_P2P_PEERS_CHANGED_ACTION
            @Override
            public void onSuccess() {
            }
            @Override
            public void onFailure(int reason) {
            }
        });
       如果發現裝置會回撥上面的onSuccess()方法,講觸發WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION這個廣播,在onReceive()中可以呼叫requestPeers()方法,然後在MainActivity的PeerListListerner介面中,呼叫onPeersAvailable()回撥方法,獲取到對等列表的詳細資訊,通過MyAdapter在RecyclerView列表中顯示。
 WifiP2pManager.PeerListListener mPeerListListerner = new WifiP2pManager.PeerListListener() {
            @Override
            public void onPeersAvailable(WifiP2pDeviceList peersList) {
                peers.clear();
                peersshow.clear();
                Collection<WifiP2pDevice> aList = peersList.getDeviceList();
                peers.addAll(aList);

                for (int i = 0; i < aList.size(); i++) {
                    WifiP2pDevice a = (WifiP2pDevice) peers.get(i);
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("name", a.deviceName);
                    map.put("address", a.deviceAddress);
                    peersshow.add(map);
                }
                mAdapter = new MyAdapter(peersshow);
                mRecyclerView.setAdapter(mAdapter);
                mRecyclerView.setLayoutManager(new LinearLayoutManager
                        (MainActivity.this));
            }
        };

連線一個對等點

      觸控RecyclerView列表上的對等裝置資訊,觸發響應事件,呼叫CreateConnect()方法,方法引數為觸控列表上的裝置資訊。在該方法中,需要先建立一個新的WifiP2pConfig物件,記錄傳進來的裝置引數,然後呼叫connect()方法。 如果裝置會回撥onSuccess()方法,這說明對等點連線成功。

private void CreateConnect(String address, final String name) {
        WifiP2pDevice device;
        WifiP2pConfig config = new WifiP2pConfig();
        config.deviceAddress = address;
        config.wps.setup = WpsInfo.PBC;

        mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
//   Register for WIFI_P2P_CONNECTION_CHANGED_ACTION
            @Override
            public void onSuccess() {

            }
            @Override
            public void onFailure(int reason) {

            }
        });
    }

判斷一方為組擁有者(GroupOwner),提交接收圖片的非同步任務

      對等點連線成功後,會觸發WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION這個廣播,在onReceive()中呼叫requestConnectionInfo()方法,然後在MainActivity的ConnectionInfoListerner介面中,呼叫onConnectionInfoAvailable()回撥方法,獲取到組連線資訊,根據獲取到的資訊,判斷是否為組擁有者。若是,作為服務端,向其提交圖片下載、讀取的非同步任務。

WifiP2pManager.ConnectionInfoListener mInfoListener = new WifiP2pManager.ConnectionInfoListener() {

            @Override
            public void onConnectionInfoAvailable(final WifiP2pInfo minfo) {
                info = minfo;
                view = (TextView) findViewById(R.id.tv_main);
                if (info.groupFormed && info.isGroupOwner) {
                    //確定為組擁有者,建立執行緒用於接收連線請求
                    //提交圖片下載、讀取的非同步任務
                } else if (info.groupFormed) {
                    //作為客戶端,建立一個執行緒用於連線組擁有者
                }
            }
        };
public class FileServerAsyncTask extends
        AsyncTask<Void, Void, String> {

    private Context context;
    private TextView statusText;
    /**
     * @param context
     * @param statusText
     */
    public FileServerAsyncTask(Context context, View statusText) {
        this.context = context;
        this.statusText = (TextView) statusText;
    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            Socket client = serverSocket.accept();
            final File f = new File(
                    Environment.getExternalStorageDirectory() +  "/" + "RecvPicture"+
                            "/wifip2pshared-" + System.currentTimeMillis() + ".jpg");
            File dirs = new File(f.getParent());

            if (!dirs.exists())
                dirs.mkdirs();
            f.createNewFile();


                /*Returns an input stream to read data from this socket*/
            InputStream inputstream = client.getInputStream();
            copyFile(inputstream, new FileOutputStream(f));
            serverSocket.close();
            return f.getAbsolutePath();

        } catch (IOException e) {
            Log.e("xyz", e.toString());
            return null;
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(String result) {if(result != null){
            Toast.makeText(context, "RecvPic:"+result, Toast.LENGTH_SHORT).show();
        }

        if (result != null) {
            statusText.setText("RecvPic: " + result);
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse("file://" + result), "image/*");
            context.startActivity(intent);
        }

    }public static boolean copyFile(InputStream inputStream, OutputStream out) {
        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                out.write(buf, 0, len);

            }
            out.close();
            inputStream.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }
}

呼叫系統圖庫選擇圖片,開啟後臺服務將其傳送

      點擊發送圖片按鈕,呼叫系統圖庫。選取圖片後,開啟圖片傳送服務,並將圖片路徑,傳送的ip地址和接收的埠號傳入。

public class FileTransferService extends IntentService {

    private static final int SOCKET_TIMEOUT = 5000;
    public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
    public static final String EXTRAS_FILE_PATH = "sf_file_url";
    public static final String EXTRAS_GROUP_OWNER_ADDRESS = "sf_go_host";
    public static final String EXTRAS_GROUP_OWNER_PORT = "sf_go_port";

    public FileTransferService(String name) {
        super(name);
    }

    public FileTransferService() {
        super("FileTransferService");
    }

    /*
     * (non-Javadoc)
     *
     * @see android.app.IntentService#onHandleIntent(android.content.Intent)
     */
    @Override
    protected void onHandleIntent(Intent intent) {

        Context context = getApplicationContext();
        if (intent.getAction().equals(ACTION_SEND_FILE)) {
            String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);

            String host = intent.getExtras().getString(
                    EXTRAS_GROUP_OWNER_ADDRESS);

            Socket socket = new Socket();

            int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);

            try {
                Log.d("xyz", "Opening client socket - ");
                socket.bind(null);
                socket.connect((new InetSocketAddress(host, port)),
                        SOCKET_TIMEOUT);

                Log.d("xyz",
                        "Client socket - " + socket.isConnected());

                /*returns an output stream to write data into this socket*/
                OutputStream stream = socket.getOutputStream();
                ContentResolver cr = context.getContentResolver();
                InputStream is = null;
                try {
                    is = cr.openInputStream(Uri.parse(fileUri));
                } catch (FileNotFoundException e) {
                }

                FileServerAsyncTask.copyFile(is, stream);


            } catch (IOException e) {
            } finally {
                if (socket != null) {
                    if (socket.isConnected()) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            // Give up
                            e.printStackTrace();
                        }
                    }
                }
            }

        }
    }
}

可分別設作為組擁有者,完成圖片的互發

       呼叫createGroup()方法,分別設定本裝置為組擁有者,實現裝置圖片的互發。

 mManager.createGroup(mChannel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.i("tag","BeGroupOwner success");
            }

            @Override
            public void onFailure(int reason) {
                Log.i("tag","BeGroupOwner failed");
            }
        });

我的原始碼地址:http://download.csdn.net/download/u010782875/10033100










宣告相關許可權