下面列出了怎么用android.net.wifi.p2p.WifiP2pDevice的API类实例代码及写法,或者点击链接到github查看源代码。
private void requestPeers() {
mWifiP2pManager.requestPeers(mWifiP2pChannel, new PeerListListener() {
@Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
if (DEBUG) {
Slog.d(TAG, "Received list of peers.");
}
mAvailableWifiDisplayPeers.clear();
for (WifiP2pDevice device : peers.getDeviceList()) {
if (DEBUG) {
Slog.d(TAG, " " + describeWifiP2pDevice(device));
}
if (isWifiDisplay(device)) {
mAvailableWifiDisplayPeers.add(device);
}
}
if (mDiscoverPeersInProgress) {
handleScanResults();
}
}
});
}
private void handleScanResults() {
final int count = mAvailableWifiDisplayPeers.size();
final WifiDisplay[] displays = WifiDisplay.CREATOR.newArray(count);
for (int i = 0; i < count; i++) {
WifiP2pDevice device = mAvailableWifiDisplayPeers.get(i);
displays[i] = createWifiDisplay(device);
updateDesiredDevice(device);
}
mHandler.post(new Runnable() {
@Override
public void run() {
mListener.onScanResults(displays);
}
});
}
private void updateDesiredDevice(WifiP2pDevice device) {
// Handle the case where the device to which we are connecting or connected
// may have been renamed or reported different properties in the latest scan.
final String address = device.deviceAddress;
if (mDesiredDevice != null && mDesiredDevice.deviceAddress.equals(address)) {
if (DEBUG) {
Slog.d(TAG, "updateDesiredDevice: new information "
+ describeWifiP2pDevice(device));
}
mDesiredDevice.update(device);
if (mAdvertisedDisplay != null
&& mAdvertisedDisplay.getDeviceAddress().equals(address)) {
readvertiseDisplay(createWifiDisplay(mDesiredDevice));
}
}
}
private void handleConnectionFailure(boolean timeoutOccurred) {
Slog.i(TAG, "Wifi display connection failed!");
if (mDesiredDevice != null) {
if (mConnectionRetriesLeft > 0) {
final WifiP2pDevice oldDevice = mDesiredDevice;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (mDesiredDevice == oldDevice && mConnectionRetriesLeft > 0) {
mConnectionRetriesLeft -= 1;
Slog.i(TAG, "Retrying Wifi display connection. Retries left: "
+ mConnectionRetriesLeft);
retryConnection();
}
}
}, timeoutOccurred ? 0 : CONNECT_RETRY_DELAY_MILLIS);
} else {
disconnect();
}
}
}
private static String getDeviceStatus(int deviceStatus) {
Log.d(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 synchronized void connectDevice(WifiP2pDevice wifiP2pDevice) {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = wifiP2pDevice.deviceAddress;
config.wps.setup = WpsInfo.PBC;
config.groupOwnerIntent = 15;
manager.connect(channel, config, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {}
@Override
public void onFailure(int reason) {
if(wifiP2PConnectionCallback != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
wifiP2PConnectionCallback.onPeerConnectionFailure();
}
});
}
}
});
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_device_list, container, false);
progressView = rootView.findViewById(R.id.scan_progress);
animationView = rootView.findViewById(R.id.gif1);
recyclerView = rootView.findViewById(R.id.scanned_list);
recyclerView.setLayoutManager(new LinearLayoutManager(activity));
wifiListAdapter = new WifiListAdapter(activity, new ArrayList<WifiP2pDevice>());
recyclerView.setAdapter(wifiListAdapter);
emptyView = rootView.findViewById(R.id.empty_view);
swipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);
((SenderActivity)activity).wifiP2PService.onCreate();
((SenderActivity)activity).wifiP2PService.onResume();
return rootView;
}
@Override
public void onDnsSdTxtRecordAvailable(String fullDomainName,
Map<String, String> txtRecordMap, WifiP2pDevice srcDevice) {
ALog.i(TAG, "onDnsSdTxtRecordAvailable");
InfoHolder holder=new InfoHolder();
holder.mFullDomainName=fullDomainName;
holder.mValueMap=txtRecordMap;
holder.mSrcDevice=srcDevice;
mHandler.obtainMessage(Event.SERVICE_INFO_AVAILABLE,holder).sendToTarget();
/* String res = "";
for (Entry<String, String> ele : txtRecordMap.entrySet()) {
res += ele.getKey();
res += " " + ele.getValue() + " ";
}*/
}
public static String getDeviceStatus(int 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 error";
}
}
private CharSequence getWifiP2pDeviceStatus(WifiP2pDevice dev) {
switch (dev.status) {
case WifiP2pDevice.CONNECTED:
return getString(R.string.status_p2p_connected);
case WifiP2pDevice.INVITED:
return getString(R.string.status_p2p_invited);
case WifiP2pDevice.FAILED:
return getString(R.string.status_p2p_failed);
case WifiP2pDevice.AVAILABLE:
return getString(R.string.status_p2p_available);
case WifiP2pDevice.UNAVAILABLE:
default:
return getString(R.string.status_p2p_unavailable);
}
}
/**
* 切断する
*/
protected void internalDisconnect(final WifiP2pManager.ActionListener listener) {
if (DEBUG) Log.v(TAG, "internalDisconnect:");
if (mWifiP2pManager != null) {
if ((mWifiP2pDevice == null)
|| (mWifiP2pDevice.status == WifiP2pDevice.CONNECTED)) {
// 接続されていないか、既に接続済みの時
if (mChannel != null) {
mWifiP2pManager.removeGroup(mChannel, listener);
}
} else if (mWifiP2pDevice.status == WifiP2pDevice.AVAILABLE
|| mWifiP2pDevice.status == WifiP2pDevice.INVITED) {
// ネゴシエーション中の時
mWifiP2pManager.cancelConnect(mChannel, listener);
}
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.component_row_devices, null);
}
WifiP2pDevice device = items.get(position);
if (device != null) {
TextView top = v.findViewById(R.id.device_name);
TextView bottom = v.findViewById(R.id.device_details);
if (top != null) {
top.setText(device.deviceName);
}
if (bottom != null) {
bottom.setText(getDeviceStatus(device.status));
}
}
return v;
}
@Override
public void cancelDisconnect() {
if(mManager != null){
final DeviceListFragment fragment = (DeviceListFragment)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){
mManager.cancelConnect(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
}
@Override
public void onFailure(int reason) {
}
});
}
}
}
private static String getDeviceStatus(int deviceStatus){
Log.e(WiFiDirectActivity.TAG, "Peer status: "+deviceStatus);
switch(deviceStatus){
case WifiP2pDevice.AVAILABLE:
return "Avaiable";
case WifiP2pDevice.INVITED:
return "Invited";
case WifiP2pDevice.CONNECTED:
return "Conntend";
case WifiP2pDevice.FAILED:
return "Failed";
case WifiP2pDevice.UNAVAILABLE:
return "Unavailable";
default:
return "Unkonw";
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row_devices, null);
}
WifiP2pDevice device = items.get(position);
if(device != null){
TextView top = (TextView)v.findViewById(R.id.device_name);
TextView bottom = (TextView)v.findViewById(R.id.device_details);
if(null != top){
top.setText(device.deviceName);
}
if(null != bottom){
bottom.setText(device.deviceAddress);
}
}
return v;
}
/**
* Takes a WifiP2pDevice and returns a String of readable device information
* @param wifiP2pDevice
* @return
*/
public String p2pDeviceToString(WifiP2pDevice wifiP2pDevice) {
if (wifiP2pDevice != null) {
String strDevice = "Device name: " + wifiP2pDevice.deviceName;
strDevice += "\nDevice address: " + wifiP2pDevice.deviceAddress;
if (wifiP2pDevice.equals(thisDevice)) {
strDevice += "\nIs group owner: " + isGroupOwner();
} else {
strDevice += "\nIs group owner: false";
}
strDevice += "\nStatus: " + deviceStatusToString(wifiP2pDevice.status) + "\n";
return strDevice;
} else {
Log.e(TAG, "WifiP2pDevice is null");
return "";
}
}
public String p2pGroupToString(WifiP2pGroup wifiP2pGroup) {
if (wifiP2pGroup != null) {
String strWifiP2pGroup = "Network name: " + wifiP2pGroup.getNetworkName();
strWifiP2pGroup += "\nIs group owner: " + wifiP2pGroup.isGroupOwner();
if (wifiP2pGroup.getOwner() != null) {
strWifiP2pGroup += "\nGroup owner: ";
strWifiP2pGroup += "\n" + p2pDeviceToString(wifiP2pGroup.getOwner());
}
if (wifiP2pGroup.getClientList() != null && !wifiP2pGroup.getClientList().isEmpty()) {
for (WifiP2pDevice client : wifiP2pGroup.getClientList()) {
strWifiP2pGroup += "\nClient: ";
strWifiP2pGroup += "\n" + p2pDeviceToString(client);
}
}
return strWifiP2pGroup;
} else {
Log.e(TAG, "WifiP2pGroup is null");
return "";
}
}
/**
* Translates a device status code to a readable String status
* @param status
* @return A readable String device status
*/
public String deviceStatusToString(int status) {
if (status == WifiP2pDevice.AVAILABLE) {
return "Available";
} else if (status == WifiP2pDevice.INVITED) {
return "Invited";
} else if (status == WifiP2pDevice.CONNECTED) {
return "Connected";
} else if (status == WifiP2pDevice.FAILED) {
return "Failed";
} else if (status == WifiP2pDevice.UNAVAILABLE) {
return "Unavailable";
} else {
return "Unknown";
}
}
void handleBroadcast(Intent intent) {
closeProgressDialog();
final String action = intent.getAction();
if (WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
p2p.isWifiP2pEnabled = true;
} else {
showMessage(R.string.event_p2p_disable);
resetData();
}
} else if (WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
new Wifip2pRequestPeers(eventHelper).execute(p2p);
} else if (WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
WifiP2pDevice me = (WifiP2pDevice) intent
.getParcelableExtra(EXTRA_WIFI_P2P_DEVICE);
thisDevice.setText(getWifiP2pDeviceInfo(me));
}
}
/**
* Initiate a connection with the peer.
*/
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.d(TAG, "onListItemClick");
WifiP2pDevice device = (WifiP2pDevice)getListAdapter().getItem(position);
Log.d(TAG, "device is: " + device.deviceAddress);
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
progressDialog = ProgressDialog.show(getActivity(), "Press back to cancel",
"Connecting to :" + device.deviceAddress, true, true);
((DeviceActionListener)getActivity()).connect(config);
}
public void requestConnect(String address) {
for (WifiP2pDevice device : mAvailableWifiDisplayPeers) {
if (device.deviceAddress.equals(address)) {
connect(device);
}
}
}
private void connect(final WifiP2pDevice device) {
if (mDesiredDevice != null
&& !mDesiredDevice.deviceAddress.equals(device.deviceAddress)) {
if (DEBUG) {
Slog.d(TAG, "connect: nothing to do, already connecting to "
+ describeWifiP2pDevice(device));
}
return;
}
if (mConnectedDevice != null
&& !mConnectedDevice.deviceAddress.equals(device.deviceAddress)
&& mDesiredDevice == null) {
if (DEBUG) {
Slog.d(TAG, "connect: nothing to do, already connected to "
+ describeWifiP2pDevice(device) + " and not part way through "
+ "connecting to a different device.");
}
return;
}
if (!mWfdEnabled) {
Slog.i(TAG, "Ignoring request to connect to Wifi display because the "
+" feature is currently disabled: " + device.deviceName);
return;
}
mDesiredDevice = device;
mConnectionRetriesLeft = CONNECT_MAX_RETRIES;
updateConnection();
}
private static int getPortNumber(WifiP2pDevice device) {
if (device.deviceName.startsWith("DIRECT-")
&& device.deviceName.endsWith("Broadcom")) {
// These dongles ignore the port we broadcast in our WFD IE.
return 8554;
}
return DEFAULT_CONTROL_PORT;
}
@SuppressWarnings("unchecked")
boolean handleMessage(int type, int status, Object obj) {
if (type == WiFiP2PCommand.CMD_RequestPeers) {
resetPeers();
if (obj != null) {
for (WifiP2pDevice dev : (Collection<WifiP2pDevice>) obj) {
peerdevs.add(dev);
peers.add(getWifiP2pDeviceInfo(dev));
}
}
return true;
}
if (type == WiFiP2PCommand.CMD_CancelConnect) {
new Wifip2pRemoveGroup(eventHelper).execute(p2p);
return true;
}
if (type == WiFiP2PCommand.CMD_RemoveGroup) {
new Wifip2pDiscoverPeers(eventHelper).execute(p2p);
return true;
}
return true;
}
@Override
public void redirectToProcessScreen(WifiP2pDevice wifiP2pDevice) {
getSupportFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right)
.replace(R.id.fragment_container, SenderFragment.newInstance(wifiP2pDevice))
.commitAllowingStateLoss();
}
public static SenderFragment newInstance(WifiP2pDevice wifiP2pDevice) {
SenderFragment fragment = new SenderFragment();
Bundle args = new Bundle();
args.putParcelable(INTENT_CONFIG, wifiP2pDevice);
fragment.setArguments(args);
return fragment;
}
void handlePeerListClick(int index) {
WifiP2pDevice dev = peerdevs.get(index);
if (dev.status == WifiP2pDevice.CONNECTED
|| dev.status == WifiP2pDevice.INVITED) {
disconnectPeer(dev);
} else if (dev.status != WifiP2pDevice.UNAVAILABLE) {
connectPeer(dev);
}
}
@Override
public void updateDeviceStatus(WifiP2pDevice mDevice) {
Logger.log(TAG, "Wi-fi direct status updating");
DeviceListFragment fragment = (DeviceListFragment)this.getSupportFragmentManager()
.findFragmentById(R.id.frag_list);
fragment.updateThisDevice(mDevice);
}
@Override
public void onDnsSdServiceAvailable(String instanceName,
String registrationType, WifiP2pDevice srcDevice) {
ALog.i(TAG, "onDnsSdServiceAvailable name:"+instanceName);
InfoHolder holder=new InfoHolder();
holder.mInstanceName=instanceName;
holder.mRegistrationType=registrationType;
holder.mSrcDevice=srcDevice;
mHandler.obtainMessage(Event.SERVICE_AVAILABLE,holder).sendToTarget();
}
private void connectPeer(WifiP2pDevice peer) {
CharSequence dev = getWifiP2pDeviceInfo2(peer);
CharSequence msg = Logger.fmt(getString(R.string.info_connect), dev);
CharSequence msg2 = Logger
.fmt(getString(R.string.info_connecting), dev);
CommandHelper cmd = new CommandHelper(new Wifip2pConnectPeer(peer,
eventHelper), p2p, msg2);
new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)
.setTitle(R.string.lab_p2p_connect).setMessage(msg)
.setNegativeButton(R.string.action_cancel, cmd)
.setPositiveButton(R.string.action_ok, cmd).show();
}