How to connect using wifi direct for transfer file? - android

i want to build an application using wifi direct to transfer files and i'm using NFC to reduce pairing time. I've already follow the instruction in http://developer.android.com/guide/topics/connectivity/wifip2p.html and http://developer.android.com/training/connect-devices-wirelessly/wifi-direct.html but my apps won't connect. and i took the code from wifi direct demo from android example.
when i trace the problem is when wifi direct broadcast receiver WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION the network info won't to connect with other device so, in my main class that implements ConnectionInfoListener that have a method onConnectionInfoAvailable it's never triggered.
can anyone help me? thx before
the code is like this
Wifi Direct BroadCast Receiver
`
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// UI update to indicate wifi p2p status.
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wifi Direct mode is enabled
activity.setIsWifiP2pEnabled(true);
} else {
activity.setIsWifiP2pEnabled(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()
if (manager != null) {
}
//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
manager.requestConnectionInfo(channel, activity);
} else {
// It's a disconnect
}
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
WifiP2pDevice device = (WifiP2pDevice) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
activity.myname = device.deviceName + " " + device.deviceAddress + " " + device.primaryDeviceType + " " + device.secondaryDeviceType + " " + device.status;
}
}`
my main class
`
// how to connect
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = names[1];
config.wps.setup = WpsInfo.PBC;
config.groupOwnerIntent = 15;
connect(config);
public void connect(WifiP2pConfig config) {
manager.connect(channel, config, new ActionListener() {
#Override
public void onSuccess() {
// WiFiDirectBroadcastReceiver will notify us. Ignore for now.
}
#Override
public void onFailure(int reason) {
Toast.makeText(getApplicationContext(), "Connect failed. Retry.", Toast.LENGTH_SHORT).show();
}
});
}
public void disconnect() {
manager.removeGroup(channel, new ActionListener() {
#Override
public void onFailure(int reasonCode) {
//Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);
Toast.makeText(getApplicationContext(), "Disconnect failed. Reason :" + reasonCode, Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess() {
Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_SHORT).show();
}
});
}
public void onChannelDisconnected() {
// we will try once more
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();
}
}
public void onConnectionInfoAvailable(WifiP2pInfo info) {
// TODO Auto-generated method stub
this.info = info;
// After the group negotiation, we can determine the group owner.
if (info.groupFormed && info.isGroupOwner) {
// Do whatever tasks are specific to the group owner.
// One common case is creating a server thread and accepting
// incoming connections.
Toast.makeText(getApplicationContext(), "Owner", Toast.LENGTH_SHORT).show();
} else if (info.groupFormed) {
// The other device acts as the client. In this case,
// you'll want to create a client thread that connects to the group
// owner.
Toast.makeText(getApplicationContext(), "Client", Toast.LENGTH_SHORT).show();
}
}
`
onConnectionInfoAvailable will never be executed because the networkInfo.isConnected() is never true.
Please help me.. Thx..

Related

How to discover android ble services after successful pairing with pin entry?

