Activity won't load when checking internet connection - java

I'm trying to create an app that checks for internet connection when it opens. I want it to display a loading screen as long as there is not internet connection and a message. The loading screen activity is activity_main.xml. The problem is that because I'm calling LoggingIn method from itself, it keeps repeating it untill I have internet connection, but the problem is that for some reason it just won't load the activity itself. It just shows me a blank screen. When I don't run LoggingIn the activity does work.
Please help is there any other way to do this?
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoggingIn();
}
public void LoggingIn ()
{
if (isNetworkAvailable())
{
if (findViewById(R.id.InternetConnection).getVisibility() == View.VISIBLE)
{
findViewById(R.id.InternetConnection).setVisibility(View.GONE);
}
AttemptLoggingIn();
}
else
{
findViewById(R.id.InternetConnection).setVisibility(View.VISIBLE);
LoggingIn();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Use background threads instead of your very strange method.
For example,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startCheck();
}
private boolean startCheck() {
new Thread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
findViewById(R.id.InternetConnection).setVisibility(View.VISIBLE);
}
});
while(!isNetworkAvailable()) {
try {
Thread.sleep(100L);// 100 ms sleep
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
if (findViewById(R.id.InternetConnection).getVisibility() == View.VISIBLE)
{
findViewById(R.id.InternetConnection).setVisibility(View.GONE);
}
AttemptLoggingIn();
}
});
}
}).start();
}

You don't need to call LoggingIn() to monitor network changes.
ConnectivityManager automatically broadcasts the CONNECTIVITY_ACTION action whenever the connectivity details change.This article can be really useful for you:
http://www.androidhive.info/2012/07/android-detect-internet-connection-status/

Related

Stop/start mediaplayer from another activity

