Notify to the active activity from BroadcastReceiver - android

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 ));
}

Related

How can close app when WIFI is connected?

recently when I click wifi connect button.
showing Connectreceiver.class (activity)
I want when finish wifi connect (=connected state)
finish app (=kill app)
How can I do?
public class Connectingreceiver extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connecting_dialog);
registerReceiver(progressFinish, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
}
private BroadcastReceiver progressFinish = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
if(networkInfo.getState()== NetworkInfo.State.CONNECTED){
moveTaskToBack(true);
finish();
android.os.Process.killProcess(android.os.Process.myPid());
}
}
}
};
#Override
protected void onPause(){
super.onPause();
try{
unregisterReceiver(progressFinish);
} catch (IllegalArgumentException e){
e.printStackTrace();
}
}
}

how to broadcast messge when data connection is enable and disable in android

public class MainActivity extends ActionBarActivity {
CheckinternetConnection internet;
TextView textview;
int tempint = 100;
private static final long REPEAT_TIME = 1000 * 5;
private PendingIntent pendingIntent;
Button button1;
Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.textview);
internet = new CheckinternetConnection();
schedueService();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(internet, filter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(internet);
}
class CheckinternetConnection extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (Utils.isNetworkAvailable(MainActivity.this)) {
textview.setVisibility(View.GONE);
startService(new Intent(getBaseContext(), myserveclass.class));
schedueService();
//setMobileDataEnabled(getApplicationContext(), true);
} else {
textview.setVisibility(View.VISIBLE);
textview.setText("It Seems Internet Connection is off");
stopService(new Intent(getBaseContext(), myserveclass.class));
CancelAlarm();
}
}
}
this is my code using this code i am able to display Connected and disconnected when application Launch i want as i Enable data connection from Setting or Top of device then there should show Data is connected and as i will Off data connection then it should display data is not connected actully i want start service when My application has network connection and stop service when notwork is not connected suggest me how to implement this.
Try with this receiver
Also make sure you have the permissions in the Manifest
class CheckinternetConnection extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conn = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = conn.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (isConnected==true)
textview.setVisibility(View.GONE);
startService(new Intent(getBaseContext(), myserveclass.class));
schedueService();
//setMobileDataEnabled(getApplicationContext(), true);
} else {
textview.setVisibility(View.VISIBLE);
textview.setText("It Seems Internet Connection is off");
stopService(new Intent(getBaseContext(), myserveclass.class));
CancelAlarm();
}
}
}

in android How to update Activity if any network changes

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");
}
}
}

Check Android Network continuously

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.

Android event for internet connectivity state change [duplicate]