Inside the BluetoothGattCallback method onConnectionStateChange I am checking for the successful connection with the BLE device and calling the discoverServices method afterwards. The BLE device needs a pin entry (prompt by Android) for an successful pairing. I want to discover all available services immediately after connecting to the device because when switching to the main activity of the application there should be data from the available characteristics already displayed.
I tried to analyze the functionality of the onConnectionStateChange method and the behavior of the BLE device with pin. Unfortunately the method is called once you initialize the connection and again after successfully entering the pin. There isn't a difference within the receiving state codes. Status and newState are exactly the same when initializing and after successful pin entry and connection. Therefore i added this workaround with the Thread.sleep method to wait for the user entry of the pin and call afterwards the discoverServices method. But this workaround is not very practical because the user need to enter the pin within these 10 seconds. If not the connection is successful but the services won't be discovered.
How can i check or differ between these two states? Initializing the connection and successful enter of the pin?
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.d("KOPPLUNG", "In onConnectionStateChange with status: " + status + " and newState: " + newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
broadcastUpdate(ACTION_GATT_CONNECTED, mCallbackBleAddress);
Log.i(TAG, "Connected to GATT server." + mCallbackBleAddress);
// Attempts to discover services after successful connection.
try {
Thread.sleep(10000);
} catch (Exception e) {
}
for(int i = 0; i<5; i++){
if(mBoltDeviceHandler.getBoltDevice(mCallbackBleAddress).getBluetoothGatt().discoverServices()){
Log.i(TAG, "Attempting to start service discovery:" + true);
break;
}
}
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
switch (status){
case 0: Log.i(TAG, "Sucessfully Disconnected from GATT server.");
break;
case 133: // Handle internal Android Bug
Log.i(TAG, "Connection aborted, Android Error 133");
broadcastUpdate(ACTION_GATT_CONNECTION_NOT_SUCCESSFUL, mCallbackBleAddress);
break;
default: Log.i(TAG, "Unexpected Disconnection from GATT server. Errorcode: "+status);
broadcastUpdate(ACTION_GATT_DISCONNECTED, mCallbackBleAddress);
autoconnect(gatt.getDevice());
}
Addition
The code for building up the connection is divided up in three different classes. The application starts with an scan activity where available devices are being searched and listed. By clicking on one list item (device) the connection process will be started.
onListItemClick
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
if (device == null) return;
Context mContext = getApplicationContext();
BoltDevice boltDevice = new BoltDevice(device,mContext);
int i = mBoltDeviceHandler.addBoltDevice(boltDevice);
Intent resultIntent = new Intent();
resultIntent.putExtra("IN_CONNECTION", boltDevice.getBleAddress());
resultIntent.putExtra("POSITION",i);
if(i != -1){
setResult(Activity.RESULT_OK, resultIntent);
}
else {
setResult(Activity.RESULT_CANCELED, resultIntent);
}
finish();
}
By running the above code an object from type BoltDevice is being created and added to the BoltDeviceHandler.
Relevant code from BoltDevice class
public BoltDevice(BluetoothDevice device, Context context) {
mContext = context;
this.mBluetoothDevice = device;
this.mBleAddress = device.getAddress();
this.mDeviceName = device.getName();
mBatteryLevel = 0;
mSpecialBolt = false;
//Workarround for 133 error taken from: https://github.com/googlesamples/android-BluetoothLeGatt/issues/44
mStartGattHandler.postDelayed(mStartGattRunnable, START_GATT_DELAY);
}
public void closeGatt() {
if (mBluetoothGatt != null) {
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
mBluetoothGatt = null;
}
}
public boolean connect() {
// Previously connected device. Try to reconnect.
if (mBluetoothGatt != null) {
Log.d(TAG, "Trying to connect with existing bluetoothGATT to: " + mBleAddress);
if (mBluetoothGatt.connect()) {
return true;
} else {
Log.d(TAG, "Could not connect to existing bluetoothGATT: " + mBleAddress);
return false;
}
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
mBluetoothLeService.connect(mBluetoothDevice);
Log.d(TAG, "Trying to create a new connection to: " + mBluetoothDevice.getAddress());
return true;
}
public boolean disconnect() {
if (mBluetoothGatt != null) {
mBluetoothGatt.disconnect();
return true;
} else {
return false;
}
}
public void bindService(){
Intent gattServiceIntent = new Intent(mContext, BluetoothLeService.class);
}
Relevant code from the MainActivity (active after the ScanActivity is finished)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (5) : {
if (resultCode == Activity.RESULT_OK) {
int i = data.getIntExtra("POSITION",-1);
mReconnect[i] = false;
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!isFinishing()) {
updateText(i,true);
ToastCompat.makeText(MainActivity.this, "In Connection!", ToastCompat.LENGTH_SHORT).show();
}
}
});
}
if (resultCode == Activity.RESULT_CANCELED) {
if(data!=null) {
int i = mBoltDeviceHandler.getBoltDevicePositionInList(data.getStringExtra("IN_CONNECTION"));
mReconnect[i] = true;
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!isFinishing()) {
ToastCompat.makeText(MainActivity.this, "In Connection!", ToastCompat.LENGTH_SHORT).show();
}
}
});
}
else{
ToastCompat.makeText(this,"No device selected!", ToastCompat.LENGTH_SHORT).show();
}
}
break;
}
}
}
(...)
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
final String address = intent.getStringExtra(BluetoothLeService.EXTRA_ADDRESS);
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
ToastCompat.makeText(MainActivity.this, mBoltDeviceHandler.getBoltDevice(address).getDeviceName() + " " + getResources().getString(R.string.BLE_Connected), ToastCompat.LENGTH_SHORT).show();
updateText(mBoltDeviceHandler.getBoltDevicePositionInList(address), false);
ToastCompat.makeText(MainActivity.this, mBoltDeviceHandler.getBoltDevice(address).getDeviceName()+ ": "+ getResources().getString(R.string.BLE_ServicesDiscovered), ToastCompat.LENGTH_SHORT).show();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
(...)
First of all, I would recommend using the Nordic library. That saved me a lot of headhacke when working with BLE on android and allow to keep a clean architecture.
You should have something of the state machine like :
connect to device
request GATT services / characteristic
request for the user code on Android
send user code
retrieve data over BLE
Also, after receiving a onConnection status change notifcation, you should xwait a few ms before starting discovering GATT
The onConnectionStateChange event is triggered just after the Android connects to a device.Moreover, when the device has Service Changed indication enabled, and the list of services has changed (e.g. using the DFU), the indication is received few hundred milliseconds later, depending on the connection interval. When received, Android will start performing a service discovery operation on its own, internally, and will NOT notify the app that services has changed.
public final void onConnectionStateChange(#NonNull final BluetoothGatt gatt,
final int status, final int newState) {
if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
// Sometimes, when a notification/indication is received after the device got
// disconnected, the Android calls onConnectionStateChanged again, with state
// STATE_CONNECTED.
// See: https://github.com/NordicSemiconductor/Android-BLE-Library/issues/43
if (bluetoothDevice == null) {
Log.e(TAG, "Device received notification after disconnection.");
log(Log.DEBUG, "gatt.close()");
try {
gatt.close();
} catch (final Throwable t) {
// ignore
}
return;
}
// Notify the parent activity/service
Log("Connected to " + gatt.Device.Address);
isConnected = true;
connectionState = State.Connected;
OnDeviceConnected(gatt.Device);
/*
* TODO: Please calculate the proper delay that will work in your solution.
* If your device does not use Service Change indication (for example does not have DFU) the delay may be 0.
*/
var delay = 1600; // around 1600 ms is required when connection interval is ~45ms.
postDelayed(() -> gatt.DiscoverServices(), delay);
} else {
if (newState == ProfileState.Disconnected)
{
var wasConnected = IsConnected;
if (gatt != null)
{
NotifyDeviceDisconnected(gatt.Device); // This sets the mConnected flag to false
if (_initialConnection) ConnectDevice(gatt.Device);
if (wasConnected || status == GattStatus.Success)
return;
}
}
/*
* Connection attempt did fail! Retry possible ?
*/
onError(gatt.Device, Error.LinkLost, status);
}
}

