In my app I have 4 activities. if any network changes i want update the activity which is in foreground state. i wrote one broadcast receiver for network changes. but I want to update activity from that broadcast receiver.
This is my broadcast receiver:
public class NetworkChangeReceiver extends BroadcastReceiver {
#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()) {
// i need to update activity ?????
}
}
}
In the manifest file :
<application
android:name=".MyApp"
....
</application>
then Create this class to store current activity context:
public class MyApp extends Application {
public void onCreate() {
super.onCreate();
}
private static Activity mCurrentActivity = null;
public static Activity getCurrentActivity(){
return mCurrentActivity;
}
public static void setCurrentActivity(Activity mCurrentActivity){
this.mCurrentActivity = mCurrentActivity;
}
}
Create a new Activity :
public class MyBaseActivity extends Activity {
protected MyApp mMyApp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMyApp = (MyApp)this.getApplicationContext();
}
protected void onResume() {
super.onResume();
mMyApp.setCurrentActivity(this);
}
protected void onPause() {
clearReferences();
super.onPause();
}
protected void onDestroy() {
clearReferences();
super.onDestroy();
}
private void clearReferences(){
Activity currActivity = mMyApp.getCurrentActivity();
if (currActivity != null && currActivity.equals(this))
mMyApp.setCurrentActivity(null);
}
}
then :
public class NetworkChangeReceiver extends BroadcastReceiver {
#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()) {
// i need to update activity ?????
TextView tv = (TextView)myApp.getCurrentActivity().findViewById(R.id.your_view_id);
tv.setText("Network is available");
}
}
}
Related
I have Broadcast Receiver for doing Internet checking. Every time device is not connected with Internet, always getting 2 output. I just want one output.
BroadcastReceiver
public class Broadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (!isConnected){
Log.i("INTERNET","------------------------- not connect");
}
}
}
And this is the output
12659-12659 I/ViewRootImpl: CPU Rendering VSync enable = true
12659-12659 I/ViewRootImpl: CPU Rendering VSync enable = true
12659-12701 V/RenderScript: Application requested CPU execution
12659-12701 V/RenderScript: 0xb8116c40 Launching thread(s), CPUs 4
12659-12659 I/INTERNET: ------------------------- not connect
12659-12659 I/INTERNET: ------------------------- not connect
try this
create one class
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);
}
}
create one another class
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;
}
}
add permisiion in maenfiest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
**and this **
**
and dont forget to add this in manifiest
<receiver
android:name="com.ncrypted.redfox.Utils.ConnectivityReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
now call the where you want to check internet like this
implement this in your activity
ConnectivityReceiver.ConnectivityReceiverListener
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
showSnack(isConnected);
}
private void showSnack(boolean isConnected) {
if (isConnected) {
getUserStatus();
} else {
Toast.makeText(this, getString(R.string.str_internet_err), Toast.LENGTH_SHORT).show();
}
}
for more information please follow this link
You can check Network availability without Broadcast Receiver.
public class ConnectivityUtils {
private final Activity mActivity;
public ConnectivityUtils(Activity mActivity) {
this.mActivity = mActivity;
}
public boolean getConnectivityStatus() {
ConnectivityManager cm = (ConnectivityManager) mActivity
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return null != activeNetwork;
}
}
Add in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
So I just implemented a checking connectivity method, but should I do this for every activity? Is there a simpler way to continually check for connectivity?
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
First create a ConnectivityChangeReceiver like the following:
public class ConnectivityChangeReceiver extends BroadcastReceiver {
private OnConnectivityChangedListener listener;
public ConnectivityChangeReceiver(OnConnectivityChangedListener listener) {
this.listener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
listener.onConnectivityChanged(isConnected);
}
public interface OnConnectivityChangedListener {
void onConnectivityChanged(boolean isConnected);
}
}
Then create a BaseActivity which extends all of your activites:
public class BaseActivity extends Activity implements OnConnectivityChangedListener {
private ConnectivityChangeReceiver connectivityChangeReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
connectivityChangeReceiver = new ConnectivityChangeReceiver(this);
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(connectivityChangeReceiver, filter);
}
#Override
public void onConnectivityChanged(boolean isConnected) {
// TODO handle connectivity change
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(connectivityChangeReceiver);
}
}
(If you don't want a BaseActivity, you can implement OnConnectivityChangedListener in all of your activities. But in that case you have to register the receiver in all of your Activity.)
You can check this out: This is service that will continuously check the connection. This will be the proper way to do it
`private void installListener() {
if (broadcastReceiver == null) {
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
NetworkInfo info = (NetworkInfo) extras
.getParcelable("networkInfo");
State state = info.getState();
Log.d("InternalBroadcastReceiver", info.toString() + " "
+ state.toString());
if (state == State.CONNECTED) {
onNetworkUp();
} else {
onNetworkDown();
}
}
};
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
}
}`
Look on this link: Android service to check internet connectivity?
Create some sort of util class, for example ConnectionUtils.
Add a public static method to that class and add a Context object to the parameters. For example:
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return isConnected;
}
Then in your Activity just call ConnectionUtils.isNetworkAvailable(this) to know if you're connected.
It would even be better to create some sort of base Activity that you extend with this method in it.
public abstract class BaseActivity extends Activity {
protected boolean isConnected() {
return ConnectionUtils.isNetworkAvailable(this);
}
}
And then let all your Activities extend BaseActivity instead of Activity
You should check before every request to the internet! The user can terminate the connection at any given time... even while your Activity is running.
I suggest you make an Utils class and put this method inside and make it public static so you can access it from everywhere within the Application.
I say it is better to check before every request. It might happen that the connection got broken in between. So its not wise to rely on a check sometime earlier
I know this question might be replica of another question but can someone help me figure out where I have gone wrong and possibly correct it if possible?
public class MainActivity extends ActionBarActivity {
TextView ford;
public String TAG=MainActivity.class.getSimpleName();
protected static final long TIME_DELAY = 1000;
//the default update interval for your text, this is in your hand , just run this sample
TextView mTextView;
Handler handler=new Handler();
Random trust = new Random();
int count =0;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView=(TextView)findViewById(R.id.textview);}
protected void onResume({
super.onResume();handler.post(updateTextRunnable);}
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
Runnable updateTextRunnable=new Runnable(){
public void run() {
if (networkInfo != null && networkInfo.isConnected()) {
mTextView.setText("connected!");
} else {
mTextView.setText("No network connection available.");
}
}
};
}
Efficient way is to create a broacast receiver which will reguralry check wifi status. Register receiver like this-
WifiMonitor wifiMonitor = new WifiMonitor();
registerReceiver(wifiMonitor, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
registerReceiver(wifiMonitor, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
public class WifiMonitor extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//do your work here
}
}
I want to show a TextView to current active activity if internet is not availabe.
I am getting internet state but how to notify it to current active activity (In which activity my concentration is).
public class NetworkChangeReceiver extends BroadcastReceiver {
#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", "Netowk Available");
} else {
//notify it to current active activity and show a textview as
//"No internet connection"
}
}
}
In your activity:
public class YourActivity extends Activity {
private TextView mTextView;
public static final String NETWORK_DISABLE_ACTION = "yourpackagename.action.network_disbale";
private LocalBroadcastManager mLocalBroadcastManager;
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(NETWORK_DISABLE_ACTION)) {
mTextView.setText("No internet connection");
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_xml);
mTextView = (TextView) findViewById(R.id.your_textView_id);
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(NETWORK_DISABLE_ACTION);
mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, intentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
}
}
and in your NetworkChangeReceiver:
if (wifi.isAvailable() || mobile.isAvailable()) {
Log.d("TAG", "Netowk Available");
} else {
//notify it to current active activity and show a textview as
//"No internet connection"
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(
YourActivity.NETWORK_DISABLE_ACTION ));
}
I want to verify the Android system networks continuously in this way, but i think that in this form is not correct, my service should update if the connection on wifi or other network is available.
public class ObjService extends Service{
private final static int NOTIFICATION=1;
public static boolean process;
private NotificationManager state;
private NotificationCompat.Builder objBuilder;
public void onCreate(){
process=true;
state=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
objBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Title")
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.launchimg))
.setSmallIcon(R.drawable.notification_img);
Thread checker=new Thread(){//1
public void run(){//2
while (process){//3
if (verifyConnection()){//4
updateNotificationService("Service is available");
}else{
updateNotificationService("Service is not available");
}//4
try{
Thread.sleep(6000);
}catch(InterruptedException e){
//..printLog..
}
}//3
};//2
};//1
checker.start();
.
.
.
my function verifyConnection() is:
public boolean verifyConnection() {
boolean flag = true;
ConnectivityManager connec = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] net = connec.getAllNetworkInfo();
if (!net[0].isAvailable() && !net[1].isAvailable())
{
flag = false;
}
return flag;
}
updateNotificationService() is:
public void updateNotificacionService(String arg){
objBuilder.setContentText(arg)
.setWhen(System.currentTimeMillis());
state.notify(NOTIFICATION, objBuilder.build());
}
Try this code below to listen whether the connection exist, if the connection state changes it notifies the change,
public class NetworkStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
super.onReceive(context, 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");
}
}
if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
Log.d("app","There's no network connectivity");
}
}
}
Then for manifest,
<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" />
Reference: Internet listener Android example
Android 7.0 (API level 24) placed limitations on broadcasts, as
described in Background Optimization. Android 8.0 (API level 26) makes
these limitations more stringent.
Apps can use Context.registerReceiver() at runtime to register a
receiver for any broadcast, whether implicit or explicit.
Documentation reference.
So, here is a utility class that utilizes a context registered BroadcastReceiver , and LifeCycleObserver for achieving Single-responsibility principle
class ConnectionUtil implements LifecycleObserver {
private ConnectivityManager mConnectivityMgr;
private Context mContext;
private NetworkStateReceiver mNetworkStateReceiver;
interface ConnectionStateListener {
void onAvailable(boolean isAvailable);
}
ConnectionUtil(Context context) {
mContext = context;
mConnectivityMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
((AppCompatActivity) mContext).getLifecycle().addObserver(this);
}
void onInternetStateListener(ConnectionStateListener listener) {
mNetworkStateReceiver = new NetworkStateReceiver(listener);
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
// Registering the Context Registered Receiver
mContext.registerReceiver(mNetworkStateReceiver, intentFilter);
}
#OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
// Removing lifecycler owner observer
((AppCompatActivity) mContext).getLifecycle().removeObserver(this);
// Unregistering the Context Registered Receiver
if (mNetworkStateReceiver != null)
mContext.unregisterReceiver(mNetworkStateReceiver);
}
public class NetworkStateReceiver extends BroadcastReceiver {
ConnectionStateListener mListener;
public NetworkStateReceiver(ConnectionStateListener listener) {
mListener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getExtras() != null) {
NetworkInfo activeNetworkInfo = mConnectivityMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
// Connected to the internet
mListener.onAvailable(true);
} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
// Not connected to the internet
mListener.onAvailable(false);
}
}
}
}
}
Manifest permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Usage:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectionUtil mConnectionMonitor = new ConnectionUtil(this);
mConnectionMonitor.onInternetStateListener(new ConnectionUtil.ConnectionStateListener() {
#Override
public void onAvailable(boolean isAvailable) {
if(isAvailable)
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Disconnected", Toast.LENGTH_SHORT).show();
}
});
}
}
Note: NetworkInfo is deprecated as of API 29, and you can use ConnectivityManager.NetworkCallback with its onAvailable() & onLost() callbacks for the same purpose instead of using a BroadcastReceiver. This answer can guide to target this purpose.