This question already has answers here:
Check INTENT internet connection
(13 answers)
Closed 4 years ago.
I am making an app where a user is uploading information and files to my server on a somewhat frequent basis. This is done in new threads through a dedicated uploader service.
I know from this thread
Detect whether there is an Internet connection available on Android
that you can check if there is an internet connection relatively easily. You can also get socketTimeoutExceptions to detect internet connectivity issues. All that is well and good, and lets me cache my uploads easily enough when the connection didn't work for whatever reason.
My question though is how do I know when to reattempt the upload? Is there an event triggered when the connection is restored? Or am I stuck making a new thread that sleeps and then checks internet connectivity every 30 seconds or something?
Any ideas would be appreciated!
very old post
but i would like to share my receiver
no need to put your hands on manifest or other boring resources :)
USAGE
YOUR ACTIVITY:
/*
* You need to implement NetworkStateReceiverListener.
* This interface is described inside the NewtworkStateReceiver class
*/
public class MyActivity implements NetworkStateReceiverListener {
/* ... */
private NetworkStateReceiver networkStateReceiver;
}
IN YOUR ACTIVITY: INSTANTIATE THE RECEIVER
public void onCreate(Bundle savedInstanceState) {
/* ... */
networkStateReceiver = new NetworkStateReceiver();
networkStateReceiver.addListener(this);
this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}
public void onDestroy() {
super.onDestroy();
networkStateReceiver.removeListener(this);
this.unregisterReceiver(networkStateReceiver);
}
IN YOUR ACTIVITY: IMPLEMENTS THE REQUIRED METHODS
#Override
public void networkAvailable() {
Log.d("tommydevall", "I'm in, baby!");
/* TODO: Your connection-oriented stuff here */
}
#Override
public void networkUnavailable() {
Log.d("tommydevall", "I'm dancing with myself");
/* TODO: Your disconnection-oriented stuff here */
}
THE RECEIVER
just copy and paste into your project as NetworkStateReceiver.java
public class NetworkStateReceiver extends BroadcastReceiver {
protected Set<NetworkStateReceiverListener> listeners;
protected Boolean connected;
public NetworkStateReceiver() {
listeners = new HashSet<NetworkStateReceiverListener>();
connected = null;
}
public void onReceive(Context context, Intent intent) {
if(intent == null || intent.getExtras() == null)
return;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
connected = true;
} else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
connected = false;
}
notifyStateToAll();
}
private void notifyStateToAll() {
for(NetworkStateReceiverListener listener : listeners)
notifyState(listener);
}
private void notifyState(NetworkStateReceiverListener listener) {
if(connected == null || listener == null)
return;
if(connected == true)
listener.networkAvailable();
else
listener.networkUnavailable();
}
public void addListener(NetworkStateReceiverListener l) {
listeners.add(l);
notifyState(l);
}
public void removeListener(NetworkStateReceiverListener l) {
listeners.remove(l);
}
public interface NetworkStateReceiverListener {
public void networkAvailable();
public void networkUnavailable();
}
}
ENJOY ;)
If you just want to do something simple when the connectivity changes, there is a much easier solution.
In your activity, create a Broadcast Receiver:
private BroadcastReceiver networkStateReceiver=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
doSomethingOnNetworkChange(ni);
}
};
Then in onResume and onPause do the registration:
#Override
public void onResume() {
super.onResume();
registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
public void onPause() {
unregisterReceiver(networkStateReceiver);
super.onPause();
}
Not quite sure what was going on in Tommaso's broadcast receiver but it wasn't working for me, here's my implementation. It only notifies on change between connectivity available/unavailable.
Also I register it in onResume() and unregister in onPause(). Otherwise it's the same as above.
public class NetworkStateReceiver extends BroadcastReceiver {
private ConnectivityManager mManager;
private List<NetworkStateReceiverListener> mListeners;
private boolean mConnected;
public NetworkStateReceiver(Context context) {
mListeners = new ArrayList<NetworkStateReceiverListener>();
mManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
checkStateChanged();
}
public void onReceive(Context context, Intent intent) {
if (intent == null || intent.getExtras() == null)
return;
if (checkStateChanged()) notifyStateToAll();
}
private boolean checkStateChanged() {
boolean prev = mConnected;
NetworkInfo activeNetwork = mManager.getActiveNetworkInfo();
mConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return prev != mConnected;
}
private void notifyStateToAll() {
for (NetworkStateReceiverListener listener : mListeners) {
notifyState(listener);
}
}
private void notifyState(NetworkStateReceiverListener listener) {
if (listener != null) {
if (mConnected) listener.onNetworkAvailable();
else listener.onNetworkUnavailable();
}
}
public void addListener(NetworkStateReceiverListener l) {
mListeners.add(l);
notifyState(l);
}
public void removeListener(NetworkStateReceiverListener l) {
mListeners.remove(l);
}
public interface NetworkStateReceiverListener {
public void onNetworkAvailable();
public void onNetworkUnavailable();
}
}
Android Nougat & O (API 24+) - Network State
Changes mades to #darnmason answer (constructor) to make it work on API 24+.
public NetworkStateReceiver(Context context) {
mListeners = new ArrayList<>();
mManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(NetworkStateReceiver.this, intentFilter);
checkStateChanged();
}

Categories

Resources