How to create a button that starts WiFi direct - android

I have no prior experience with app development and am now supposed to create an app in android studio that connects to a sensor by WiFi-direct. I have read up on WiFi-direct and tried to follow the guides https://developer.android.com/guide/topics/connectivity/wifip2p.html and https://stuff.mit.edu/afs/sipb/project/android/docs/training/connect-devices-wirelessly/wifi-direct.html but when using their code I have still no clue how to move forward. I have also looked at several demo apps for WiFi direct.
My code looks like this at the moment.
Broadcast reciever:
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel,
MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// Check to see if Wi-Fi is enabled and notify appropriate activity
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
mActivity.setIsWifiP2pEnabled(true);
} else {
mActivity.setIsWifiP2pEnabled(false);
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// Call WifiP2pManager.requestPeers() to get a list of current peers
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Respond to new connection or disconnections
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Respond to this device's wifi state changing
}
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
private boolean isWifiP2pEnabled = false;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
this.isWifiP2pEnabled = isWifiP2pEnabled;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
}
/* register the broadcast receiver with the intent values to be matched */
#Override
protected void onResume() {
super.onResume();
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
registerReceiver(mReceiver, mIntentFilter);
}
/* unregister the broadcast receiver */
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
}
The next part in the guide is that I should try to discover peers. Where should I implement this code?
mManager.discoverPeers(mChannel, 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.
}
#Override
public void onFailure(int reasonCode) {
// Code for when the discovery initiation fails goes here.
// Alert the user that something went wrong.
}
});
My final product should be a button that when I press it I should search for peers and be able to connect to one. The sensor will boot in WiFi direct. Does anyone know where I can find more info on how to proceed or have tips on what classes I need and such?
Thank you!

The way it works is by:
Calling discoverPeers when tapping on the button
Next, in your WiFiDirectBroadcastReceiver -> WIFI_P2P_PEERS_CHANGED_ACTION condition, request the list of available peers like this: mManager.requestPeers(mChannel, peerListListener);
Then, you have to implement WifiP2pManager.PeerListListener in your activity or fragment because the discovered peers will return into this method:
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {}
Once you have the list of peers, you can connect to any peer using
mManager.connect(mChannel, config, new ActionListener() {});
I believe following https://developer.android.com/guide/topics/connectivity/wifip2p.html is good enough to get the api working.
Goodluck.

Related

intent ACTION_BATTERY_LOW broadcast firing every ten seconds. Why?

I'm writing a service that must accept and react on ACTION_BATTERY_LOW broadcast. I'm using next code:
public class MyService extends Service {
...
private final BroadcastReceiver batteryBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(LOG_TAG, "batteryBroadcastReceiver.onReceive()->intent="+intent.toString());
if(intent.getAction().equals(Intent.ACTION_BATTERY_LOW))
Log.d(LOG_TAG, "intent.getAction() == Intent.ACTION_BATTERY_LOW!");
}
};
public void onCreate() {
super.onCreate();
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
registerReceiver(batteryBroadcastReceiver,intentFilter);
}
public void onDestroy() {
super.onDestroy();
unregisterReceiver(batteryBroadcastReceiver);
}
}
When battery charge level goes to low (~15%) Android sends an intent with action ACTION_BATTERY_LOW and then sends it again every 10 seconds which I'm receiving in MyServive. Why does it happen? What can I do or what I'm doing wrong? Tested on real device.
The period to send Intent.ACTION_BATTERY_LOW is up to the OS and the manufacturer. It's informed periodically so you have updated information through time and you can make better decisions.
I don't know what do you want to accomplish but if you are getting the action repeated you can monitor also Intent.ACTION_BATTERY_OKAY and have a flag indicating whether the action for the low battery has been made. That flag changes its value depending on the action the broadcastReceiver receives, e.g.
public class MyService extends Service {
...
private final BroadcastReceiver batteryBroadcastReceiver = new BroadcastReceiver() {
private bool mBatteryLowActionHasBeenMade = false;
#Override
public void onReceive(Context context, Intent intent) {
Log.d(LOG_TAG, "batteryBroadcastReceiver.onReceive()->intent="+intent.toString());
if(intent.getAction().equals(Intent.ACTION_BATTERY_LOW) && !this.mBatteryLowActionHasBeenMade ) {
Log.d(LOG_TAG, "intent.getAction() == Intent.ACTION_BATTERY_LOW!");
this.mBatteryLowActionHasBeenMade = true;
}
if(intent.getAction().equals(Intent.ACTION_BATTERY_OKAY)) {
this.mBatteryLowActionHasBeenMade = false;
}
}
};
public void onCreate() {
super.onCreate();
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
intentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
registerReceiver(batteryBroadcastReceiver,intentFilter);
}
public void onDestroy() {
super.onDestroy();
unregisterReceiver(batteryBroadcastReceiver);
}
}
If that doesn't fit your requirements try monitoring the battery level with Intent.ACTION_BATTERY_CHANGED

Android Wifi Direct onPeersAvailable doesn't shows anything