i'm trying to play stream radio using Mediaplayer with MP1 as variable of Mediaplayer i want to play it in all Fragments app,expect one activity (ActivityOne) which is contains another Mediaplayer MP2 to play,so i want to stop MP1 when i'm in (ActivityOne) activity, and play MP2 , and when i return from (ActivityOne) i want to resume MP1, my big problem is the (ActivityOne) called when i click button which is exist in fragment
my code below works only in one direction :
when i return from (ActivityOne) activity, the music stops.
structure of the app : MainAcitivty > Fragment > ActivityOne
MainActivity.java
MediaPlayer MP1;
boolean prepared = false;
boolean started = false;
PlayerTask playerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = new MediaPlayer();
playerTask = new PlayerTask();
playerTask.execute(stream);
/**/
MusicButton = findViewById(R.id.toggleButton);
MusicButton.setVisibility(View.INVISIBLE);
MusicButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (started && MusicButton.isChecked()) {
started = false;
MP1.pause();
MusicButton.setChecked(true);
} else {
started = true;
MP1.start();
MusicButton.setChecked(false);
}
}
});
}
#SuppressLint("StaticFieldLeak")
public class PlayerTask extends AsyncTask<String, Void, Boolean> {
ProgressBar loadingRL = findViewById(R.id.progressBar);
#Override
protected void onPreExecute() {
super.onPreExecute();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
MP1.setAudioAttributes(attribs);
} else {
MP1.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
loadingRL.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(String... strings) {
try {
MP1.setDataSource(strings[0]);
MP1.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
MP1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer MP1) {
MP1.start();
}
});
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
MusicButton.setVisibility(View.VISIBLE);
MusicButton.setChecked(true);
loadingRL.setVisibility(View.VISIBLE);
}
ActivityOne.java
MediaPlayer MP2;
boolean prepared = false;
boolean started = false;
ToggleButton music;
PlayerTask playerTask = null;
CoordinatorLayout coordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_for_ringtone);
coordinatorLayout = findViewById(R.id.coord);
MP2 = new MediaPlayer();
playerTask = new PlayerTask();
playerTask.execute(url);
}
#SuppressLint("StaticFieldLeak")
public class PlayerTask extends AsyncTask<String, Void, Boolean> {
ProgressBar pb = findViewById(R.id.progress);
#Override
protected void onPreExecute() {
super.onPreExecute();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
MP2.setAudioAttributes(attribs);
} else {
MP2.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
}
#Override
protected Boolean doInBackground(String... strings) {
if (!isCancelled()) {
try {
MP2.setDataSource(strings[0]);
MP2.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
MP2.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer MP2) {
MP2.start();
}
});
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
music.setEnabled(true);
music.setVisibility(View.VISIBLE);
music.setChecked(true);
all.setVisibility(View.VISIBLE);
}
#Override
protected void onCancelled(Boolean aBoolean) {
if (isCancelled() && MP2.isPlaying()) {
MP2.stop();
}
}
}
#Override
public void onBackPressed() {
if (playerTask != null && playerTask.getStatus() == AsyncTask.Status.FINISHED) {
if (MP2.isPlaying()) {
MP2.stop();
}
} else if (playerTask != null && playerTask.getStatus() != AsyncTask.Status.FINISHED) {
playerTask.cancel(true);
}
super.onBackPressed();
}
i spent 2 days to resolve this problem without any result ,please someone help me i will be thankful to him
You could solve this by using Otto library. First create a new Java class but choose enum instead and inside enum you can add: PLAY and PAUSE for example:
public enum PlaybackEvent {
PLAY, PAUSE
}
Then if you are not using custom Application class create one and extend Application and override inside onCreate method. Inside your app gradle add compile 'com.squareup:otto:1.3.8' then create an instance of Bus inside Application class and register. For example this would look like this:
public class MApplication extends Application {
public static Bus sBus = new Bus(ThreadEnforcer.MAIN);
#Override
public void onCreate() {
super.onCreate();
sBus.register(this);
}
Don't forget to replace in manifest default application class with your new one
<application
android:name="com.packagename.MApplication"
After that in your MainActivity class override and register/unregister your event bus in onResume and in onPause.
#Override
protected void onResume() {
super.onResume();
try {
MApplication.sBus.register(this);
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
MApplication.sBus.unregister(this);
}
catch(Exception e){
e.printStackTrace();
}
}
After that in MainActivity create a public void method passing as parameter PlayBackEvent and Subscribe so you can listen a message which will be send from your fragment class. For example:
#Subscribe
public void handlePlaybackEvent(PlaybackEvent event) {
switch (event) {
case PLAY:
if(MP1.isPlaying())
MP1.pause();
break;
case PAUSE:
if(!MP1.isPlaying())
MP1.play();
break;
}
}
And last thing you have to do is to send the message from your fragment when starting second activity and that will go:
MApplication.sBus.post(PlaybackEvent.PAUSE);
and of course you can also send a message to play again MP1 from second activity overriding onBackPressed putting inside line of code:
MApplication.sBus.post(PlaybackEvent.PLAY);
Hope this will help you to resolve the problem.
Have you tried using startActivityForResult()?

Check if we are connected (WIFI/3-4G) - Android Java

I have a splashscreen (for try Internet), if we can't connect, we don't launch app.
So, i have try to found one java class on internet and i have found that :https://stackoverflow.com/a/6987498/5070495
I have adapt the code, but i have an error in
if (SplashScreen.getInstance(this).isOnline()) {
Error :
getInstance(android.content.Context')in 'com.srazzz.package.Splashscreen' cannot be applied to '(anonymous java.lang.thread')
All my class
public class SplashScreen extends Activity {
static Context context;
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo;
boolean connected = false;
private static SplashScreen instance = new SplashScreen();
public static SplashScreen getInstance(Context ctx) {
context = ctx.getApplicationContext();
return instance;
}
public boolean isOnline() {
try {
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
connected = networkInfo != null && networkInfo.isAvailable() &&
networkInfo.isConnected();
return connected;
} catch (Exception e) {
System.out.println("CheckConnectivity Exception: " + e.getMessage());
Log.v("connectivity", e.toString());
}
return connected;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timerThread = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
if (SplashScreen.getInstance(this).isOnline()) {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
} else {
//Toast t = Toast.makeText("test").show();
//Log.v("Home", "############################You are not online!!!!");
Intent i = new Intent(SplashScreen.this, chatonly.class);
startActivity(i);
}
}
}
};
timerThread.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Use like this,
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (isOnline()) {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
} else {
//Toast t = Toast.makeText("test").show();
//Log.v("Home", "############################You are not online!!!!");
Intent i = new Intent(SplashScreen.this, chatonly.class);
startActivity(i);
}
}
}, 3000);
Try writing out fully qualified thread class name as example
new java.lang.Thread(new Runnable() {
public void run() {
if (SplashScreen.getInstance(this).isOnline()) {
//do stuff here} else{
//Don't do stuff} }
}).start();

AsycTask Throwing IllegalStateException - Fragment Not Attached To Activity

I have the following AsyncTask in my Android application. This AsyncTask is contained with within the OnCreate() method of a class that extends PreferenceFragment.
public class NotificationsPreferenceFragment extends PreferenceFragment {
private static Context context;
public NotificationsPreferenceFragment() {
}
public NotificationsPreferenceFragment(Context context) {
this.context = context;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notifications);
getPreferenceManager().findPreference(getString(R.string.send_all_notifications))
.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
class NotificationSendTask extends DialogAsyncTask {
public static final String TAG = "NotificationFragment";
public NotificationSendTask(Activity activity, String dialogMsg) {
super(activity, dialogMsg);
}
#Override
protected String doInBackground(String... params) {
String url = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(getString(R.string.notification_web_service_url), getString(R.string.default_notification_web_service_url));
if (NetworkingHelper.isNetworkAvailable(getActivity())) {
NotificationDao notificationDao = new NotificationDaoImpl(DatabaseManager.getInstance(getActivity().getApplicationContext()), getActivity().getApplicationContext());
List<Notification> unsentNotificationList = notificationDao.findAllNotSent();
if (unsentNotificationList.size() != 0) {
NotificationSenderTask ns = new NotificationSenderTask(url, context);
try {
if (ns.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (unsentNotificationList)).get()) {
return getString(R.string.success);
}
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
} catch (ExecutionException e) {
Log.e(TAG, e.getMessage());
}
return getString(R.string.failed_to_send_notifications);
} else {
return getString(R.string.no_notifications_to_send);
}
} else {
return getString(R.string.no_connection_notifications);
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null && dialog.isShowing()) {
dialog.hide();
}
Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
}
}
NotificationSendTask notificationSendTask = new NotificationSendTask(getActivity(), "Sending unsent notifications...");
notificationSendTask.execute();
return true;
}
});
getPreferenceManager().findPreference(getString(R.string.export_notifications)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
NotificationExportTask notificationExportTask = new NotificationExportTask(NotificationsPreferenceFragment.this.getActivity(), 1);
notificationExportTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return true;
}
});
}
}
I am getting the following exception:
java.lang.IllegalStateException: Fragment NotificationsPreferenceFragment{416092f8} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:741)
at android.app.Fragment.getString(Fragment.java:763)
Can someone please explain to me why this is happening and suggest ways to fix this issue?
UPDATE:
Here is the code for the Activity:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
}
Since you are performing background task in your app. there is no guarantee that user will stay on same screen until task finishes so if user navigates to other screen or presses home button before task is completed; your fragment is detached from activity. So always make sure that you have fragment attached with the Activity.
try checking with
if (isAdded) {
//Do your UI stuff here
}
add above check wherever you get callback
Move your code from onCreate to onActivityCreated instead of trying to getActivity # onCreate.
That's because the fragment can be created when the activity is not yet ready, that's when you are trying to use it.
That is of course if you are adding the fragment to an activity like:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(android.R.id.content, new PreferenceFragment()).commit();