How to obtain Google Fit data from Smart watch Wearable device Fossil Q Founder? Which complies BLE requirements? In Android

I am trying to pull the data from Intel's Fossil Android based Smartwatch (BLE device) via Google Fit Android SDK. The BLE Scan seem to happen, pairing occurs but inside the result Callback it doesn't go to onDeviceFound (I can proceed from there if it reaches). It eventually times out within few seconds from the start of the scan.
Any help would be appreciated.
Thanks for the docs link. I did go through all of that thoroughly but it didn't help. This is my Class file and I can call startBleScan from my MainActivity, the BleScan seems to be working, but after that it doesn't proceed to go on to onDeviceFound method.
public class BlueToothDevicesManager {
private static final String TAG = "BlueToothDevicesManager";
private static final int REQUEST_BLUETOOTH = 1001;
private Main2Activity mMonitor;
private GoogleApiClient mClient;
public BlueToothDevicesManager(Main2Activity monitor, GoogleApiClient client) {
mMonitor = monitor;
mClient = client;
}
public void startBleScan() {
if (mClient.isConnected()) {
Log.i(TAG, "Google account is connected");
}
BleScanCallback callback = new BleScanCallback() {
#Override
public void onDeviceFound(BleDevice device) {
Log.i(TAG, "BLE Device Found: " + device.getName());
claimDevice(device);
}
#Override
public void onScanStopped() {
Log.i(TAG, "BLE scan stopped");
}
};
PendingResult result = Fitness.BleApi.startBleScan(mClient, new StartBleScanRequest.Builder()
.setDataTypes(DataType.TYPE_POWER_SAMPLE, DataType.TYPE_STEP_COUNT_CADENCE, DataType.TYPE_STEP_COUNT_DELTA, DataType.TYPE_SPEED, DataType.TYPE_ACTIVITY_SAMPLE, DataType.TYPE_DISTANCE_DELTA, DataType.TYPE_ACTIVITY_SEGMENT, DataType.TYPE_LOCATION_SAMPLE)
.setBleScanCallback(callback)
.build());
result.setResultCallback(new ResultCallback() {
#Override
public void onResult(#NonNull Result result) {
Status status = result.getStatus();
if (!status.isSuccess()) {
String a = status.getStatusCode() + "";
Log.i(TAG, a);
switch (status.getStatusCode()) {
case FitnessStatusCodes.DISABLED_BLUETOOTH:
try {
status.startResolutionForResult(mMonitor, REQUEST_BLUETOOTH);
} catch (SendIntentException e) {
Log.i(TAG, "SendIntentException: " + e.getMessage());
}
break;
}
Log.i(TAG, "BLE scan unsuccessful");
} else {
Log.i(TAG, "ble scan status message: " + status.getStatusMessage());
Log.i(TAG, "Ble scan successful: " + status.getResolution());
}
}
});
}
public void claimDevice(BleDevice device) {
//Stop ble scan
//Claim device
PendingResult<Status> pendingResult = Fitness.BleApi.claimBleDevice(mClient, device);
pendingResult.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status st) {
if (st.isSuccess()) {
Log.i(TAG, "Claimed device successfully");
} else {
Log.e(TAG, "Did not successfully claim device");
}
}
});
}
}

