How to show notification on internet connect? - java

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

Related

Android Internet Connection checker OUTSIDE the app

My app needs to do something whenever the internet is connected and vice-versa. However, I need to do this OUTSIDE my application. There are a lot of ideas and help here on stackoverflow but it is always WITHIN the application. I know that the AlarmManager works outside the application but it would just be draining the battery if I try to check if there's internet connection every 5 minutes. What I wanted is to check the connection outside the app to download something.
I also found out that Intent Service can work outside the application as well. I have tried to put this inside the Wakeful Broadcast Receiver. However, it is still not being called.
Can someone out there help me? Thanks!
Here's my Wakeful Broadcast Receiver
public class ConnectivityOutsideAppReceiver extends WakefulBroadcastReceiver {
private static final String LOG_TAG = ConnectivityOutsideAppReceiver.class.getSimpleName();
private ConnectivityManager connectivityManager;
private static boolean connection = false;
#Override
public void onReceive(Context context, Intent intent){
ComponentName comp = new ComponentName(context.getPackageName(),
ConnectivityOutsideAppService.class.getName());
// Start the service, keeping the device awake while it is
// launching.
startWakefulService(context, (intent.setComponent(comp)
));
}
}
This is the Intent Service
public class ConnectivityOutsideAppService extends IntentService {
private static final String LOG_TAG = ConnectivityOutsideAppService.class.getSimpleName();
private ConnectivityManager connectivityManager;
private static boolean connection = false;
private Context context;
public ConnectivityOutsideAppService() {
super(ConnectivityOutsideAppService.class.getSimpleName());
this.context = context;
}
#Override
protected void onHandleIntent(Intent intent) {
connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
checkConnectionOnDemand();
Log.e(LOG_TAG, " ## onHandleIntent##");
if (connection == true
&& intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
false)) {
Log.e(LOG_TAG, " ## connection == true ##");
connection = false;
} else if (connection == false
&& !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
false)) {
Log.e(LOG_TAG, " ## connection == false ##");
connection = true;
}
ConnectivityOutsideAppReceiver.completeWakefulIntent(intent);
}
public static boolean hasConnection() {
return connection;
}
private void checkConnectionOnDemand() {
Log.e(LOG_TAG, " ## checkConnectionOnDemand ##");
final NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info == null || info.getState() != NetworkInfo.State.CONNECTED) {
if (connection == true) {
Log.e(LOG_TAG, " ## connection == true ##");
connection = false;
}
} else {
if (connection == false) {
Log.e(LOG_TAG, " ## connection == false ##");
connection = true;
}
}
}
}
This is my Android Manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<service
android:name="com.timetrackermobilelog.BusinessServices.ConnectivityOutsideAppService"
android:exported="false"/>
<receiver android:name="com.timetrackermobilelog.Utilities.ConnectivityOutsideAppService"
android:enabled="true"
android:process=":remote">
<intent-filter android:priority="1000" >
<action android:name="com.timetrackermobilelog.Utilities.ConnectivityOutsideAppService" />
<category android:name="com.Utilities" />
</intent-filter>
</receiver>
I have tried registering the receiver inside the Activity but it doesn't work as well.
IntentFilter intentFilter = new IntentFilter("com.pointwest.timetrackermobilelog.Utilities.ConnectivityOutsideAppReceiver");
ConnectivityOutsideAppReceiver connectivityOutsideAppReceiver = new ConnectivityOutsideAppReceiver();
registerReceiver(connectivityOutsideAppReceiver, intentFilter);
Is there anything that I missed?
Thanks to #Mike M. in giving the answer with just a few lines of changes.
In Android Manifest, change it to :
<intent-filter android:priority="1000" >
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
And onHandleIntent of the Service, change it to :
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

what is the best way to check Internet connection continuously in android

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

Connect WiFi Manager from separate AsyncTask class in Android

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.

NetworkChangeReceiver's onReceive method is called multiple times when 3G and WIFI are enable at same time

I'm developing an android application and I have the next problem:
I implemented Broadcast receiver for connectivity change and the method onReceive seems to be called 4 times in a row when 3G and Wifi are enabled at the same time.
So my question is:
Is there a way listen only for internet connection, not for network change?
Or is there any way for the method onReceive to be called only once when 3G and Wifi are enable at the same time?
Here is my code:
public class NetworkChangeReceiver extends BroadcastReceiver {
public static final String TAG = "NetworkMonitoring";
#Override
public void onReceive(Context context, Intent intent) {
if (isOnline(context)) {
Log.v(TAG, "Connected!");
// update(context);
} else {
Log.v(TAG, "Not connected!");
// stopUpdate(context);
}
}
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
return true;
return false;
}
}
In the Android Manifest:
<receiver android:name="xxxxx.xxxxx.xxxxx.NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Here is the log:
05-06 16:24:05.985: V/NetworkMonitoring(569): Connected!
05-06 16:24:10.250: V/NetworkMonitoring(569): Connected!
05-06 16:24:10.720: V/NetworkMonitoring(569): Connected!
05-06 16:24:11.031: V/NetworkMonitoring(569): Connected!
(Notice the time!)
I had the same problem with the same type of broadcast receiver.
Searched a little and found a workaround.
BroadcastReceiver receives multiple identical messages for one event
Edit:
The workaround is to use a flag that tells you when is the first time onReceive is being invoked.
public class ConnectionChangeReceiver extends BroadcastReceiver {
private static boolean firstConnect = true;
#Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null) {
if(firstConnect) {
// do subroutines here
firstConnect = false;
}
}
else {
firstConnect= true;
}
}
}
Hope it helps.

Query a web page

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.

Categories

Resources