How to reboot my current activity,when i connect net? - android

I am developing an application and I am displaying images from URl using xml parsing.
When internet gets disconnected I pop up alert window.
Now I wan my current activity automatically reboot, when my device connect net.

You need to have a BroadcastReceiver to listen to internet changes.
If you just need this logic in your activity you can do something like this:
private BroadcastReceiver mReceiver;
private IntentFilter mFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
mFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
mReceiver = new ConnectionChangeReceiver();
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
private class ConnectionChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent i) {
ConnectivityManager connectivityManager = (ConnectivityManager) ActivityActionBar.this
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getActiveNetworkInfo() == null) {
onLoseInternet();
}
}
}
onLoseInternet() method you should do something to reset everything.
Possibilities:
Best way I found so far
In the onCreate() method I have two calls: getWidgets() and populateWidgets().
getWidgets() is in charge of doing all the findViewById stuff and populateWidgets() will basically populate them with the correct info.
So when I need to reset the info I just call populateWidgets().
Hacky way
I don't know if this will work but you can try doing:
finish();
startActivity(new Intent(this, this.class));

Related

Dynamic BroadcastReceiver to Check Online Connectivity

I want to dynamically set up a BroadcastReceiver to check whether or not I am online ONLY when my app is running in the foreground. Within my main class, I created an an Intent Filter, a nested BroadcastReceiver Class and finally register/unregister the receiver within the onResume and onPause methods respectively.
My question is, is there an an intent ACTION that I can add to my intent filter that checks for online connectivity?
If not, how can I create this Dynamic Broadcast Receiver to perform only when my app is running?
Here is what my Class looks like....
public class MainActivity extends AppCompatActivity {
private IntentFilter onlineIntentFilter;
private CheckOnlineReceiver checkOnlineReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onlineIntentFilter = new IntentFilter();
checkOnlineReceiver = new CheckOnlineReceiver();
//*****WHAT INTENT ACTION CAN I PASS TO CHECK NETWORK CONNECTIVITY******
onlineIntentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(checkOnlineReceiver, onlineIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(checkOnlineReceiver);
}
private class CheckOnlineReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Toast.makeText(getApplicationContext(),"IN METHOD, ACTION = " + action, Toast.LENGTH_LONG).show();
}
}}
Add connectivity action
onlineIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
and don't forget to add the permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
The broadcast receiver's onReceive() will be called on connectivity change which means on both connected and disconnected. so whenever you receive the braodcast you have check for connectivity as below
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
Here is the standard way to do this.
Create a interface which will have two methods onNetworkConnected() and onNetworkDisconnected()
public interface NetworkConnectivityListener {
public void onNetworkConnected();
public void onNetworkDisconnected();
}
Any class that wants to listen to network changes will implement this interface and override it's two methods.
Create a class which will extend the BroadcastReceiver and this receiver's onReceive() will catch the connectivity changes. In this class create a function to register the listeners
public class NetworkBroadcastReceiver extends BroadcastReceiver {
private NetworkConnectivityListener listener;
public NetworkBroadcastReceiver(NetworkConnectivityListener listener) {
this.listener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (listener != null) {
if (isConnectedToInternet()) {
listener.onNetworkConnected();
} else {
listener.onNetworkDisconnected();
}
}
}
PS you can easily check if your device is connected to internet or not. Just google.
Now let's say you want your MainActivity to listen to netwrork changes, all you have to do is implement the NetworkConnectivityListener in your main activity call and create an instance of the NetworkBroadcastReceiver passing the context of MainActivity and it will start to get the network updates.
add intentfilter CONNECTIVITY_ACTION
You will need to create a service as you are looking to perform a long-running task in the background.
A service will need to be registered in the manifest, within the <application> tags.
<service android:name=".WifiService"
android:stopWithTask="true"
android:enabled="true"/>
stopWithTask causes the service to be destroyed when all of your activities are destroyed (the default value is true).
You will need to register and unregister a BroadcastReceiver to the CONNECTIVITY_CHANGE action in the service class.
public class WifiService extends Service {
private BroadcastReceiver mReceiver;
#Nullable
#Override
public IBinder onBind(Intent intent) {
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
// Your BroadcastReceiver class
mReceiver = new WifiReceiver();
registerReceiver(mReceiver, filter);
return null;
}
#Override
public boolean onUnbind(Intent intent) {
unregisterReceiver(mReceiver);
return super.onUnbind(intent);
}
}
And then in the BroadcastReceiver you must listen for CONNECTIVITY_CHANGE.
public class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isConnected = networkInfo != null &&
networkInfo.isConnectedOrConnecting();
if (isConnected) {
switch (networkInfo.getType()) {
case ConnectivityManager.TYPE_WIFI:
// Connected via wifi
break;
case ConnectivityManager.TYPE_ETHERNET:
// Connected via ethernet
break;
case ConnectivityManager.TYPE_MOBILE:
// Connected via mobile data
break;
}
}
}
}
With this setup you will be able to notify components of your application on connectivity change.