android wifi-direct connect success callback calling repeatedly

i trying to connect to one wifi device using wifidirect but when i run following code it's always show connected device notification infinitely may i know where i made mistake
Here is my code snippet
if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
final Context ctx = context;
//showing this pop up message always can you help me to understand this issue please
Toast.makeText(ctx, "WIFI_P2P_PEERS_CHANGED_ACTION",Toast.LENGTH_LONG).show();
if (mManager != null) {
mManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
for ( WifiP2pDevice peer : peers.getDeviceList()) {
WifiP2pDevice device=peer;
String serverName = "Android_f9c4";
if(device.deviceName.equals(serverName)){
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
mManager.connect(mChannel,config ,new ActionListener() {
//whats wrong here
#Override
public void onSuccess() {
// This fire always
Toast.makeText(ctx, "connected",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(int reason) {
// TODO Auto-generated method stub
Toast.makeText(ctx, "Not connected",Toast.LENGTH_LONG).show();
}
});
}
}
}
});
}
}
}
use
ArrayList<WifiP2pDevice> list=peers.getDeviceList();
for( WifiP2pDevice peer : list)
in place of
for ( WifiP2pDevice peer : peers.getDeviceList()) {

WIFI P2P stops discovering peers and doesn't accept connections after 2 minutes

I have been messing around with the following issue for about 2 months now.
I am building an application on a custom android board which will act as a wifi display (WFD). When I boot the board, I can easily connect from several different phones (LG Optimus G, LG Optimus G pro, Samsung S3 and S4). After connecting and watching the screen being duplicated on the TV screen attached to the custom board, I can then disconnect and if I reconnect within 2 minutes, I can connect again.
If I boot the board (or disconnect) and then wait 2 minutes, the device no longer sees the phones, and the phones sometimes sees the board, and sometimes not. If the phone sees the board, I can initiate a connect, but I cannot connect succesfully.
I have tried all kind of options, but none seem viable.
The board is running on AOSP 4.2.2
I have right now some complicated code that does restart the discoverPeers function every 40 seconds, as normally it stops after 30 seconds. Besides that I disable WFD and re-enable it, with a 4 second delay between it.
I also tried disabling and reenabling p2p and the channel, all with no result.
Below is my code, the receiver is in a separate class.
#Override
protected void onCreate(Bundle savedInstanceState)
{
Settings.System.putInt(getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER);
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
setContentView(R.layout.wifi_direct_discovery);
connectPicture = findViewById(R.id.LinearLayout1);
Log.d(TAG, "onCreate");
isConnecting = false;
localWifiP2pWfdInfo = new WifiP2pWfdInfo();
localWifiP2pWfdInfo.setWfdEnabled(true);
localWifiP2pWfdInfo.setDeviceType(1);
localWifiP2pWfdInfo.setSessionAvailable(true);
localWifiP2pWfdInfo.setControlPort(7236);
localWifiP2pWfdInfo.setMaxThroughput(50);
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
super.onCreate(savedInstanceState);
}
#Override
public void onPeersAvailable(WifiP2pDeviceList peers)
{
List<WifiP2pDevice> peersList = new ArrayList<WifiP2pDevice>();
final ArrayList<String> list = new ArrayList<String>();
final ListView listview = (ListView) findViewById(R.id.deviceListView);
peersList.clear();
peersList.addAll(peers.getDeviceList());
if (peersList.size() == 0)
{
Log.d(TAG, "No devices found");
list.clear();
if ((pd != null) && pd.isShowing() && (isConnecting == false))
{
pd.dismiss();
Log.d(TAG, "Closed connecting dialog, restarting P2P");
Toast.makeText(this, "Connection failed please try again", Toast.LENGTH_LONG).show();
restartP2p(false);
}
else if (isConnecting == false)
{
restartP2p(false);
}
listview.setAdapter(new ArrayAdapter<String>(this, R.layout.list_black_text, R.id.list_content, list));
return;
}
else
{
int i = 0;
boolean found = false;
for (i = 0; i < peersList.size(); i++)
{
Log.d(TAG, "Found device: " + peersList.get(i).toString());
list.add(peersList.get(i).deviceName);
if ((pd != null) && pd.isShowing())
{
if (peersList.get(i).deviceAddress.equalsIgnoreCase(client.deviceAddress))
{
found = true;
}
}
}
if (!found)
{
if ((pd != null) && pd.isShowing())
{
Log.d(TAG, "Failed to find current client: closed connecting dialog, restarting P2P");
Toast.makeText(this, "Disconnected please try again", Toast.LENGTH_LONG).show();
restartP2p(false);
}
else
{
Log.d(TAG, "Failed to find current client, but we weren't trying to connect");
}
}
}
listview.setAdapter(new ArrayAdapter<String>(this, R.layout.list_black_text, R.id.list_content, list));
}
#Override
public void onConnectionInfoAvailable(WifiP2pInfo p2pInfo)
{
if (p2pInfo.isGroupOwner)
{
stopP2PDispeerTimeoutThread();
Log.d(TAG, "Connected as group owner");
int i = p2pInfo.mWfdRtspPort;
Log.d(TAG, "------------------------- onConnectionInfoAvailable rtsp port = " + i);
// get the ip addres from the connected client. Mac address is in
// client
String sourceIP = null;
while (sourceIP == null)
{
sourceIP = getIPFromMac(client.deviceAddress);
millisleep(250);
if (sourceIP == null)
{
Log.e(TAG, "Failed to get client address!!!!! from " + client.deviceAddress);
}
}
if (i == 0)
{
// this is not a wfd source, so let's get into client mode for
// upgrade etc.
Log.e(TAG, "This device is not a WFD source, so switch to client mode, device = "
+ client.deviceAddress);
}
else
{
Log.d(TAG, "Start connect to source : " + sourceIP);
if ((pd != null) && pd.isShowing())
pd.dismiss();
// need to stop the connection timeout thread here..
stopConnectTimeoutThread();
Intent intent = new Intent(getBaseContext(), WFDPlayActivity.class);
intent.putExtra("SOURCE_IP", sourceIP);
intent.putExtra("RTSPPORT", i);
startActivityForResult(intent, 210);
}
}
else
{
Log.e(TAG, "Connected as peer, this is very very wrong!!!!, restartP2P");
restartP2p(false);
startP2PDispeerTimeoutThread(34);
}
}
#Override
public void onConnectionRequested(WifiP2pDevice arg0, WifiP2pConfig arg1)
{
Log.d(TAG, "------------------------------------- onConnectionRequested");
stopP2PDispeerTimeoutThread();
isConnecting = true;
client = arg0;
if ((pd != null) && (pd.isShowing()))
{
pd.dismiss();
}
if (client != null)
{
createConnectionProgressDialog(client.deviceName);
}
}
public void onResume()
{
if (first_time == false)
{
Log.d(TAG, "onResume");
intentFilter.addAction("android.net.wifi.p2p.STATE_CHANGED");
intentFilter.addAction("android.net.wifi.p2p.PEERS_CHANGED");
intentFilter.addAction("android.net.wifi.p2p.CONNECTION_STATE_CHANGE");
intentFilter.addAction("android.net.wifi.p2p.THIS_DEVICE_CHANGED");
registerReceiver(receiver, intentFilter);
if (!mP2PDispeerThread.isRunning)
startP2PDispeerTimeoutThread(34);
manager.setDialogListener(channel, this);
manager.discoverPeers(channel, new WifiP2pManager.ActionListener()
{
#Override
public void onSuccess()
{
Log.d(TAG, "discoverPeers success");
}
#Override
public void onFailure(int reasonCode)
{
Log.d(TAG, "discoverPeers failed");
}
});
}
else
{
Log.d(TAG, "onResume, first time");
restartP2p(first_time);
first_time = false;
}
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
super.onResume();
}
public void restartP2p(boolean first)
{
if (first)
{
mWifiManager = ((WifiManager) getSystemService("wifi"));
mWifiManager.setWifiEnabled(true);
sleep(4); // was 4
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
manager.enableP2p(channel);
sleep(3); // was 3
mDisplayManager = ((DisplayManager) getSystemService("display"));
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);
mlock = mWifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF , "LockTag");
mlock.acquire();
instance = this;
receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
registerReceiver(receiver, intentFilter);
manager.setWFDInfo(channel, localWifiP2pWfdInfo, new WifiP2pManager.ActionListener()
{
public void onFailure(int paramAnonymousInt)
{
Log.d(TAG, "Failed to set WFD info with reason " + paramAnonymousInt + ".");
}
public void onSuccess()
{
Log.d(TAG, "updateWfdEnableState");
}
});
sleep(1);
manager.setDialogListener(channel, this);
manager.discoverPeers(channel, new WifiP2pManager.ActionListener()
{
#Override
public void onSuccess()
{
Log.d(TAG, "discoverPeers success");
}
#Override
public void onFailure(int reasonCode)
{
Log.d(TAG, "discoverPeers failed");
}
});
}
else
{
manager.stopPeerDiscovery(channel, new WifiP2pManager.ActionListener()
{
#Override
public void onSuccess()
{
Log.d(TAG, "stopPeerDiscovery success");
}
#Override
public void onFailure(int reasonCode)
{
Log.d(TAG, "stopPeerDiscovery failed");
}
});
localWifiP2pWfdInfo.setWfdEnabled(false);
manager.setWFDInfo(channel, localWifiP2pWfdInfo, new WifiP2pManager.ActionListener()
{
public void onFailure(int paramAnonymousInt)
{
Log.d(TAG, "Failed to set WFD info with reason " + paramAnonymousInt + ".");
}
public void onSuccess()
{
Log.d(TAG, "updateWfdEnableState");
}
});
sleep(4);
localWifiP2pWfdInfo.setWfdEnabled(true);
manager.setWFDInfo(channel, localWifiP2pWfdInfo, new WifiP2pManager.ActionListener()
{
public void onFailure(int paramAnonymousInt)
{
Log.d(TAG, "Failed to set WFD info with reason " + paramAnonymousInt + ".");
}
public void onSuccess()
{
Log.d(TAG, "updateWfdEnableState");
}
});
manager.discoverPeers(channel, new WifiP2pManager.ActionListener()
{
#Override
public void onSuccess()
{
Log.d(TAG, "discoverPeers success");
}
#Override
public void onFailure(int reasonCode)
{
Log.d(TAG, "discoverPeers failed");
}
});
}
if (first)
startP2PDispeerTimeoutThread(40); // only start the thread 1 time...
}
In the logging initially I see that the device and the phone connect successfully.
After disconnect, I see the devices being lost in the log, and after that, when I try to connect, I see the message:
I/wpa_supplicant(1839): [CTRL_IFACE]p2p0: P2P_CONNECT da:57:ef:cb:8e:be pbc go_intent=0
After this everything stops, the application is still running, I could see that from a log line that runs every second in the thread that stops and restarts the discovery every 40 seconds.
If anyone has any idea left why this behavior is happening, let me know. The only way to recover right now is to reboot the board (but that is not an option).
Thanks for your replies,
Arvy

