I have an application that uses an AsyncTask to connect to WiFi using WifiManager.
Now, I am using this in my MainActivity class as
public class connectWifi extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
public connectWifi(MyActivity activity) {
dialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Connecting to WiFi. Please Wait.");
dialog.show();
}
#Override
protected void onPostExecute(Void result) {
connected = true;
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo conn = wifi.getConnectionInfo();
Context context = getApplicationContext();
CharSequence wifi_on = "Connected to " + conn.getSSID();
int duration = Toast.LENGTH_LONG;
Toast responseToast = Toast.makeText(context, wifi_on, duration);
responseToast.show();
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... voids) {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
try {
Thread.sleep(3000);
} catch (Exception e) {
}
return null;
}
}
Now, I have another class AlarmReceiver which gets called via a Broadcast. I am performing some network based action in that class which needs me to connect to WiFi first.
How can I create a separate class for connectWifi which does not involve first running MainActivity?
The issue I am facing is in creating the Context object which says Non-static 'getApplicationContext()' cannot be referenced from static context.
The same issue is with getSystemService(). How can I create this class as needed?
abc is the AsyncTask class.
AlarmReceiver is the BroadcastReceiver
My current flow of control is as follows:
START PROCEDURE
- AlarmManager receives Broadcast
- AlarmManager calls enableWifi() in abc
- enableWifi() connects to WiFi
- AlarmManager checks for connection state
- AlarmManager then calls new abc().execute("DATA1")
- abc then performs the doInBackground task (network request)
- AlarmManager calls disableWifi() in abc to end WiFi
END PROCEDURE
You can create a separated class that depends on Context. Both Activity and a BroadcastReceiver can provide a Context to this class.
Activity is a subclass of Context, so you can pass the Activity as parameter.
And the first parameter of onReceive from BroadcastReceiver is the Context.
So you can create an class that receives an Context instance an use the WifiManager:
// This can run outside UI Thread
public static void enableWifi(Context context) {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
// This must run on UI Thread
public static void verifyWifi(Context context) {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo conn = wifi.getConnectionInfo();
CharSequence wifi_on = "Connected to " + conn.getSSID();
int duration = Toast.LENGTH_LONG;
Toast.makeText(context, wifi_on, duration).show();
}
You can use this class to detect when Wifi is enabled or change it's state.
public class NetworkChangeReceiver extends BroadcastReceiver {
// Static Listener, you can change this
static OnNetworkConnectionChangedListener mListener;
// Service to check if Wifi is connected or not
ConnectivityManager mConnectivityManager;
#Override
public void onReceive(Context context, Intent intent) {
if(mListener != null) {
if(mConnectivityManager == null) {
mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
mListener.onConnectionChanged(NetworkStatusHelper.getConnectivityStatus(mConnectivityManager) != NetworkStatusHelper.TYPE_NOT_CONNECTED);
}
}
public static boolean isConnected(Context context) {
return NetworkStatusHelper.getConnectivityStatus((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)) != NetworkStatusHelper.TYPE_NOT_CONNECTED;
}
public static void setOnNetworkConnectionChangedListener(OnNetworkConnectionChangedListener listener) {
mListener = listener;
}
public interface OnNetworkConnectionChangedListener {
public void onConnectionChanged(boolean connected);
}
}
With this you i'll need to require the ACCESS_NETWORK_STATE permission.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And you i'll need to add a receiver for CONNECTIVITY_CHANGE and WIFI_STATE_CHANGED
<receiver
android:name="yourpackage.NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
With this you can track when Wifi change its connectivity and is connected.
Related
I have SplashActivity, Activity A and Activity B.
When the Internet is not available, Splash activity redirects to Activity A and when Internet is available and is connected SplashActivity redirects to Activity B.
I would like to immediately close the Activity A when user is connected itself and Open Activity B when user is still inside the app and he open his wifi or mobile Data.
Here is the code I'm using in SplahsActivity to redirect to Activity A and Activity B as per Network status
public static boolean isNetworkStatusAvialable(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
and I check with
if (isNetworkStatusAvialable(getApplicationContext())) {
// Load Activity B
} else {
Load Activity A and Toast Message, " No Internet"
}
Thanks in advance.
In this case you should check network status using BroadcastReceiver because you immediately want to close current activity and move to other activity. So below is complete code for it:
ConnectivityStatusReceiver.java
public class ConnectivityStatusReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
Toast.makeText(context, activeNetworkInfo.getTypeName() + " connected", Toast.LENGTH_SHORT).show();
// Your code to start Activity B
Activity activity = (Activity) context;
intent = new Intent(activity, ActivityB.class);
activity.startActivity(intent);
} else {
Toast.makeText(context, "No Internet or Network connection available", Toast.LENGTH_LONG).show();
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ConnectivityStatusReceiver connectivityStatusReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectivityStatusReceiver = new ConnectivityStatusReceiver();
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectivityStatusReceiver, intentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (connectivityStatusReceiver != null) {
// unregister receiver
unregisterReceiver(connectivityStatusReceiver);
}
}
}
To close Activity A you just add android:noHistory="true" in Manifest like below:
<activity android:label="#string/app_name" android:name="ActivityA"/>
Hope this will help you.
I have to show a notification when the device is connected to internet.
Do i need to run a service all the time for this?
ConnectivityReceiver.java
public class ConnectivityReceiver
extends BroadcastReceiver {
public static ConnectivityReceiverListener connectivityReceiverListener;
public ConnectivityReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent arg1) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
if (connectivityReceiverListener != null) {
connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
}
}
public static boolean isConnected() {
ConnectivityManager
cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
}
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}}
MyApplication.java
public class MyApplication extends Application {
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}}
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".MyApplication"
android:allowBackup="true"
...
<receiver
android:name=".ConnectivityReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
...
</application>
Activity.class
public class MainActivity extends AppCompatActivity
implements ConnectivityReceiver.ConnectivityReceiverListener {
...
#Override
protected void onResume() {
super.onResume();
// register connection status listener
MyApplication.getInstance().setConnectivityListener(this);
}
...
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
if(isConnected){
Toast.makeText(context, "Internet Connected", Toast.LENGTH_SHORT).show();
}else{Toast.makeText(context, "Internet not Connected", Toast.LENGTH_SHORT).show();}
}}
You need a broadcast receiver to receive network state changes then pass this data to service which is not a bound service and create a notification or you can create your notification in your broadcast receiver.
You don't have to run a service to check for connection changes.
You can register a broadcast receiver with the android.net.conn.CONNECTIVITY_CHANGE intent.
Note that
Apps targeting Android 7.0 (API level 24) and higher do not receive
this broadcast if they declare the broadcast receiver in their
manifest. Apps will still receive broadcasts if they register their
BroadcastReceiver with Context.registerReceiver() and that context is
still valid.
Link for more information:
https://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION
Similar question: https://stackoverflow.com/a/2295044/2174489
I am developing an application. In that one screen check Internet connection, immediately after onCreate() method. If network connection is good i am calling one AsyncTask class for load countries list and show it on screen in spinnerView. If there is no network connection i am showing Toast Message to User and call check_Network(AsyncTask). In this class protected Long doInBackground(URL... params) method i'm checking Network connected or not if connected call countries AsyncTask otherwise again i am calling check_Network(AsyncTask). this process repeat until network is connected. my problem is It is correct way for Check Network Repeatedly. please suggested me. sorry i am poor in english please understand.blow i am showing my code
if (CheckNetwork.isOnline(this)) {
try {
new CountryProcess().execute();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(
getApplicationContext(),
getString(R.string.network_connection_fail)
+ "!", Toast.LENGTH_LONG).show();
new NetWork_connectivity().execute();
}
//.......................//
class NetWork_connectivity extends AsyncTask<URL, Integer,Long>
{
#Override
protected Long doInBackground(URL... params)
{
if (CheckNetwork.isOnline(MainActivity.this)) {
new CountryProcess().execute();
}else
{
new NetWork_connectivity().execute();
}
return null;
}
}
Add below code in manifest, for adding receiver with connectivity change intent
<receiver android:name=".NetworkStateReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And at receiver side, get extras associated with intent and check for status. So whenever there is change in network status, you will be notified then perform your task accordingly.
public class NetworkStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
//connected
}
}
if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
//not connected
}
}
}
For your case, you would like to add permission in manifest and register receiver in your activity.
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkReceiver, filter);
Make sure to unregister it as well before leaving activity with
unregisterReceiver(networkReceiver);
private BroadcastReceiver networkReceiver = new BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
//connected
}
}
//not connected
}
}
And based upon your requirement that you requires connected status only one time. First check for connectivity and if not connected then only register receiver.
public boolean isNetworkConnected() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
To access internet we need INTERNET Permission
To detect network status we need ACCESS_NETWORK_STATE Permission
Add these lines in your AndroidManifest.xml:
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Create this method in your java class:
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
When ever you want to check Internet Status in your application call isConnectingToInternet() function and it will return true or false
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false
How must I go about coding to get an app to query the state of a device, through internet protocol to see if its on or off.
public void port0156 (View view) {
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://192.168.2.66/index.html?o0=1");
}
You can register a broadcastreceiver to monitor connectivity changes.
In manifest :
<receiver android:name="com.yourpackage.NetworkChangeReciever" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
the class in com.yourpackage :
public class NetworkChangeReciever extends BroadcastReceiver {
private final static String TAG = "NetworkChangeReciever";
public interface NetworkChangeRecieverListener {
public void OnNetworkChangeReciever(boolean wifiConnected);
}
#Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) || mobile.isAvailable()) {
Log.d(TAG, "Network Available.");
}
else {
Log.d(TAG, "Network Unavailable");
}
}
}
You can see if the app is online (or reachable) by seeing if it returns a ping you can easily do this by using OS and parsing the output.
I need to locate my current location in a building by scanning the strongest available Wifi to launch an activity. I want to locate only 3 places in that building. So if I am currently near any of those locations, I will click a button to scan the strongest available Wifi to launch an activity.
I need to scan available Wifi in a building.
Get the 3 strongest signal.
Then detect whether any of those 3 strongest signal's SSID is the same with the specific SSID that I want to locate.
If my SSID is one of the strongest 3 signals, then the application will launch a xml layout activity,
So far I already have the coding to scan strongest available Wifi. But I don't know how to launch an activity when the strongest specific Wifi SSID detected. I do not need the information about the Wifi, just to launch my activity layout that has my information.
At the moment I'm using the following bit of code to scan the strongest Wifi signal that I got from here:
WiFiDemo.java
public class WiFiDemo extends Activity implements OnClickListener {
private static final String TAG = "WiFiDemo";
WifiManager wifi;
BroadcastReceiver receiver;
TextView textStatus;
Button buttonScan;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Setup UI
textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
// Setup WiFi
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// Get WiFi status
WifiInfo info = wifi.getConnectionInfo();
textStatus.append("\n\nWiFi Status: " + info.toString());
// List available networks
List<WifiConfiguration> configs = wifi.getConfiguredNetworks();
for (WifiConfiguration config : configs) {
textStatus.append("\n\n" + config.toString());
}
// Register Broadcast Receiver
if (receiver == null)
receiver = new WiFiScanReceiver(this);
registerReceiver(receiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
Log.d(TAG, "onCreate()");
}
#Override
public void onStop() {
unregisterReceiver(receiver);
}
public void onClick(View view) {
Toast.makeText(this, "On Click Clicked. Toast to that!!!",
Toast.LENGTH_LONG).show();
if (view.getId() == R.id.buttonScan) {
Log.d(TAG, "onClick() wifi.startScan()");
wifi.startScan();
}
} }
WiFiScanReceiver.java
public class WiFiScanReceiver extends BroadcastReceiver {
private static final String TAG = "WiFiScanReceiver";
WiFiDemo wifiDemo;
public WiFiScanReceiver(WiFiDemo wifiDemo) {
super();
this.wifiDemo = wifiDemo;
}
#Override
public void onReceive(Context c, Intent intent) {
List<ScanResult> results = wifiDemo.wifi.getScanResults();
ScanResult bestSignal = null;
for (ScanResult result : results) {
if (bestSignal == null
|| WifiManager.compareSignalLevel(bestSignal.level, result.level) < 0)
bestSignal = result;
}
String message = String.format("%s networks found. %s is the strongest.",
results.size(), bestSignal.SSID);
Toast.makeText(wifiDemo, message, Toast.LENGTH_LONG).show();
Log.d(TAG, "onReceive() message: " + message);
}
}
You just need to start your activity from onReceive. Unless I'm not understanding your question, you just need to fire off your activity.
Since you have the context on your receiver's onReceive you just need to startActivity()
Start Activity inside onReceive BroadcastReceiver
#Override
public void onReceive(Context context, Intent intent) {
//start activity
Intent i = new Intent();
i.setClassName("com.test", "com.test.MainActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
Don't forget to define a proper filter for it in your manifest.
http://developer.android.com/reference/android/content/BroadcastReceiver.html