OnReceive() method auto triggered

I have created the one receiver inside an Activity for when internet is connected auto calling web service.
Code like
//Create receiver for while network will come auto call webservice
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (!noConnectivity) {
bar.setVisibility(View.VISIBLE);
callAuthorizeWebservice();
} else {
bar.setVisibility(View.INVISIBLE);
Toast.makeText(SplashScreenActivity.this, "Check Your Internet connection", Toast.LENGTH_LONG).show();
}
}
};
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(mConnReceiver);
}
#Override
protected void onStart() {
super.onStart();
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
When I open that Activity the onReceive() is method called everytime.
How to avoid calling it the first time (when opening that Activity)?
The broadcast is sent when you register for the first time(cf sticky broadcast), a solution is to use isInitialStickyBroadcast in the onReceive callback of your BroadcastReceiver to know if you are actually proceeding a sticky broadcast and act accordingly (BroadcastReceiver : isInitialStickyBroadcast)

Android:The if statement of wifi scan result is not being entered?

I have built BroadcastReceiver in my MainActivity to catch system broadcast(internet connection and wifi scan result). The internet connection broadcast is being caught but I am facing problem to catch the broadcast of the wifi scan result. no error is being thrown. I do not know what shall I add additional to get it work. I appreciate any help.
MainActivity:
public class MainActivity extends ActionBarActivity {
BroadcastReceiverListener receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new BroadcastReceiverListener();
}
private class BroadcastReceiverListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//This if statement is being arrived
if (intent.getAction().equals(
android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
//This code works without BroadcastReceiver.
}
else if (intent.getAction().equals(
android.net.ConnectivityManager.CONNECTIVITY_ACTION)) {
// I am getting here broadcast for the internet connection
}
}
};
protected void onResume() {
IntentFilter wifi = new IntentFilter();
wifi.addAction(android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(receiver, wifi);
IntentFilter conn = new IntentFilter();
conn.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(receiver, conn);
super.onResume();
}
#Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
}
There's no need to create two IntentFilters, just create the one and use addAction() to add multiple actions:
IntentFilter wifi = new IntentFilter();
wifi.addAction(android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
wifi.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(receiver, wifi);
See here:
Android - Registering a broadcast receiver for two intents?

Using broadcastreceiver only on certain activity

I have two activities on is Register() and the other is ReadNews(). I am using broadcast receiver to detect internet connection automatically to execute some code.
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
if(MyApplication.isActivityVisible() == true) {
Log.d("WifiReceiver", "Have Wifi Connection");
Toast.makeText(context, "تم الإتصال بالشبكة", Toast.LENGTH_LONG).show();
if (context instanceof RegisterActivity){
Intent i = new Intent(context,
ReadNews.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
else {
}
}
}
How can I start the ReadNews() activity only when the internet connection goes on while the user still using the RegisterActivity() only?
I tried to use the context like if (context instanceof RegisterActivity) but that doesn't seem right.
As I said in a comment, you don't need an inner class, you can just create a stand-alone class, like this:
public class MyWifiReceiver extends BroadcastReceiver {
private Activity activityToFinish;
MyWifiReceiver(Activity activityToFinish) {
this.activityToFinish = activityToFinish;
}
#Override
public void onReceive(Context context, Intent intent) {
// do what ever you want here
...
// finish the activity
activityToFinish.finish();
}
}
and in RegisterActivity, declare a private member variable like this:
private MyWifiReceiver wifiReceiver;
in RegisterActivity.onCreate() create an instance of the receiver passing the Activity in the constructor, like this:
wifiReceiver = new MyWifiReceiver(this);
then register and unregister the wifiReceiver as you've shown in your own answer.
Thanks to #Squonk comment, I have followed that short comment instructions to accomplish what I want to do and now I want to share summary of my code to show how this thing works:
Broadcast receiver inner class
private BroadcastReceiver wifiReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//do what ever you want here
};
registering Broadcast receiver in onResume()
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); //or any intent filter you want
registerReceiver(wifiReceiver, filter);
}
unregistering Broadcast receiver in onPause
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(wifiReceiver);
}
Important
Don't use an <intent-filter> in the manifest.
registering the broadcast receiver must be dynamic (onResume,onPause)

How to update the UI of Activity from BroadCastReceiver

