下面列出了怎么用android.net.wifi.p2p.WifiP2pManager的API类实例代码及写法,或者点击链接到github查看源代码。
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));
}
}
@Override
public synchronized void stopScanImpl() {
mIsRunning = false;
mContext.unregisterReceiver(mReceiver);
mManager.stopPeerDiscovery(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.d(TAG, "stop discovering");
}
@Override
public void onFailure(int reasonCode) {
Log.d(TAG, "stop discovery failed " + reasonCode);
}
});
}
@Override
public synchronized void handleOnPeersChangedResponse() {
manager.requestPeers(channel, new WifiP2pManager.PeerListListener() {
@Override
public void onPeersAvailable(final WifiP2pDeviceList wifiP2pDeviceList) {
if(wifiP2PConnectionCallback != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
wifiP2PConnectionCallback.onPeerAvailable(wifiP2pDeviceList);
}
});
}
}
});
}
@Override
public void startDataTransfer(final String message) {
manager.requestConnectionInfo(channel, new WifiP2pManager.ConnectionInfoListener() {
@Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
boolean isGroupOwner = wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner;
boolean isClient = RECEIVER_PREFS_VALUE.equalsIgnoreCase(PreferenceUtils.getStringValues(activity, PREFS_CLIENT_KEY));
if(isClient && isGroupOwner) {
handleOnPeerServer(wifiP2pInfo);
} else if(!isClient && !isGroupOwner && message != null) {
handleOnPeerClient(wifiP2pInfo, message);
}
}
});
}
protected void forceDisconnect() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
WifiP2pManager.ActionListener doNothing = new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
}
@Override
public void onFailure(int reason) {
}
};
stopServiceDiscovery(false);
manager.cancelConnect(channel, doNothing);
manager.clearLocalServices(channel, doNothing);
manager.clearServiceRequests(channel, doNothing);
manager.stopPeerDiscovery(channel, doNothing);
}
}
public void connect(WifiP2pDevice device)
{
WifiP2pConfig config=new WifiP2pConfig();
config.deviceAddress=device.deviceAddress;
config.wps.setup= WpsInfo.PBC;
_wifiP2pManager.connect(_channel, config, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
}
@Override
public void onFailure(int reason) {
}
});
}
/**
* WiFiP2pHelperインスタンスをシステムに登録
*/
public synchronized void register() {
if (DEBUG) Log.v(TAG, "register:");
final Context context = mWeakContext.get();
if ((context != null) & (mReceiver == null)) {
mChannel = mWifiP2pManager.initialize(context,
context.getMainLooper(), mChannelListener);
mReceiver = new WiFiDirectBroadcastReceiver(mWifiP2pManager, mChannel, this);
final IntentFilter intentFilter = new IntentFilter();
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);
context.registerReceiver(mReceiver, intentFilter);
}
}
/**
* 指定した機器へ接続を試みる
* @param config
* @throws IllegalStateException
*/
public void connect(@NonNull final WifiP2pConfig config) throws IllegalStateException {
if (DEBUG) Log.v(TAG, "connect:config=" + config);
if (mChannel != null) {
mWifiP2pManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
// WiFiDirectBroadcastReceiver will notify us. Ignore for now.
}
@Override
public void onFailure(int reason) {
callOnError(new RuntimeException("failed to connect, reason=" + reason));
}
});
} else {
throw new IllegalStateException("not registered");
}
}
/**
* 切断する
*/
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
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
//��ʼ��WifiP2pManager
mManager = (WifiP2pManager)getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
//������Ҫ������action
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);
}
@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) {
}
});
}
}
}
@Override
public void disconnect() {
final DeviceDetailFragment fragment = (DeviceDetailFragment)getFragmentManager().findFragmentById(R.id.frag_detail);
fragment.resetViews();
mManager.removeGroup(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
fragment.getView().setVisibility(View.GONE);
}
@Override
public void onFailure(int reason) {
Log.e(WiFiDirectActivity.TAG, "disconnect faile reason: "+reason);
}
});
}
/**
* Registers a WifiDirectBroadcastReceiver with an IntentFilter listening for P2P Actions
*/
public void registerP2pReceiver() {
p2pBroadcastReceiver = new WifiDirectBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
// Indicates a change in the list of available peers
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
// Indicates a change in the Wi-Fi P2P status
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
// Indicates the state of Wi-Fi P2P connectivity has changed
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
// Indicates this device's details have changed.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
registerReceiver(p2pBroadcastReceiver, intentFilter);
Log.i(TAG, "P2P BroadcastReceiver registered");
}
/**
* Removes persistent/remembered groups
*
* Source: https://android.googlesource.com/platform/cts/+/jb-mr1-dev%5E1%5E2..jb-mr1-dev%5E1/
* Author: Nick Kralevich <[email protected]>
*
* WifiP2pManager.java has a method deletePersistentGroup(), but it is not accessible in the
* SDK. According to Vinit Deshpande <[email protected]>, it is a common Android paradigm to
* expose certain APIs in the SDK and hide others. This allows Android to maintain stability and
* security. As a workaround, this removePersistentGroups() method uses Java reflection to call
* the hidden method. We can list all the methods in WifiP2pManager and invoke "deletePersistentGroup"
* if it exists. This is used to remove all possible persistent/remembered groups.
*/
private void removePersistentGroups() {
try {
Method[] methods = WifiP2pManager.class.getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("deletePersistentGroup")) {
// Remove any persistent group
for (int netid = 0; netid < 32; netid++) {
methods[i].invoke(wifiP2pManager, channel, netid, null);
}
}
}
Log.i(TAG, "Persistent groups removed");
} catch(Exception e) {
Log.e(TAG, "Failure removing persistent groups: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Removes the current WifiP2pGroup in the WifiP2pChannel.
*/
public void removeGroup() {
if (wifiP2pGroup != null) {
wifiP2pManager.removeGroup(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
wifiP2pGroup = null;
groupFormed = false;
isGroupOwner = false;
Log.i(TAG, "Group removed");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure removing group: " + FailureReason.fromInteger(reason).toString());
}
});
}
}
/**
* Removes a registered local service.
*/
public void removeService() {
if(wifiP2pServiceInfo != null) {
Log.i(TAG, "Removing local service");
wifiP2pManager.removeLocalService(channel, wifiP2pServiceInfo, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
wifiP2pServiceInfo = null;
Intent intent = new Intent(Action.SERVICE_REMOVED);
localBroadcastManager.sendBroadcast(intent);
Log.i(TAG, "Local service removed");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure removing local service: " + FailureReason.fromInteger(reason).toString());
}
});
wifiP2pServiceInfo = null;
} else {
Log.w(TAG, "No local service to remove");
}
}
private void clearServiceDiscoveryRequests() {
if (serviceRequest != null) {
wifiP2pManager.clearServiceRequests(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
serviceRequest = null;
Log.i(TAG, "Service discovery requests cleared");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure clearing service discovery requests: " + FailureReason.fromInteger(reason).toString());
}
});
}
}
/**
* Initiates a connection to a service
* @param service The service to connect to
*/
public void initiateConnectToService(DnsSdService service) {
// Device info of peer to connect to
WifiP2pConfig wifiP2pConfig = new WifiP2pConfig();
wifiP2pConfig.deviceAddress = service.getSrcDevice().deviceAddress;
wifiP2pConfig.wps.setup = WpsInfo.PBC;
// Starts a peer-to-peer connection with a device with the specified configuration
wifiP2pManager.connect(channel, wifiP2pConfig, new WifiP2pManager.ActionListener() {
// The ActionListener only notifies that initiation of connection has succeeded or failed
@Override
public void onSuccess() {
Log.i(TAG, "Initiating connection to service");
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failure initiating connection to service: " + FailureReason.fromInteger(reason).toString());
}
});
}
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// The list of discovered peers has changed
handlePeersChanged(intent);
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// The state of Wi-Fi P2P connectivity has changed
handleConnectionChanged(intent);
} else if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// Indicates whether Wi-Fi P2P is enabled
handleP2pStateChanged(intent);
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Indicates this device's configuration details have changed
handleThisDeviceChanged(intent);
} else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
handleWifiStateChanged(intent);
} else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
handleScanResultsAvailable(intent);
}
}
private void connectToDevice(final SalutDevice device, final SalutCallback onFailure) {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.macAddress;
manager.connect(channel, config, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.d(TAG, "Attempting to connect to another device.");
lastConnectedDevice = device;
}
@Override
public void onFailure(int reason) {
onFailure.call();
Log.e(TAG, "Failed to connect to device. ");
}
});
}
public void createGroup(final SalutCallback onSuccess, final SalutCallback onFailure) {
manager.createGroup(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.v(TAG, "Successfully created group.");
Log.d(TAG, "Successfully created " + thisDevice.serviceName + " service running on port " + thisDevice.servicePort);
isRunningAsHost = true;
if (onSuccess != null) {
onSuccess.call();
}
}
@Override
public void onFailure(int reason) {
Log.e(TAG, "Failed to create group. Reason :" + reason);
if (onFailure != null)
onFailure.call();
}
});
}
public void cancelConnecting() {
manager.cancelConnect(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.v(TAG, "Attempting to cancel connect.");
}
@Override
public void onFailure(int reason) {
Log.v(TAG, "Failed to cancel connect, the device may not have been trying to connect.");
}
});
stopServiceDiscovery(true);
connectingIsCanceled = true;
}
@Override
@SuppressLint("InlinedApi")
public void onReceive(Context context, Intent intent) {
if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(intent.getAction())) {
WifiP2pGroup wifiP2pGroup = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_GROUP);
onWifiP2pGroupChange(wifiP2pGroup);
} else if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(intent.getAction())) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, 0 /* default to unknown */);
onWifiP2pStateChange(state);
}
}
/** Handle a state change notification about wifi p2p. */
private void onWifiP2pStateChange(int state) {
if (state == WifiP2pManager.WIFI_P2P_STATE_DISABLED) {
wifiP2pNetworkInfo = null;
observer.onNetworkDisconnect(WIFI_P2P_NETWORK_HANDLE);
}
}
public WifiDisplayController(Context context, Handler handler, Listener listener) {
mContext = context;
mHandler = handler;
mListener = listener;
mWifiP2pManager = (WifiP2pManager)context.getSystemService(Context.WIFI_P2P_SERVICE);
mWifiP2pChannel = mWifiP2pManager.initialize(context, handler.getLooper(), null);
IntentFilter intentFilter = new IntentFilter();
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);
context.registerReceiver(mWifiP2pReceiver, intentFilter, null, mHandler);
ContentObserver settingsObserver = new ContentObserver(mHandler) {
@Override
public void onChange(boolean selfChange, Uri uri) {
updateSettings();
}
};
final ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(Settings.Global.getUriFor(
Settings.Global.WIFI_DISPLAY_ON), false, settingsObserver);
resolver.registerContentObserver(Settings.Global.getUriFor(
Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON), false, settingsObserver);
resolver.registerContentObserver(Settings.Global.getUriFor(
Settings.Global.WIFI_DISPLAY_WPS_CONFIG), false, settingsObserver);
updateSettings();
}
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION)) {
// This broadcast is sticky so we'll always get the initial Wifi P2P state
// on startup.
boolean enabled = (intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,
WifiP2pManager.WIFI_P2P_STATE_DISABLED)) ==
WifiP2pManager.WIFI_P2P_STATE_ENABLED;
if (DEBUG) {
Slog.d(TAG, "Received WIFI_P2P_STATE_CHANGED_ACTION: enabled="
+ enabled);
}
handleStateChanged(enabled);
} else if (action.equals(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION)) {
if (DEBUG) {
Slog.d(TAG, "Received WIFI_P2P_PEERS_CHANGED_ACTION.");
}
handlePeersChanged();
} else if (action.equals(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)) {
NetworkInfo networkInfo = (NetworkInfo)intent.getParcelableExtra(
WifiP2pManager.EXTRA_NETWORK_INFO);
if (DEBUG) {
Slog.d(TAG, "Received WIFI_P2P_CONNECTION_CHANGED_ACTION: networkInfo="
+ networkInfo);
}
handleConnectionChanged(networkInfo);
} else if (action.equals(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION)) {
mThisDevice = (WifiP2pDevice) intent.getParcelableExtra(
WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
if (DEBUG) {
Slog.d(TAG, "Received WIFI_P2P_THIS_DEVICE_CHANGED_ACTION: mThisDevice= "
+ mThisDevice);
}
}
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION:
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
wifiP2PService.handleOnWifiStateChanged(state);
break;
case WifiP2pManager.WIFI_P2P_PEERS_CHANGED_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()
wifiP2PService.handleOnPeersChangedResponse();
break;
case WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION:
// Broadcast when a device's details have changed,
// such as the device's name
WifiP2pDevice wifiP2pDevice = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
wifiP2PService.handleOnDeviceStatusChanged(wifiP2pDevice);
break;
case WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION:
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()) wifiP2PService.handleOnPeerConnected();
else wifiP2PService.handleOnPeerDisconnected();
break;
}
}
@Override
public synchronized void onResume() {
if (!wifiManager.isWifiEnabled()) wifiManager.setWifiEnabled(true);
wifiDirectBroadcastReceiver = new WiFiDirectBroadcastReceiver(this);
IntentFilter intentFilter = new IntentFilter();
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);
activity.registerReceiver(wifiDirectBroadcastReceiver, intentFilter);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void stopServiceDiscovery(boolean shouldUnregister) {
isDiscovering = false;
firstDeviceAlreadyFound = false;
if (isConnectedToAnotherDevice)
disconnectFromDevice();
if (shouldUnregister) {
Log.v(Salut.TAG, "Unregistered Salut reciever.");
dataReceiver.context.unregisterReceiver(receiver);
receiverRegistered = false;
}
if (manager != null && channel != null) {
manager.removeServiceRequest(channel, serviceRequest, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Log.v(TAG, "Successfully removed service discovery request.");
}
@Override
public void onFailure(int reason) {
Log.v(TAG, "Failed to remove service discovery request. Reason : " + reason);
}
});
}
}
public void startWifiDiscovery ()
{
if (mWifiEnabled)
{
mWifiManager.discoverPeers(mWifiChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
// Code for when the discovery initiation is successful goes here.
// No services have actually been discovered yet, so this method
// can often be left blank. Code for peer discovery goes in the
// onReceive method, detailed below.
Log.d(TAG,"success on wifi discover");
}
@Override
public void onFailure(int reasonCode) {
// Code for when the discovery initiation fails goes here.
// Alert the user that something went wrong.
Log.d(TAG,"FAIL on wifi discovery: " + reasonCode);
}
});
discoverWifiService();
}
}