Is there an Android Intent ACTION_XXX that notifies me when an Internet Connection is available?
I want to instantiate a BroadcastReceiver that notifies my application when a user enables Internet Connection (by wifi, by GSM, etc.)
Could anyone help me?
<receiver android:name=".YOURRECEIVER">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Accepted answer is correct. I only add Receiver code for completion:
public class NetworkStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.d("app","Network connectivity change");
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
Log.i("app","Network "+ni.getTypeName()+" connected");
} else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
Log.d("app","There's no network connectivity");
}
}
}
Update to #lujop answer:
public class NetworkStateReceiver extends BroadcastReceiver {
private static final String TAG = "NetworkStateReceiver";
#Override
public void onReceive(final Context context, final Intent intent) {
Log.d(TAG, "Network connectivity change");
if (intent.getExtras() != null) {
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni != null && ni.isConnectedOrConnecting()) {
Log.i(TAG, "Network " + ni.getTypeName() + " connected");
} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Log.d(TAG, "There's no network connectivity");
}
}
}
}
MyReceiver.java
public class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(isConnected(context)) Toast.makeText(context, "Connected.", Toast.LENGTH_LONG).show();
else Toast.makeText(context, "Lost connect.", Toast.LENGTH_LONG).show();
}
public boolean isConnected(Context context) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
return isConnected;
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
UPDATE
If your app targets API level 26 or higher, you cannot use the
manifest to declare a receiver for implicit broadcasts (broadcasts
that do not target your app specifically), except for a few implicit
broadcasts that are exempted from that restriction. In most cases, you
can use scheduled jobs instead.
usage
connection = MyReceiver()
// onCreate - onDestroy, onResume - onPause depends on you
override fun onStart() {
super.onStart()
registerReceiver(connection, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
}
override fun onStop() {
super.onStop()
// remember unregister to avoid leak
unregisterReceiver(connection)
}
UPDATE 2
CONNECTIVITY_ACTION This constant was deprecated in API level 28.
apps should use the more versatile requestNetwork(NetworkRequest, PendingIntent), registerNetworkCallback(NetworkRequest, PendingIntent) or registerDefaultNetworkCallback(ConnectivityManager.NetworkCallback) functions instead for faster and more detailed updates about the network changes they care about.
because it added in API level 22, so above code will work fine on all versions of android
The missing part of all answers is a reminder to register for that action:
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(your_receiver, filter);
This code will work (in all versions) as the manifest registration will not work for 7+(API 25 and above) devices see this link.
private void foo(){
registerReceiver(connectionBroadcastReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private BroadcastReceiver connectionBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent == null || intent.getExtras() == null)
return;
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
// connected
}
}
};
I'm using broadcast to check the connection every time. Create a class for connection info.
import android.content.Context;
import android.content.ContextWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectivityStatus extends ContextWrapper{
public ConnectivityStatus(Context base) {
super(base);
}
public static boolean isConnected(Context context){
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo connection = manager.getActiveNetworkInfo();
if (connection != null && connection.isConnectedOrConnecting()){
return true;
}
return false;
}
}
Apply code into your Activity:
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(!ConnectivityStatus.isConnected(getContext())){
// no connection
}else {
// connected
}
}
};
Register broadcast in your activity's onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
..
...
....
}
Don't forget to unregistered/register on Activity cycle:
#Override
protected void onResume() {
super.onResume();
your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onPause() {
super.onPause();
your_activity_context.unregisterReceiver(receiver);
}
Continuing meow mwo's Answer
you can enable/disable the receiver by:
enable
ComponentName receiver = new ComponentName(MainActivity.this, MyReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();
}
disable
ComponentName receiver = new ComponentName(MainActivity.this, MyReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();
}
where, the same can be called in an Intent or in onCreate
NetworkInfo.isConnected() is unreliable method to test for internet status, it will return true when there is a network connection even though it may have no internet access (ex. wifi with no internet). A more reliable approach would be to use ping with a CONNECTIVITY_ACTION BroadcastReceiver:
private void registerInternetReceiver()
{
if (this.internetReceiver != null) return;
this.internetReceiver = new BroadcastReceiver()
{
#Override
public void onReceive (Context context, Intent intent)
{
if (isInternetAvailable()) Log.i ("Tag", "internet status online");
else Log.i ("Tag", "internet status offline");
}
};
IntentFilter filter = new IntentFilter();
filter.addAction (ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver (internetReceiver, filter);
}
private boolean isInternetAvailable()
{
try
{
return (Runtime.getRuntime().exec ("ping -c 1 google.com").waitFor() == 0);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return false;
}
**Also worked on above Android 7.0**
// AndroidManifest.xml
<service
android:name=".NetworkSchedulerService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"/>
// MyApplication.java
import android.app.Application;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
public class MyApplication extends Application {
private static Context context;
public static Context getContext() {
return context;
}
public static final String TAG = MyApplication.class.getSimpleName();
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
mInstance = this;
scheduleJob();
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
private void scheduleJob()
{
JobInfo myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
.setRequiresCharging(true)
.setMinimumLatency(1000)
.setOverrideDeadline(2000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
assert jobScheduler != null;
jobScheduler.schedule(myJob);
}
}
// Constants.java
public class Constants {
public static final String CONNECT_TO_WIFI = "WIFI";
public static final String CONNECT_TO_MOBILE = "MOBILE";
public static final String NOT_CONNECT = "NOT_CONNECT";
public final static String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
}
// LiveConnectivityReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class LiveConnectivityReceiver extends BroadcastReceiver {
private MConnectivityReceiver mConnectivityReceiver;
LiveConnectivityReceiver(MConnectivityReceiver listener) {
mConnectivityReceiver = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
mConnectivityReceiver.onNetworkConnectionChanged(isConnected(context));
}
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
public interface MConnectivityReceiver {
void onNetworkConnectionChanged(boolean isConnected);
}
}
// MainActivity.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStop() {
stopService(new Intent(this, NetworkSchedulerService.class));
super.onStop();
}
#Override
protected void onStart() {
super.onStart();
startService( new Intent(this, NetworkSchedulerService.class));
}
#Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(this.mReceiver);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter("android.intent.action.MAIN");
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean isConnection = intent.getBooleanExtra("VALUE", false);
if (!isConnection) {
Toast.makeText(context, "No Internet Connection", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Back to online", Toast.LENGTH_SHORT).show();
}
}
};
this.registerReceiver(mReceiver, intentFilter);
}
}
// NetworkSchedulerService.java
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.content.IntentFilter;
public class NetworkSchedulerService extends JobService implements LiveConnectivityReceiver.ConnectivityReceiverListener
{
private LiveConnectivityReceiver mLiveConnectivityReceiver;
#Override
public void onCreate()
{
super.onCreate();
mLiveConnectivityReceiver = new LiveConnectivityReceiver(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
#Override
public boolean onStartJob(JobParameters params) {
registerReceiver(mLiveConnectivityReceiver, new IntentFilter(Constants.CONNECTIVITY_ACTION));
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
unregisterReceiver(mLiveConnectivityReceiver);
return true;
}
#Override
public void onNetworkConnectionChanged(boolean isConnected)
{
Intent broadcastedIntent=new Intent("android.intent.action.MAIN");
broadcastedIntent.putExtra("VALUE", isConnected);
sendBroadcast(broadcastedIntent);
}
}
From Android 7++, #fedj's answer will not work but you can register the broadcast receiver programmatically.
Apps targeting Android 7.0 (API level 24) and higher do not receive
CONNECTIVITY_ACTION broadcasts if they declare the broadcast receiver
in their manifest. Apps will still receive CONNECTIVITY_ACTION
broadcasts if they register their BroadcastReceiver with
Context.registerReceiver() and that context is still valid.
I would read the docs updated for nougat + , because intent is deprecated due to the # of devices, network info alone is not sufficient. I would use connectivity manager ( connectivity action, add variables there) commands and vars there, because most has changed in the last year alone, and on for testing, enable cell data always active, verbose logging and aggressive handover, use wlan filter if needed:
https://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION
**You can put this line of code on Helper Methods and call it when you want to check internet connection **
public static class InternetState {
static ConnectivityManager cm;
static public boolean isConnected(Context context) {
try {
cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
} catch (NullPointerException e) {
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return isConnected;
}
}
Related
I register a broadcast on runtime to receive "android.net.wifi.WIFI_STATE_CHANGED"
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
broadcastReceiverAction = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.net.wifi.WIFI_STATE_CHANGED")) {
/*I get this action as soon as calling registerReceiver(broadcastReceiverAction, intentFilter);*/
}
}
}
registerReceiver(broadcastReceiverAction, intentFilter);
Issue: This gets the broadcast action as soon as registering the receiver.
I got this on Android API 26 & Higher Which I can not declare "android.net.wifi.WIFI_STATE_CHANGED" in Manifest. (No Longer Supported by Android System)
To check network connectivity state change you can do it programmatically. It supports API 21+.
public class ConnectionStateMonitor extends ConnectivityManager.NetworkCallback {
public final String TAG = ConnectionStateMonitor.class.getSimpleName();
private boolean isLost = false;
final NetworkRequest networkRequest;
Context context;
private ConnectionStateMonitor instance;
private boolean isLost = false;
private ConnectionStateMonitor() {
networkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build();
}
public synchronized ConnectionStateMonitor getInstance() {
if (instance == null) {
instance = new ConnectionStateMonitor();
}
return instance;
}
public void enable(Context context) {
try {
if (context == null) return;
this.context = context;
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
connectivityManager.registerNetworkCallback(networkRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onAvailable(Network network) {
Log.i(TAG, "onAvailable called " +
network.toString());
if (isLost) {
isLost = false;}
// when network available called it
}
#Override
public void onLost(Network network) {
super.onLost(network);
isLost = true;
// when network lost called it
Log.i(TAG, "onLost called ");
}
}
[Simple Solution]
Problem is Sticky Broadcasts which trigger at the moment of registration.
To avoid this I simply add another parameter to restrict the process.
I defined a static variable
public static boolean triggerBroadcast = false;
Then I change it to after registering the broadcast by few second delay.
registerReceiver(broadcastReceiverAction, intentFilter);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
triggerWifiBroadcast = true;
}
}, 3000);
Then onReceive() I compare intent.getAction with this
if (intent.getAction().equals("android.net.wifi.WIFI_STATE_CHANGED") && triggerBroadcast ) {
//
}
Then you can change it to false whenever decide to unregister the broadcast receiver.
I am working on an android app with calling webservice when it has internet by using service and broadcast receivers below is my code:
public class YourService extends IntentService {
private static String TAG = YourService.class.getSimpleName();
private MyThread mythread;
public boolean isRunning = false;
JSONArray SaveOrderDart,SaveOrderDetails,UpdateDart,updateOrderDetails;
private static String urlDartorder= Config.url+"SaveDartDetails";
private static String urlupdateOrderDetails= Config.url+"UpdateOrderDetails";
private static String urlSaveOrderDetails= Config.url+"SaveOrderDetails";
private static String urlDartupdate= Config.url+"UpdateDartDetails";
DartDatabase ddb;
OrderDatabase ord;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* #param name Used to name the worker thread, important only for debugging.
*/
public YourService(String name) {
super(name);
}
#Override
public void onCreate() {
super.onCreate();
mythread=new MyThread();
}
public YourService()
{
super("call webservice");
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Bundle extras = intent.getExtras();
boolean isNetworkConnected = extras.getBoolean("isNetworkConnected");
// your code
if(isNetworkConnected){
if(!isRunning){
mythread.start();
isRunning = true;
}
Log.e("TAG", "Yes");
}
else {
if (mythread != null) {
isRunning = false;
mythread.interrupt();
}
//mythread.stop();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if(!isRunning){
mythread.start();
isRunning = true;
}
}
My broadcastreceiver
public class ConnectivityChangeReceiver extends BroadcastReceiver {
boolean mLastState =false;
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that which service class will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
YourService.class.getName());
//mLastState = true;
intent.putExtra("isNetworkConnected", isConnected(context));
context.startService((intent.setComponent(comp)));
}
public boolean isConnected(Context context) {
ConnectivityManager connectivityManager = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE));
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
}
}
my purpose is when internet is present i want to call webservice not present then stop the thread and service but by this code i can't stop the service i don't no why please help me!
but i can't stop thread please help me!
I have created one IntentService to send local data to the server.
I am calling this service from two different broadcast receivers.
1) When from Connectivity change receiver.
2) on 12 am with alarm manager
Its working fine when an app is open.
But not working when an app is closed.
Below is my IntentService code.
public class ExpertEventService extends IntentService {
#Inject
Context context;
#Inject
Realm realm;
public ExpertEventService() {
super("ExpertEventService");
Log.e("expertEvent", "service constructor");
// Toothpick.inject(this, Toothpick.openScope(Constants.APPSCOPENAME));
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Toothpick.inject(this, Toothpick.openScope(Constants.APPSCOPENAME));
Log.e("expertEvent", "service started");
RealmResults<AskExpertEventModel> results = realm.where(AskExpertEventModel.class).findAll();
List<AskExpertEventModel> requestList = realm.copyFromRealm(results);
String language = realm.where(LanguageStore.class).equalTo(LanguageStore.ISSELECTED, true).findAll().first().getCode();
String appInstanceCode = Preferences.getAppInstanceCode(context);
String token = Preferences.getToken(context);
Api.userManagement(context).expertEvent(appInstanceCode, token, language, requestList)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(new ApiSuccess<EventResponse>() {
#Override
public void call(EventResponse eventResponse) {
Log.e("expertEvent", eventResponse.getStatus());
if (eventResponse.getStatus().equalsIgnoreCase(Constants.Status.STATUS_SUCCESS)) {
Log.e("expertEvent", "sucess");
new RealmDB().deleteEvent();;
}
}
}, new ApiFail() {
#Override
public void httpStatus(HttpErrorResponse response) {
Log.e("expertEvent", response.getError());
}
#Override
public void noNetworkError() {
Log.e("expertEvent", "no network connection");
}
#Override
public void unknownError(Throwable e) {
Log.e("expertEvent", e.getMessage());
}
});
}
}
1) Receiver called when connectivity change
public class NetworkStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("expertEvent", "Connectivity changed");
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (info.isConnected()) {
//start service
Log.e("expertEvent", "Connected ");
Intent serviceIntent = new Intent(context,
ExpertEventService.class);
context.startService(serviceIntent);
}
} else {
Log.e("expertEvent", "not connected");
}
}
}
2) Execute when 12 am
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//call service
Log.e("alarmreceiver","in alarm receiver");
Intent serviceIntent = new Intent(context, ExpertEventService.class);
context.startService(serviceIntent);
}
}
Explanation:
Hello Everyone, I am trying to check my device is connected with internet or not. I am explaining all the step what i do.
Step-1: I have created a receiver class to check when the connection status change.
Step-2: I also created a Interface in which i have method to get the connection status (true/false)
Step-3: Implement this listener on my Activity and then override the listener method.
Step-4: If my internet is connected then go ahead. If my internet is not connected i put the message your internet is not connected.
Step-5: Finally i register this receiver in AndroidManifest.xml file.
Note: All above step is working fine until SDK_VERSION Marshmallow. When i checked it with Nougt(7.0) then it's not working.
Receiver
public class ConnectivityReceiver extends BroadcastReceiver {
public static ConnectivityReceiverListener connectivityReceiverListener;
public ConnectivityReceiver(){
super();
}
#Override
public void onReceive(Context context, Intent intent) {
if (connectivityReceiverListener != null) {
connectivityReceiverListener.onNetworkConnectionChanged(Utils.isInternetConnected(context));
}
}
public static boolean isConnected(Context context) {
if(Utils.isInternetConnected(context)){
return true;
}else{
return false;
}
}
}
Listener
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
Internet connection status method
public static boolean isInternetConnected(final Context _context) {
ConnectivityManager cm = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
return true;
} else {
return false;
}
}
Permission and register receiver in Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<receiver
android:name="com.durian.receivers.ConnectivityReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Below method is check internet connetion
private boolean checkConnection() {
boolean isConnected = ConnectivityReceiver.isConnected(CustomerActivity.this);
showSnack(isConnected);
return isConnected;
}
Below method is check isconnected or not
private void showSnack(boolean isConnected) {
String message;
int color;
Snackbar snackbar;
if (isConnected) {
Toast.make(getActivity(),"CONNECTED",Toast.LENGTH_SHORT).show();
} else {
Toast.make(getActivity(),"Disconnected",Toast.LENGTH_SHORT).show();
}
}
Below method call the listener
#Override
protected void onResume() {
super.onResume();
AppController.getInstance().setConnectivityListener(this);
}
Here is my Application class which register in android with name parameter
public class AppController extends Application{
public static final String TAG=AppController.class.getSimpleName();
public static Typeface fntGabriola;
public static Typeface fntRalewayLight;
public static Typeface fntRalewayMedium;
public static Typeface fntRalewayRegular;
public static Typeface fntRalewaySemiBold;
public static Typeface fntsegoeuRegular;
public static Typeface fntsegoeuLight;
public static Typeface fntsegoeSemiBold;
public static Typeface fntModerneSans;
public static Typeface fntMordernist;
public static Typeface fntOpenSans;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
Fabric.with(this, new Crashlytics());
fntGabriola=Typeface.createFromAsset(getAssets(),"fonts/Gabriola.ttf");
fntRalewayLight=Typeface.createFromAsset(getAssets(),"fonts/Raleway-Light.ttf");
fntRalewayMedium=Typeface.createFromAsset(getAssets(),"fonts/Raleway-Medium.ttf");
fntRalewayRegular=Typeface.createFromAsset(getAssets(),"fonts/Raleway-Regular.ttf");
fntRalewaySemiBold=Typeface.createFromAsset(getAssets(),"fonts/Raleway-SemiBold.ttf");
fntsegoeuRegular=Typeface.createFromAsset(getAssets(),"fonts/segoeui.ttf");
fntsegoeuLight=Typeface.createFromAsset(getAssets(),"fonts/segoeuil.ttf");
fntsegoeSemiBold=Typeface.createFromAsset(getAssets(),"fonts/seguisb.ttf");
fntModerneSans=Typeface.createFromAsset(getAssets(),"fonts/moderne_sans.ttf");
fntMordernist=Typeface.createFromAsset(getAssets(),"fonts/Sk-Modernist-Regular.otf");
fntOpenSans=Typeface.createFromAsset(getAssets(),"fonts/OpenSans-Regular.ttf");
}
public static synchronized AppController getInstance() {
return mInstance;
}
public void setConnectivityListener(ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}
}
Note: Everything is working fine below the nought OS Version. But the problem is when i test in nought it is not working. Please give a proper solutions which working in all the OS.
For reference you can check the snapdeal application
I want exactly as in snapdeal Android application.
/**You can simply use below code Snippet**/
/**Below code Check 2 condition that Your device is connected to Wifi or Data - Connection or not. If yes then will also check that Internet is working or not..**/
/**ConnectivityReceiver Class**/
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ConnectivityReceiver
{
private static ConnectivityReceiver.AsyncResponse asyncResponse;
/************************************************ for checking internet connection*******/
public static boolean isNetworkAvailable(Context context)
{
ConnectivityManager connectivity = null;
boolean isNetworkAvail = false;
try
{
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;
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (connectivity != null)
{
connectivity = null;
}
}
return isNetworkAvail;
}
private static class ConnectionCheck extends AsyncTask<String,Void,Boolean>
{
#Override
protected Boolean doInBackground(String... params)
{
HttpURLConnection urlConnection = null;
try
{
if(params[0].endsWith("") || params[0] == null)
{
params[0] = "http://www.google.com/";
}
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (!url.getHost().equals(urlConnection.getURL().getHost()))
{
// we were redirected! Kick the user out to the browser to sign on?
return true;
}
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
finally
{
urlConnection.disconnect();
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean)
{
super.onPostExecute(aBoolean);
asyncResponse.processFinish(aBoolean);
}
}
public interface AsyncResponse
{
void processFinish(boolean output);
}
public static void speedTest(String url,ConnectivityReceiver.AsyncResponse asyncResponse)
{
ConnectivityReceiver.asyncResponse = asyncResponse;
new ConnectivityReceiver.ConnectionCheck().execute(url);
}
}
/**Code implementation in your class**/
String ConnectionCheck_Url = "http://www.google.com/";
if(ConnectivityReceiver.isNetworkAvailable(MainActivity.this))
{
ConnectivityReceiver.speedTest(ConnectionCheck_Url,new ConnectivityReceiver.AsyncResponse()
{
#Override
public void processFinish(boolean output)
{
if (output)
{
/* * If The output Value --->"True" Then Only
request will Execute
* NOTE: Here "True" Value Means Intenet is Working*/
// Implement your code here
}
else
{
//Please_Check_Your_Internet_Connection
}
}
});
}
else
{
// Please_Connect_to_your_Wifi_or_Data_Connection
}
}
/**Android MainifestFile.xml**/
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
I need to check for internet connection in background....
i am saving some data in my database and whenever i get internet connection,
it should upload the data on my server...
i need a background service which will check for internet connection continuously even if i close my App,
i tried few methods but they all work only if i open my app...
Currently i am checking the internet connection like this
/checking internet connection
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
connected = true;
}
else
//not connected to internet
connected = false;
if(connected) {
//getting teacher data if INTERNET_STATE is true(if will be still true if connected to a wifi or network without internet)
getOfflineSubjectData();
getTeacherData();
}
else{
getOfflineSubjectData();
Toast.makeText(teacher_homePage.this,"no internet",Toast.LENGTH_SHORT).show();
}
NOTE
I don't want a method which will not work after i close my app...
Just like whatsapp when we close the app,We still get text messages
I know it's too late to answer your question but still, this is a perfectly working solution.
We can easily do it by using a Service and a Broadcast Receiver simultaneously to get the output as you wish. This will work always i.e when app is running, app is minimized or when app is even removed from minimized apps.
Manifest Code :
<application
...
<service android:name=".MyService" />
</application>
MyService.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
NotificationManager manager ;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (CONNECTIVITY_CHANGE_ACTION.equals(action)) {
//check internet connection
if (!ConnectionHelper.isConnectedOrConnecting(context)) {
if (context != null) {
boolean show = false;
if (ConnectionHelper.lastNoConnectionTs == -1) {//first time
show = true;
ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
} else {
if (System.currentTimeMillis() - ConnectionHelper.lastNoConnectionTs > 1000) {
show = true;
ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
}
}
if (show && ConnectionHelper.isOnline) {
ConnectionHelper.isOnline = false;
Log.i("NETWORK123","Connection lost");
//manager.cancelAll();
}
}
} else {
Log.i("NETWORK123","Connected");
showNotifications("APP" , "It is working");
// Perform your actions here
ConnectionHelper.isOnline = true;
}
}
}
};
registerReceiver(receiver,filter);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
ConnectionHelper.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionHelper {
public static long lastNoConnectionTs = -1;
public static boolean isOnline = true;
public static boolean isConnected(Context context) {
ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
}
public static boolean isConnectedOrConnecting(Context context) {
ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
}
Your Activity Code
startService(new Intent(getBaseContext(), MyService.class));
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;
public class CheckConnectivity extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent arg1) {
boolean isConnected = arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if(isConnected){
Toast.makeText(context, "Internet Connection Lost", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
}
}
}
Android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.connect.broadcast"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver android:exported="false"
android:name=".CheckConnectivity" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
</manifest>
Probably there is some better way, but I've implemented this as a STICK_SERVICE as #Rahul suggested, and for avoiding killing the service I forced a fixed notification in status bar. I know this probably is not a good practice, however the client has asked to show "App is running..." in the status bar, so it's ok.
SyncService.class
public class SyncService extends IntentService {
private static int FOREGROUND_ID = 1338;
public Boolean isServiceRunning = false;
Integer delay;
private NotificationManager mgr;
public SyncService() {
super("SyncService");
}
#Override
public void onStart(#Nullable Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
performSync();
startSyncThread();
mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
final NotificationCompat.Builder builder = buildForeground();
startForeground(1, builder.build());
return START_STICKY;
}
public Boolean isWifiConnected() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi.isConnected();
}
public void startSyncThread() {
Handler handler = new Handler();
delay = 1000;
handler.postDelayed(new Runnable() {
public void run() {
performSync();
handler.postDelayed(this, delay);
}
}, delay);
}
public void performSync() {
if (isWifiConnected()) {
Log.i("SyncService:", "Wifi connected, start syncing...");
Sync sync = new Sync(this);
sync.postPhotos();
sync.postEvents();
sync.getEvents();
delay = 60000;
} else {
Log.i("SyncService:", "Wifi IS NOT connected, ABORT syncing...");
delay = 1000;
}
Log.i("SyncService:", delay + "");
}
#Override
protected void onHandleIntent(Intent intent) {
WakefulReceiver.completeWakefulIntent(intent);
}
private NotificationCompat.Builder buildForeground() {
Intent intent = new Intent(this, EventsActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder b = new NotificationCompat.Builder(this);
b.setContentTitle("Prime Share is running")
.setSmallIcon(android.R.drawable.stat_notify_sync_noanim)
.setOngoing(true)
.setAutoCancel(false)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent);
return (b);
}
}
And then in my first activity onCreate I call this:
context = this;
startSyncIntent = new Intent(this, SyncService.class);
startService(startSyncIntent);
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
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;
}
use this method anywhere
if (!isNetworkAvailable(this)) {
} else {}
Code check internet access by using timer, I have made a service for that
First time I have posted on stack.... so sorry in advance because i am not able to post it in good format
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000;
public static String str_receiver = "pravin.service.receiver";
Intent intent;
DatabaseHandler dh=new DatabaseHandler(this);
public CheckInternet(){
}
#Override
public void onCreate()
{
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetInternetStatus(), 5, notify_interval);
intent = new Intent(str_receiver);
}
private class TimerTaskToGetInternetStatus extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
icConnected();
}
});
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onStart(Intent intent,int startid)
{
}
public boolean icConnected()
{
Log.d("Called " , "INTERNET");
ConnectivityManager connec =
(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);
// Check for network connections
if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
Log.d("INTERNET","TRUE");
dh.getIssues();
return true;
// if connected with internet
//makeText(this, " Connected ", LENGTH_LONG).show();
} else if (
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED ) {
Log.d("INTERNET","FALSE");
return false;
//makeText(this, " Not Connected ", LENGTH_LONG).show();
}
return false;
}
}