I am learning Android concepts Activity and BroadCastReceiver. I want to update the content of Activity from the BroadtCastReceiver both are in different java class.
It is something like
MyActivity.java and MyBroadtCastReceiver.java
Is this possible to do this in Android ?
A BroadcastReceiver can be used in many ways but when it comes to something as specific as updating the UI components of an Activity, there is little advantage to declaring / defining a BroadcastReceiver in it's own Java class file.
Reasoning - the BroadcastReceiver has to have some prior "knowledge" of the Activity and what it is required to do in order to update the UI. In effect the BroadcastReceiver is tied to the Activity itself and it makes sense to declare / define it as an inner class.
Another important aspect is the Activity needs to be in a "running" (i.e., visible) state in order to guarantee manipulation of UI components. In this case, registering the receiver in onResume() and unregistering in onPause() will help prevent problems.
Using a generic template I'd do something like the following...
class MyActivity extends Activity {
boolean mIsReceiverRegistered = false;
MyBroadcastReceiver mReceiver = null;
// onCreate(...) here
#Override
protected void onResume() {
// Other onResume() code here
if (!mIsReceiverRegistered) {
if (mReceiver == null)
mReceiver = new MyBroadcastReceiver();
registerReceiver(mReceiver, new IntentFilter("YourIntentAction"));
mIsReceiverRegistered = true;
}
}
#Override
protected void onPause() {
if (mIsReceiverRegistered) {
unregisterReceiver(mReceiver);
mReceiver = null;
mIsReceiverRegistered = false;
}
// Other onPause() code here
}
private void updateUI(Intent intent) {
// Do what you need to do
}
private class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
}
}
EDIT: A couple of extra notes...
The life-cycle of a BroadcastReceiver is between entering and leaving onReceive(...). Once it has returned from onReceive(...) the instance remains in a dormant state waiting for the next broadcast.
Directly related to point 1 - a BroadcastReceiver isn't designed for "heavy lifting". Basically the onReceive(...) method should be kept as simple as possible. Any methods it calls should also be as light-weight as possible...get in, do your stuff, get out then wait for the next broadcast. If updating the UI is going to take some time (perhaps updating a ListView by re-querying a database for a large amount of data for example), consider calling code which performs asynchronously (an AsyncTask for example).
Yes its possible. This is what i do.
Class i send the broadcast from (BackgroundActivity.java):
public static final String BROADCAST_BUFFER_SEND_CODE = "com.example.SEND_CODE";
onCreate(){
bufferIntentSendCode = new Intent(BROADCAST_BUFFER_SEND_CODE);
}
private void sendBufferingBroadcastSendCode() {
bufferIntentSendCode.putExtra("buffering", "1");
sendBroadcast(bufferIntentSendCode);
}
The class it will receive the broadcast(SendCode.java):
onResume(){
registerReceiver(broadcastBufferReceiver, new IntentFilter(BackgroundActivity.BROADCAST_BUFFER_SEND_CODE));
}
// set up broadcast receiver
private BroadcastReceiver broadcastBufferReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent bufferIntent) {
SendCode.this.LoadMessages(alarmNumber);
}
};
I unregister it in onPause
this.unregisterReceiver(broadcastBufferReceiver);
Register a new BroadcastReceiver object in your activity with same intent-filters as your MyBroadtCastReceiver. Since BroadcastReceiver and MyBroadtCastReceiver has same intent-filters both of their onReceive() will be invoked. Whatever update that you want to do in Activity can be done in onReceive of your BroadcastReceiver.
You can do like this:
public class MyActivity extends Activity{
// used to listen for intents which are sent after a task was
// successfully processed
private BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
new UpdateUiTask().execute();
}
};
#Override
public void onResume() {
registerReceiver(mUpdateReceiver, new IntentFilter(
YOUR_INTENT_ACTION));
super.onResume();
}
#Override
public void onPause() {
unregisterReceiver(mUpdateReceiver);
super.onPause();
}
// used to update the UI
private class UpdateUiTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... voids) {
Context context = getApplicationContext();
String result = "test";
// Put the data obtained after background task.
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO: UI update
}
}
}
Squonk-s answer only works, if the Activity is active currently.
If you dont want to declare / define your BroadcastReceiver (BR) in an other Activity, or if you want to make some changes even if the app is not foreground, than your solution would look something like this.
First, you declare the BR, and save, or override the data needed to show in Acitvity.
public class MyBR extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// override the data. Eg: save to SharedPref
}
}
Then in Activity, you show the data
TextView tv = findViewById(R.id.tv);
tv.setText(/*get the data Eg: from SharedPref*/);
And you should use a Timer to refresh the tv as well:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView tv = findViewById(R.id.tv);
tv.setText(/*get the data Eg: from SharedPref*/);
}
});
}
}, REFRESH_RATE, REFRESH_RATE);
REFRESH_RATE could be something like 1 second, but you decide.
try like this it may help you.
Define this method in activity's oncreate method in which you want to update ui,
BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//your code to update ui
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("giveyourappname"));
Define this action at place from where you want to update ui,
try{
ActivityManager am = (ActivityManager) this .getSystemService(ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
Log.d("Activity", "Current Activity ::" + taskInfo.get(0).topActivity.getClassName());
Log.d("Package", "Package Name : "+ componentInfo.getPackageName());
if(componentInfo.getPackageName().equals("your application package name")){
Intent intent = new Intent("giveyourappname");
//add data you wnat to pass in intent
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}catch(Throwable e){
e.printStackTrace();
}

Categories

Resources