I'm trying to develop a simple app using Wifi Direct. The problem is I can't get a list of available peers using onPeersAvailable method. I tried the solutions mentioned here and here but no luck.There is nothing at logs, tried using Toast instead of log but nothing showed up on the screen either. Here is my Main and BroadCastReceiver classes.
Main Class:
public class MainActivity extends AppCompatActivity {
private final String TAG = this.getClass().toString();
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
Button btn_discover = (Button) findViewById(R.id.btn_discover);
btn_discover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
/*Toast.makeText(getApplicationContext(), "Discovery is a success.",
Toast.LENGTH_SHORT).show();*/
//startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
#Override
public void onFailure(int reasonCode) {
Toast.makeText(getApplicationContext(), "Discovery is a failure "+reasonCode,
Toast.LENGTH_SHORT).show();
}
});
}
});
}
/* register the broadcast receiver with the intent values to be matched */
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
/* unregister the broadcast receiver */
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}}
BroadCastReceiver class:
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private final String LOG_TAG = this.toString();
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel,
MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
Log.i(LOG_TAG, "Wifi Direct is enabled");
} else {
Log.i(LOG_TAG, "Wifi Direct is not enabled");
}
} 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 (mManager != null) {
mManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList) {
Log.i(LOG_TAG, "Found some peers!!! "+wifiP2pDeviceList.getDeviceList().size());
}
});
}
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Respond to new connection or disconnections
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Respond to this device's wifi state changing
}
}}
I am sure my device (2012 Nexus 7 running Android 4.4.4) supports Wifi Direct.
I think the issue is because you are creating new "PeerListListener" inside the "WiFiDirectBroadcastReceiver".
Try to add it to your main activity instead:
public class MainActivity extends AppCompatActivity implements WifiP2pManager.PeerListListener
And then add new method to you main activity to listen to available peers:
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
Log.i(LOG_TAG, "Found some peers!!! " + peerList.getDeviceList().size());
}
Note: Don't forget to create new listener variable instead "WiFiDirectBroadcastReceiver" and pass the main activity as a reference to it.
Hope this helps.

OnReceive() method auto triggered

I have created the one receiver inside an Activity for when internet is connected auto calling web service.
Code like
//Create receiver for while network will come auto call webservice
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (!noConnectivity) {
bar.setVisibility(View.VISIBLE);
callAuthorizeWebservice();
} else {
bar.setVisibility(View.INVISIBLE);
Toast.makeText(SplashScreenActivity.this, "Check Your Internet connection", Toast.LENGTH_LONG).show();
}
}
};
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(mConnReceiver);
}
#Override
protected void onStart() {
super.onStart();
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
When I open that Activity the onReceive() is method called everytime.
How to avoid calling it the first time (when opening that Activity)?
The broadcast is sent when you register for the first time(cf sticky broadcast), a solution is to use isInitialStickyBroadcast in the onReceive callback of your BroadcastReceiver to know if you are actually proceeding a sticky broadcast and act accordingly (BroadcastReceiver : isInitialStickyBroadcast)

Android:The if statement of wifi scan result is not being entered?

I have built BroadcastReceiver in my MainActivity to catch system broadcast(internet connection and wifi scan result). The internet connection broadcast is being caught but I am facing problem to catch the broadcast of the wifi scan result. no error is being thrown. I do not know what shall I add additional to get it work. I appreciate any help.
MainActivity:
public class MainActivity extends ActionBarActivity {
BroadcastReceiverListener receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new BroadcastReceiverListener();
}
private class BroadcastReceiverListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//This if statement is being arrived
if (intent.getAction().equals(
android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
//This code works without BroadcastReceiver.
}
else if (intent.getAction().equals(
android.net.ConnectivityManager.CONNECTIVITY_ACTION)) {
// I am getting here broadcast for the internet connection
}
}
};
protected void onResume() {
IntentFilter wifi = new IntentFilter();
wifi.addAction(android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(receiver, wifi);
IntentFilter conn = new IntentFilter();
conn.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(receiver, conn);
super.onResume();
}
#Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
}
There's no need to create two IntentFilters, just create the one and use addAction() to add multiple actions:
IntentFilter wifi = new IntentFilter();
wifi.addAction(android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
wifi.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(receiver, wifi);
See here:
Android - Registering a broadcast receiver for two intents?

How to reboot my current activity,when i connect net?

I am developing an application and I am displaying images from URl using xml parsing.
When internet gets disconnected I pop up alert window.
Now I wan my current activity automatically reboot, when my device connect net.
You need to have a BroadcastReceiver to listen to internet changes.
If you just need this logic in your activity you can do something like this:
private BroadcastReceiver mReceiver;
private IntentFilter mFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
mFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
mReceiver = new ConnectionChangeReceiver();
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
private class ConnectionChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent i) {
ConnectivityManager connectivityManager = (ConnectivityManager) ActivityActionBar.this
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getActiveNetworkInfo() == null) {
onLoseInternet();
}
}
}
onLoseInternet() method you should do something to reset everything.
Possibilities:
Best way I found so far
In the onCreate() method I have two calls: getWidgets() and populateWidgets().
getWidgets() is in charge of doing all the findViewById stuff and populateWidgets() will basically populate them with the correct info.
So when I need to reset the info I just call populateWidgets().
Hacky way
I don't know if this will work but you can try doing:
finish();
startActivity(new Intent(this, this.class));

Categories

Resources