Trying to collect wifi data like Metal Gear Solid Portable Ops

I'm trying to create an app that scans for wifi. When the player does something in the game, it "consumes" the strongest wifi signal. That signal should no longer be detected on the next scan.
Anyone who's played Metal Gear Solid Portable ops would know what I mean.
I tried to do this by creating a List of Wireless Signals that have already been used by the player and can no longer be detected again. The problem is that after scanning the best network, I scan again and it still displays the same network instead of ignoring it.
public void onClick(View arg0) {
if (arg0.getId() == R.id.bStart) {
ActivityLoader.loadMain(this);
}
if (arg0.getId() == R.id.bScan) {
Toast.makeText(this, "Searching....", Toast.LENGTH_LONG).show();
for (ScanResult selectedSpot : networkList) {
{
if (firstSignal == null || checkIfNotUsed(firstSignal)) {
firstSignal = selectedSpot;
usedNetworks.add(firstSignal.SSID);
break;
}
}
}
}
if (firstSignal != null) {
Toast.makeText(
this,
"Found Food and Ammo at the " + firstSignal.SSID
+ " store.", Toast.LENGTH_LONG).show();
// textStatus.setText(usedNetworks.toString());
textStatus.setText(networkList.toString());
} else {
Toast.makeText(this, "Found nothing!!!", Toast.LENGTH_LONG).show();
}
}
private boolean checkIfNotUsed(ScanResult selectedSpot) {
// TODO Auto-generated method stub
boolean flag = true;
if (usedNetworks.isEmpty()) {
flag = true;
} else {
for (String used : usedNetworks) {
if (selectedSpot.SSID.equals(used)) {
flag = false;
break;
}
}
}
return flag;
}

Categories

Resources