hi i have created a global actions class and created functions inside this class which i'm trying to access inside another activity the problem i'm having is that in eclipse I'm getting coding errors around the functions that access system feature such as getSystemService() and getApplicationContext() does anyone know why or how to let a global class accept system features?
heres what i have so far heres my GloblActions.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class GlobalActions{
Context mContext;
// constructor
public GlobalActions(Context context){
this.mContext = context;
}
public final static boolean isOnline (Context someContext){ {
Log.v("globals", "isonline");
ConnectivityManager cm = (ConnectivityManager) someContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
public final static void checkInternet(Context someContext){
isOnline(someContext);
if(isOnline(someContext) == false){
Log.v("globals", "isOnline = false");
Intent register = new Intent(someContext.getApplicationContext(), LoginForm.class);
someContext.startActivity(register);
}
}
}
heres where i'm using the function in an activity. my goal is is to check internet connection on every activity by just calling the global function and if no connection is found go to an activity that says no internet connection.
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.os.Handler;
import com.myApp.myApp.GlobalActions;
public class IntroLoader extends Activity {
public Handler handler;
public TextView loadText = null;
public Animation AniFadein = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lo_introloader);
findViewById(R.id.progressBar1).setVisibility(View.GONE);
findViewById(R.id.loadTextView).setVisibility(View.GONE);
GlobalActions.isOnline(null);
GlobalActions.checkInternet(null);
handler = new Handler();
final Runnable fadeIn = new Runnable()
{
public void run()
{
animations();
findViewById(R.id.progressBar1).setVisibility(View.VISIBLE);
findViewById(R.id.loadTextView).setVisibility(View.VISIBLE);
}
};
handler.postDelayed(fadeIn, 3000);
final Runnable aSyncTask= new Runnable()
{
public void run()
{
PostTask posttask;
posttask = new PostTask();
posttask.execute();
}
};
handler.postDelayed(aSyncTask, 4000);
}
public void animations(){
loadText = (TextView)findViewById(R.id.loadTextView);
AniFadein = AnimationUtils.loadAnimation(this, R.anim.fadein);
loadText.startAnimation(AniFadein);
}
public class PostTask extends AsyncTask<Void, String, Boolean> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
boolean result = false;
publishProgress("progress");
return result;
}
protected void onProgressUpdate(String... progress) {
StringBuilder str = new StringBuilder();
for (int i = 1; i < progress.length; i++) {
str.append(progress[i] + " ");
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
checkLoginData();
}
}
public void checkLoginData(){
Intent register = new Intent(getApplicationContext(), LoginForm.class);
startActivity(register);
}
}
Do
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
Contexts can use the method getSystemService() but your class isn't a Context, you need to use your mContext variable.
This means that you can also replace getApplicationContext() with mContext. And if you really need getApplicationContext() (unlikely - normal Contexts should work fine), use
mContext.getApplicationContext()
Also, you declare your isOnline() method as static, but then you need to use a Context for checking and making the toast. Either don't make it static or change it so it accepts in a Context, eg
public final static boolean isOnline (Context someContext){
And replace calls there that need a Context with someContext. Static methods don't need an instance of the class, and so, you can't use mContext. Once you fix the getApplicationContext() issue you have now, the compiler should throw an error about accessing a non static field in a static way. Same with your checkInternet(). I suggest you revaluate your logic, there are multiple problems with your class - I suggest making everything a static method that accepts in a Context which will be given by the calling Activity.
Lastly be careful about showing Toasts and other UI Elements in a global non-ui class. Toasts should be fine since they run on top of windows, but a Dialog will need a window, and if mContext is not an instance of Activity, that will fail (Activities have a window, other Contexts (like getApplicationContext()), do not.
Related
The goal of the code is to query the google api for a list of books that the user has chosen. The app takes the text inputted in the editText field, and when the user clicks the search button, the query parameter in the query url should be changed to the inputted text then another network request is made using a loader. I can't seem to get this to function. Below is the code:
Query URLS
private static String queryUrl = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=20&orderBy=relevance";
private static String baseUrl = "https://www.googleapis.com/books/v1/volumes?";
Search Button On Click
//Method that takes the current URL and modifies it based on what the user searched
private void searchButtonOnClick() {
Log.d(LOG_TAG, "searchButtonOnClick was called");
//Get the user input
if (TextUtils.isEmpty(editText.getText())) {
Toast.makeText(this, "No Search Entered", Toast.LENGTH_SHORT).show();
} else {
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme("https")
.authority("www.googleapis.com")
.appendPath("books")
.appendPath("v1")
.appendPath("volumes")
.appendQueryParameter("q", editText.getText().toString())
.appendQueryParameter("maxResults", "100")
.appendQueryParameter("orderBy", "relevance");
queryUrl = uriBuilder.build().toString();
LoaderManager loaderManager = getSupportLoaderManager();
booksListAdapter.clear();
loaderManager.initLoader(BOOK_LOADER_ID, null, this);
}
}
Full MainActivity Class
package com.example.booksearch;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;
import android.net.Uri.Builder;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.lang.reflect.Array;
import java.net.NetworkInterface;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Book>> {
//Log tag for debugging purposes
public static final String LOG_TAG = MainActivity.class.getSimpleName();
//Getting title author and image, link book to where to buy when clicked
private static String input = "";
private static String queryUrl = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=20&orderBy=relevance";
private static String baseUrl = "https://www.googleapis.com/books/v1/volumes?";
private EditText editText;
private List<Book> books = new ArrayList<>();
private static BooksListAdapter booksListAdapter;
private static int BOOK_LOADER_ID;
private Button searchButton;
private TextView emptyTextView;
private ImageView imageView;
private ProgressBar loadProgressIndicator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Hook up search button
searchButton = findViewById(R.id.search_button);
//Hook up editText
editText = findViewById(R.id.search_edit_text);
//setting up searchButtonOnclickListener
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchButtonOnClick();
}
});
//Get a connectivity Manager to monitor network state
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
//Get details about the devices network
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
//Hook up the empty textView
emptyTextView = findViewById(R.id.empty_text_view);
//Hook up progress indicator
loadProgressIndicator = findViewById(R.id.loading_data_progress_indicator);
//If there is a network connection fetch data if not, set the text on the empty text view accordingly
if (networkInfo != null && networkInfo.isConnected()) {
LoaderManager loaderManager = getSupportLoaderManager();
loaderManager.initLoader(BOOK_LOADER_ID, null, this);
} else {
//if no internet connection display error message
loadProgressIndicator.setVisibility(View.GONE);
emptyTextView.setText(R.string.no_internet);
}
// the Book objects are added to this array list off the main thread, thats why the adapter is set to an empty array list.
//This line of code will always be executed before the asynchonous Load is done, because it's on the main thread.
booksListAdapter = new BooksListAdapter(this, new ArrayList<Book>());
ListView bookListView = findViewById(R.id.book_list_view);
bookListView.setAdapter(booksListAdapter);
bookListView.setEmptyView(emptyTextView);
//Set onclick listener on the list to send the user to where to buy the book
bookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Book currentBook = booksListAdapter.getItem(position);
//Check to see if there is a place to buy the book before sending the user off
if (currentBook.getWhereToBuyBook().isEmpty()) {
Toast.makeText(MainActivity.this, "Cannot find where to purchase", Toast.LENGTH_SHORT).show();
} else {
Uri bookURi = Uri.parse(currentBook.getWhereToBuyBook());
//Creating an intent to send the user to a website
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, bookURi);
//send the intent to another app that can handle it
startActivity(websiteIntent);
}
}
});
}
#NonNull
#Override
public Loader<List<Book>> onCreateLoader(int id, #Nullable Bundle args) {
return new BookLoader(this, queryUrl);
}
#Override
public void onLoadFinished(#NonNull Loader<List<Book>> loader, List<Book> data) {
//After the first results load check for internet connectivity to avoid error message loading at app startup
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo == null) {
emptyTextView.setText(R.string.no_internet);
} else if (networkInfo != null && networkInfo.isConnected()) {
//display when there is internet but there were no results
emptyTextView.setText(R.string.no_books_found);
}
booksListAdapter.clear();
//If there is a valid list of books, add them to the dataset, this will trigger the listview to update
if (data != null && !data.isEmpty()) {
booksListAdapter.addAll(data);
} else {
emptyTextView.setText(R.string.no_books_found);
}
loadProgressIndicator.setVisibility(View.GONE);
}
#Override
public void onLoaderReset(#NonNull Loader<List<Book>> loader) {
booksListAdapter.clear();
}
//Method that takes the current URL and modifies it based on what the user searched
private void searchButtonOnClick() {
Log.d(LOG_TAG, "searchButtonOnClick was called");
//Get the user input
if (TextUtils.isEmpty(editText.getText())) {
Toast.makeText(this, "No Search Entered", Toast.LENGTH_SHORT).show();
} else {
Uri buildUri = Uri.parse(baseUrl);
Uri.Builder uriBuilder = new Uri.Builder();
buildUri.buildUpon();
uriBuilder.scheme("https")
.authority("www.googleapis.com")
.appendPath("books")
.appendPath("v1")
.appendPath("volumes")
.appendQueryParameter("q", editText.getText().toString())
.appendQueryParameter("maxResults", "100")
.appendQueryParameter("orderBy", "relevance");
queryUrl = uriBuilder.build().toString();
booksListAdapter.clear();
LoaderManager loaderManager = getSupportLoaderManager();
loaderManager.restartLoader(BOOK_LOADER_ID, null, this);
loaderManager.initLoader(BOOK_LOADER_ID, null, this).forceLoad();
}
}
}
As per the code snippet you have shared, .appendQueryParameter("q", editText.getText().toString()) is taking the query param already. Can you explain a bit more, what exactly is the issue you are facing?
Update:
Change your query to --
private static String baseUrl = "https://www.googleapis.com/books/v1/volumes?maxResults=20&orderBy=relevance&q=";
Change your else block to this -
else {
queryUrl = baseUrl + editText.getText().toString();
LoaderManager loaderManager = getSupportLoaderManager();
booksListAdapter.clear();
loaderManager.initLoader(BOOK_LOADER_ID, null, this);
}
Long story short, I have a class that handles my app shared preferences.
I call it from various other classes without issues, but when I try to call it from my service (from the same APK) I get a null exception. I am guessing that it's getting called from the wrong context or something like that. Here is the relevant code.
MainActivity.java
package com.deskwizard.audiomanager;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.deskwizard.audiomanager.DataSaveRestore;
public class MainActivity extends FragmentActivity {
public static Context contextOfApplication;
final FragmentManager fm = getFragmentManager();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contextOfApplication = getApplicationContext();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_settings, new FadeBalanceFragment());
ft.commit();
// TODO: Load previously saved settings for all values
DataSaveRestore.restore_all();
// TODO: init I2C
}
public static Context getContextOfApplication() {
return contextOfApplication;
}
}
DataSaveRestore.java (defaultpreferences class)
package com.deskwizard.audiomanager;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
public class DataSaveRestore extends Application {
// Data variables
public static int Bass_level, Bass_CFreq, Bass_Qfact, Sub_level,
Sub_Lowpass, Treble_level, Treble_CFreq, Mid_level, Mid_CFreq,
Mid_Qfact, Fade, Balance, Loudness_level, Loudness_freq,
Loudness_boost;
static boolean Bass_DCMode, Loudness_state;
static Context applicationContext = MainActivity.getContextOfApplication();
public static void restore_all() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(applicationContext);
if (prefs.getInt("data_saved", 0) == 0) {
set_defaults();
load_defaults();
} else {
load_defaults();
}
//TODO: send settings to TDA7418
DS3903.set_lowpass(DataSaveRestore.Sub_Lowpass);
};
Service code snippet:
public class AudioManagerService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO do something useful
Log.d("com.deskwizard.audiomanager", "starting service...");
DataSaveRestore.restore_all(); // restore settings to TDA7418/DS3903
start();
return Service.START_STICKY;
}
The Null Exception error refers to this line, only when called from the service, it works properly from the main application and other classes:
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(applicationContext);
Let me know if any further code can help narrow it down.
Thanks,
DW
Because, In your service when you call, DataSaveRestore.restore_all(); It make reference on, (As there is no MainActivity context available from Servce)
static Context applicationContext = MainActivity.getContextOfApplication();
on this line, applicationContext will be null as it can't find MainActivity initialization
Simply, Just change your restore_all() method from Application class.
First remove static and and use getApplicationContext() of Android application class method to get application context as in Service,
public void restore_all() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
if (prefs.getInt("data_saved", 0) == 0) {
set_defaults();
load_defaults();
} else {
load_defaults();
}
//TODO: send settings to TDA7418
DS3903.set_lowpass(DataSaveRestore.Sub_Lowpass);
};
Now call, restore_all(); by initializing object of Application class not a static way.
Like,
DataSaveRestore dataSaveRestore = (DataSaveRestore) getApplicationContext();
dataSaveRestore.restore_all();
I'm working on getting a better handle on AsyncTask and am trying to create controls dynamically with asyncTask's onPostExecute().
The code I have below does work and it creates controls, but is there a way to loop this, but delay it so that variable I is incremented after the asynctask completes?
I've read through using the get() method, but I can't seem to make it work.
Can anyone advise how to either wait till a background task is complete or some other way to dynamically create controls based on a variable number?
package com.example.dynamicallycreatecontrols;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
Integer i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
while (i < 5) {
new createControl().execute(i);
i++;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//asynctask
public class createControl extends AsyncTask<Integer, Void, Button> {
Button btn = new Button(MainActivity.this);
LinearLayout ll = (LinearLayout) findViewById (R.id.llMain);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
protected void onPreExecute(Integer i) {
// nothing right now
}
#Override
protected Button doInBackground(Integer... arg0) {
// TODO Auto-generated method stub
// do the calculation
return null;
}
protected void onPostExecute(Button v) {
// build the controls here
btn.setText("Play" + i);
ll.addView(btn, lp);
SystemClock.sleep(1000);
}
}
}
I'm new to android development and java so i'm not sure if I'm just misunderstanding a concept of get() or if there is a better way to do this all together.
Thanks for any time allocated in assistance.
-nick
When doInBackground() done I move to onPostExecute(). I don't need any delays there. When I call task.execute(/**/) actually I invoke doInBackground() async task and I don't care when it finish but I know that I have callback onPostExecute() and I wait and update my main Thread from there.
To make it clearer lets say you have application where user wants to register to server and update GUI led to green color. User presses on button and calls method registerClient()
This method runs:
private void registerClient(){
...
dialog = ProgressDialog.show(LoginActivity.this, "", "Connecting. Please wait...", true);
HeavyTask task = new HeavyTask();
task.execute(user, password, domain);
}
So what we have in HeavyTask:
private class HeavyTask extends AsyncTask<String, Void, Void> {
private String username = "";
private String domain = "";
private String password = "";
// run async task
protected Void doInBackground(String... args) {
username = args[0];
password = args[1];
domain = args[2];
registerClientToServer(username, password, domain, null);
return null;
}
protected void onPostExecute(Void results) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
updateGUI(username, domain);
}
}, 500);
}
}
Why not create an object and instantiate it? You can control if the object exists or if it already finished what he had to do.
Example:
public class MainActivity extends Activity {
private createControl cc = null;
Integer i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
while (i < 5) {
if (cc == null){
cc = new createControl();
cc.execute(i);
i++;
}
}
}
...
}
Then in onPostExecute just add cc = null;
I'm starting with android, my question is regarding to this official tutorial:
http://developer.android.com/training/basics/network-ops/connecting.html
In the "Perform network operations on a Separate Thread", I have the exact same code in eclipse and I get the following error in eclipse:
The type MainActivity.DownloadWebpageText must implement the inherited abstract method AsyncTask.doInBackground(Object...)
I understand that to override doInBackground() it must get an object as parameter and I expecting and String...
How do i solve that?
I'm pretty confused, because this code is in the main android training section.
Thank you very much and merry christmas!
EDIT: Here's my code. Same code that the guide i linked:
package com.example.com.example.networkoperations;
import java.io.IOException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
final String LOG_TAG = "Connectivity tests (chux)";
Button btn;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(this);
tv = (TextView) findViewById(R.id.textView1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onClick(View arg0) {
tvText("Clicado!");
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()){
new DownloadWebpageText().execute("http://mydomain.com");
}
else
tvText("No hay conexión a internet");
}
private void tvText(String text){
String oldText = tv.getText().toString() + "\n";
tv.setText(oldText + text);
}
private class DownloadWebpageText extends AsyncTask{
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
tv.setText(result);
}
}
}
Change the you class deceleration of downloading from
private class DownloadWebpageText extends AsyncTask{
}
to be like
private class DownloadWebpageText extends AsyncTask<String,Void,String>{
}
Anyone know if I can receive my main Activity's onStop, onPause and onResume callbacks inside another class / object?
I've got a broadcast receiver that lives inside another class (a WebView). I use the receiver to detect when the network goes down and switch to a local copy of my page with some useful content. I need to un-register the broadcast receiver when onStop/onPause are called and re-register it during onResume.
I can do this by hand (I added a couple public methods to a class that extends WebView to do just that) , but it'd be nice to have Android just call it for me.
edit: Sure, here's the class, I'd like it to be able to receive get a callback from Android when my main activity's onStop gets called without having to call startInternetMonitoring() / stopInternetMonitoring():
package com.glimmersoft.spent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
/**
* #author Jer
*
*/
public class OfflineWebView extends WebView {
private BroadcastReceiver receiver;
private IntentFilter filter;
private Context myContext;
public OfflineWebView(Context context,AttributeSet attrs) {
super(context, attrs);
WebSettings webSettings = this.getSettings();
webSettings.setJavaScriptEnabled(true);
myContext = context;
}//END CLASS CONSTRUCTTOR
/**
* #param internetOn The URL to display in this OfflineWebView when there is an active Internet connection.
* #param internetOff The URL to display in this OfflineWebView if there is no active Internet connection.
*/
public void setPages(final String internetOn, final String internetOff){
final OfflineWebView finalThisRef = this;
filter = new IntentFilter();
filter.addAction(SpendConstants.ANDROID_CONNECTIVITY_CHANGED);
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm.getActiveNetworkInfo()!=null&&cm.getActiveNetworkInfo().isConnected()){// TODO: THIS FAILES IF
finalThisRef.loadUrl(internetOn);
}else{
finalThisRef.loadUrl(internetOff);
}
}//END IF/ELSE
};
myContext.registerReceiver(receiver, filter);
}//END FUNCTION SETPAGES
public void startInternetMonitoring(){
myContext.registerReceiver(receiver, filter);
}//END METHOD STARTINTERNETMONITORING
public void stopInternetMonitoring(){
myContext.unregisterReceiver(receiver);
}//END METHOD STOPINTERNETMONITORING
}//END CLASS OfflineWebView
Thanks all!
Instead of putting your BroadcastReceiver inside your OfflineWebView, make it a static class you register maybe in a base Activity and have it a hold a reference to your OfflineWebView. When onReceive is called, you can then reference your OfflineWebView to load your online/offline content.
file: MyBaseActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.webkit.WebView;
public class MyBaseActivity extends Activity {
private static final String ANDROID_CONNECTIVITY_CHANGED = "android.net.conn.CONNECTIVITY_CHANGE";
protected static final ConnectivityBroadcastReceiver sReceiver = new ConnectivityBroadcastReceiver();
private static final IntentFilter sFilter = new IntentFilter(ANDROID_CONNECTIVITY_CHANGED);
static class ConnectivityBroadcastReceiver extends BroadcastReceiver {
private String internetOnUrl = "your online url";
private String internetOffUrl = "your offline url";
WebView offlineWebView;
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// only do your online/offline loading if we have a webview set
if (offlineWebView != null) {
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isConnected()) {
offlineWebView.loadUrl(internetOnUrl);
} else {
offlineWebView.loadUrl(internetOffUrl);
}
}
}
}
#Override
public void onStart() {
super.onStart();
// register receiver
registerReceiver(sReceiver, sFilter);
}
#Override
public void onStop() {
super.onStop();
// unregister receiver
unregisterReceiver(sReceiver);
}
}
file: MyActivity.java
import android.R;
import android.os.Bundle;
import android.webkit.WebView;
public class MyActivity extends MyBaseActivity {
private WebView mWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// load your content root
setContentView(R.layout.main_layout);
// find your webview
mWebView = (WebView)findViewById(R.id.webView);
}
#Override
public void onStart() {
super.onStart();
// set your webview in the OfflineBroadcastReceiver
sReceiver.offlineWebView = mWebView;
}
#Override
public void onStop() {
super.onStop();
// clear your webview from the OfflineBroadcastReceiver
sReceiver.offlineWebView = null;
}
}