public void connect(WifiP2pConfig config) { manager.connect(channel, config, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { // WiFiDirectBroadcastReceiver will notify us. Ignore for now. peerListener.connectionSuccess(); } @Override public void onFailure(int reason) { peerListener.connectionFailure(); Toast.makeText(activity, "Connect failed. Retry.", Toast.LENGTH_SHORT).show(); } }); }
public WiFiDirectConnection(Activity activity, WiFiTransfer transfer) { this.activity = activity; this.transfer = transfer; 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); manager = (WifiP2pManager) activity.getSystemService(Context.WIFI_P2P_SERVICE); channel = manager.initialize(activity.getApplicationContext(), activity.getMainLooper(), channelListener); channelListener = new ChannelListener(); connectionInfoListener = new ConnectionInfoListener(); }
public void discoverPeers () { mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { // Code for when the discovfindNeighborsery 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. } @Override public void onFailure(int reasonCode) { // Code for when the discovery initiation fails goes here. // Alert the user that something went wrong. } }); }
private void connectToPeer (WifiP2pDevice device) { WifiP2pConfig config = new WifiP2pConfig(); config.deviceAddress = device.deviceAddress; config.wps.setup = WpsInfo.PBC; mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { // WiFiDirectBroadcastReceiver will notify us. Ignore for now. } @Override public void onFailure(int reason) { } }); }
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); statusTxtView = (TextView) findViewById(R.id.status_text); 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); startRegistrationAndDiscovery(); servicesList = new WiFiDirectServicesList(); getFragmentManager().beginTransaction() .add(R.id.container_root, servicesList, "services").commit(); }
@Override public void onFailure(int reason) { String errorMessage = ""; switch (reason){ case WifiP2pManager.BUSY: errorMessage="busy"; break; case WifiP2pManager.ERROR: errorMessage="error"; break; case WifiP2pManager.P2P_UNSUPPORTED: errorMessage="p2p unsupported"; break; } Log.d(tag,"onError: " + errorMessage); }
/** * 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); } }
/** * WiFi Directに対応した機器探索を開始 * @throws IllegalStateException */ public synchronized void startDiscovery() throws IllegalStateException { if (DEBUG) Log.v(TAG, "startDiscovery:"); if (mChannel != null) { mWifiP2pManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { } @Override public void onFailure(final int reason) { callOnError(new RuntimeException("failed to start discovery, reason=" + reason)); } }); } else { throw new IllegalStateException("not registered"); } }
/** * 指定した機器へ接続を試みる * @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); } } }
/** * Handle incoming messages. This class handles broadcasts sent by WifiP2pManager. * We handle them by calling other methods in the class as appropriate to handle * each type of event. One specific method is called for each type of event * and handles all the logic related to that event. * * @see android.content.BroadcastReceiver#onReceive(android.content.Context, * android.content.Intent) */ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { onWifiP2pStateChanged(context, intent); } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { onWifiP2pPeersChanged(context, intent); } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) { onWifiP2pConnectionChanged(context, intent); } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) { onWifiP2pThisDeviceChanged(context, intent); } else if (WifiP2pManager.WIFI_P2P_DISCOVERY_CHANGED_ACTION.equals(action)) { onWifiP2pDiscoveryChanged(context, intent); } else { // TODO(lerner): This shouldn't happen, exception? Log.wtf(TAG, "Received an event we weren't expecting: " + action); } }
/** * Receives events indicating whether Wifi Direct is enabled or disabled. */ private void onWifiP2pStateChanged(Context context, Intent intent) { // Since int is a simple type, we have to provide a default value // in case the requested key isn't contained as an extra. int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, DEFAULT_EXTRA_INT); if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) { Log.d(TAG, "Wifi Direct enabled"); // Wifi Direct mode is enabled // TODO(lerner): Do something since it's enabled? } else if (state == WifiP2pManager.WIFI_P2P_STATE_DISABLED) { Log.d(TAG, "Wifi Direct disabled"); // Wifi Direct mode is disabled // TODO(lerner): Do something since it's disabled? } else if (state == DEFAULT_EXTRA_INT) { Log.e(TAG, "Wifi P2P state changed event handled, but the intent " + "doesn't include an int to tell whether it's enabled or " + "disabled!"); } }
/** * Issue a request to the WifiP2pManager to start discovering peers. * This is an internal method. To turn on/off peer discovery from higher * level application code, call setSeekingDesired(true/false). */ private void seekPeers() { // DO NOT SUBMIT // Switched this to be && if (!getSeeking() && lastSeekingWasLongAgo()) { setSeeking(true); touchLastSeekingTime(); stopwatch.reset(); stopwatch.start(); mWifiP2pManager.discoverPeers(mWifiP2pChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.d(TAG, "Discovery initiated"); } @Override public void onFailure(int reasonCode) { Log.d(TAG, "Discovery failed: " + reasonCode); setSeeking(false); stopSeekingPeers(); } }); } else { Log.v(TAG, "Attempted to seek peers while already seeking, not doing it."); } }
/** * Handle incoming messages. This class handles broadcasts sent by WifiP2pManager. * We handle them by calling other methods in the class as appropriate to handle * each type of event. One specific method is called for each type of event * and handles all the logic related to that event. * * @see android.content.BroadcastReceiver#onReceive(android.content.Context, * android.content.Intent) */ public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(!initialized){ Log.d("peerDebug", "received action:"+action+", but speaker not yet initialized, ignoring transmission"); log.warn("received action:"+action+", but speaker not yet initialized, ignoring transmission"); return; } if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { onWifiP2pStateChanged(context, intent); } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { onWifiP2pPeersChanged(context, intent); } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) { onWifiP2pConnectionChanged(context, intent); } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) { onWifiP2pThisDeviceChanged(context, intent); } else if (WifiP2pManager.WIFI_P2P_DISCOVERY_CHANGED_ACTION.equals(action)) { onWifiP2pDiscoveryChanged(context, intent); } else { // TODO(lerner): This shouldn't happen, exception? log.error( "Received an event we weren't expecting: " + action); Log.d("peerDebug", "Received an event we weren't expecting: " + action); } }
/** * Receive events noting when Android has started or stopped looking * for Wifi P2P peers. */ private void onWifiP2pDiscoveryChanged(Context context, Intent intent) { int discoveryStateCode = intent.getIntExtra(WifiP2pManager.EXTRA_DISCOVERY_STATE, -1); if (discoveryStateCode == WifiP2pManager.WIFI_P2P_DISCOVERY_STARTED) { log.debug( "Device is seeking Wifi Direct peers."); Log.d("peerDebug", "Device is seeking Wifi Direct peers."); setSeeking(true); } else if (discoveryStateCode == WifiP2pManager.WIFI_P2P_DISCOVERY_STOPPED) { log.debug( "Device is NOT seeking Wifi Direct peers."); Log.d("peerDebug", "Device is NOT seeking Wifi Direct peers."); setSeeking(false); } else { log.error( "Discovery changed event didn't have an EXTRA_DISCOVERY_STATE?!"); Log.d("peerDebug", "Discovery changed event didn't have an EXTRA_DISCOVERY_STATE?!"); } }
@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 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()); } }); } }
private void addServiceDiscoveryRequest() { serviceRequest = WifiP2pDnsSdServiceRequest.newInstance(); // Tell the framework we want to scan for services. Prerequisite for discovering services wifiP2pManager.addServiceRequest(channel, serviceRequest, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.i(TAG, "Service discovery request added"); } @Override public void onFailure(int reason) { Log.e(TAG, "Failure adding service discovery request: " + FailureReason.fromInteger(reason).toString()); serviceRequest = null; } }); }
/** * 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()); } }); }
/** * Creates a service that can be connected to without prompting. This is possible by creating an * access point and broadcasting the password for peers to use. Peers connect via normal wifi, not * wifi direct, but the effect is the same. */ public void startAddingNoPromptService(ServiceData serviceData) { if (wifiP2pServiceInfo != null) { removeService(); } isCreatingNoPrompt = true; noPromptServiceData = serviceData; wifiP2pManager.createGroup(channel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.i(TAG, "Group created successfully"); //Note that you will have to wait for WIFI_P2P_CONNECTION_CHANGED_INTENT for group info } @Override public void onFailure(int reason) { Log.i(TAG, "Group creation failed: " + FailureReason.fromInteger(reason)); } }); }
public void discoverDevice() { Log.d(TAG, "WifiP2pHelper-->discoverDevice()"); if (!isWifiOn()) { toggleWifi(true); } if (isConnected) { Log.d(TAG, "WifiP2pHelper-->discoverDevice ended-->isConnected=true"); return; } handler.sendEmptyMessage(WIFIP2P_DEVICE_DISCOVERING); manager.discoverPeers(channel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { } @Override public void onFailure(int reasonCode) { Log.d(TAG, "WifiP2pHelper-->discoverDevice failed reasonCode=" + reasonCode); } }); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_wifidirect); // add necessary intent values to be matched. 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); intentFilter_update.addAction("UPDATE_PEERS"); manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); channel = manager.initialize(this, getMainLooper(), null); }
@Override public void connect(WifiP2pConfig config) { manager.connect(channel, config, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { // WiFiDirectBroadcastReceiver will notify us. Ignore for now. } @Override public void onFailure(int reason) { Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.", Toast.LENGTH_SHORT).show(); } }); }
@Override public void disconnect() { final DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager() .findFragmentById(R.id.frag_detail); fragment.resetViews(); manager.removeGroup(channel, new WifiP2pManager.ActionListener() { @Override public void onFailure(int reasonCode) { Log.d(TAG, "Disconnect failed. Reason :" + reasonCode); } @Override public void onSuccess() { fragment.getView().setVisibility(View.GONE); } }); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.wifi_activity_main); // add necessary intent values to be matched. 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); intentFilter_update.addAction("UPDATE_PEERS"); manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); channel = manager.initialize(this, getMainLooper(), null); }
@Override public void connect(WifiP2pConfig config) { manager.connect(channel, config, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Toast.makeText(WiFiDirectActivity.this, "连接成功,选择文件发送", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(int reason) { Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.", Toast.LENGTH_SHORT).show(); } }); }
@Override public void onReceive(Context context, Intent intent) { action = intent.getAction(); Log.v("Wifip2pBR","on receive. action: " + action); networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO); wifiP2pInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_INFO); wifiP2pDevice = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE); Log.v("Wifip2pBR","on receive. networkinfo: " + networkInfo); Log.v("Wifip2pBR","on receive. wifiP2pInfo: " + wifiP2pInfo); Log.v("Wifip2pBR","on receive. wifiP2pDevice: " + wifiP2pDevice); if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { // Call WifiP2pManager.requestPeers() to get a list of current peers if (networkingService.mManager != null && !networkingService.connected) { networkingService.mManager.requestPeers(networkingService.mChannel, networkingService.peerListListener); } } }