Android application structure: Scheduled Threads

I'm having trouble with my app. What I want is:
MainActivity launches & creates a scheduled thread which periodically checks whether the WiFi service is enabled. If it IS, go to a new activity. If it ISN'T then launch a warning & take the user to the WiFi settings page.
When the user comes back to the Main Activity, the MainActivity code will now sense the WiFi service is enabled & send them to the second activity.
I have this working. Here's the code:
#Override
protected void onResume()
{
super.onResume();
ScheduledExecutorService oScheduledExecutor = Executors.newSingleThreadScheduledExecutor();
try
{
oScheduledExecutor.scheduleAtFixedRate({RUNNABLE HERE}, 0, 5, TimeUnit.SECONDS);
}
catch (Exception e)
{
System.out.println("(MainActivity) Caught Exception here. #1");
System.out.println("(MainActivity) Error: " + e.getMessage() + " Cause: " + e.getCause());
e.printStackTrace();
}
}
#Override
protected void onStart()
{
super.onStart();
// Assign WifiManager to System service
oWiFiManager = (WifiManager) getSystemService(WIFI_SERVICE);
// Create Runnable
oWiFiUpdater = new Runnable() {
#Override
public void run()
{
// If we should show WiFi Disabled
if (shouldShowWiFiAlert())
{
runOnUiThread(new Runnable() {
#Override
public void run() {
launchWiFiDisabledAlert();
}
});
}
Intent oAPListIntent = new Intent(getApplicationContext(), APList.class);
startActivity(oAPListIntent);
}
}
};
However when we are on the second activity, the first thread is still running. I thought that when the Activity is removed from View, all threads cease running??
I want the executor to only run when the Activity is viewable! Any ideas!?
EDIT: Answer thanks to inspiration from njzk2
#Override
protected void onResume()
{
super.onResume();
createWiFiAlertDialog();
boolean bWiFiEnabling = wifiEnabling();
while (bWiFiEnabling)
{
try
{
doSyncedWait(500);
}
catch (Exception e)
{
System.out.println("(MainActivity) Exception caught waiting. " + e.getMessage());
}
bWiFiEnabling = wifiEnabling();
}
boolean bWiFiEnabled = wifiReady();
if (!bWiFiEnabled)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog oAlertDialog = m_oAlertDialog;
oAlertDialog.show();
}
});
}
else
{
Intent oIntent = new Intent(this,APList.class);
startActivity(oIntent);
}
}
private boolean wifiEnabling()
{
WifiManager oWiFiManager = m_oWiFiManager;
if (oWiFiManager == null) return false;
if (oWiFiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) return true;
return false;
}
private boolean wifiReady()
{
WifiManager oWiFiManager = m_oWiFiManager;
if (oWiFiManager == null) return false;
// If the WiFi state is anything other than enabled, then wait.
if (oWiFiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) return true;
return false;
}
If you give your runnable a reference to the activity, and set a boolean to true in onResume() and false in onPause(), you should be able to reference the boolean from your runnable and then use a if statement to only run if the boolean is set to true.

show toast when connectivity changes

I built an app that streams audio using a webview. Now I added a check if there's connectivity (or not). Using toast I show a message with "true" or "false", but I'd like show a toast only when the connectivity changes. What should I do?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
update();
private void update() {
new Thread() {
public void run() {
while (true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
isOnline();
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
Toast.makeText(getApplicationContext(), "true",Toast.LENGTH_LONG).show();
return true;
}
Toast.makeText(getApplicationContext(), "false",Toast.LENGTH_LONG).show();
return false;
Try this :
public class BroadCastSampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
if(currentNetworkInfo.isConnected()){
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show();
}
}
};
}
Add this permission in your Manifest :
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
The ConnectivityManager broadcasts the CONNECTIVITY_ACTION ("android.net.conn.CONNECTIVITY_CHANGE") action whenever the connectivity details have changed. You can register a broadcast receiver in your manifest to listen for these changes and resume (or suspend) your background updates accordingly.
That comes from the android developer information.
You can read more here: http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
That should have everything you need to show the toast notifications.
You should register for android.net.conn.CONNECTIVITY_CHANGE. And show a dialog only on receiving the intent.
You can create an inner class that extends a BroadcastReceiver and shows a toast in it's onReceive method.
That should work :)

Categories

Resources