Screen doesnt show before onResume - android

I am trying to show a waiting screen in my app while it's trying to connect my server. For some reason, the screen shows only in the middle of the while loop and sometimes even after the while loop has done its work. Also, even after the while loop gets to its end the code after it doesn't executed (it doesn't print the values). Does anyone know how to fix it?
This is the code:
public class LoadingActivity extends AppCompatActivity {
public static final long SEC_IN_MS = 1000;
public static final int CONNECT_LOOP_TIME = 5; //In seconds
DataSender dataSender = new DataSender();
DataCenter dataCenter = DataCenter.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading);
dataSender.execute();
dataCenter.connect();
}
#Override
protected void onResume() {
super.onResume();
moveToMenu();
}
public void moveToMenu() {
long loopStartTime = System.currentTimeMillis();
boolean didConnect = false;
while(!didConnect &&
System.currentTimeMillis()-loopStartTime <= SEC_IN_MS*CONNECT_LOOP_TIME) {
//Wait until connected or 5 seconds pass
System.out.println(System.currentTimeMillis()-loopStartTime);
if(dataCenter.getRespond().equals(dataCenter.okMsg())) {
didConnect = true;
}
}
System.out.println("111111111111111111");
System.out.println(didConnect);
if(didConnect) {
Intent nextIntent = new Intent(this, MenuActivity.class);
startActivity(nextIntent);
}
else {
System.out.println("OOPS");
}
}
}

Related

Overlap of time IntentService

I have little problem with overlap of time in ProgressBar. I have list card. When click this item show activity with display detail Card show progress bar with counts down the time. When time is over, Counts again. When add next Card and click this card show time previous Card. I don't idea why new Card
has the same time as old Card.
ProgressBarService.class
public class ProgressBarService extends IntentService {
private int interval;
public static final String KEY_EXTRA_PROGRESS = "progress";
public ProgressBarService() {
super(ProgressBarService.class.getSimpleName());
}
#Override
protected void onHandleIntent(Intent intent) {
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ProgressBarService.KEY_EXTRA_PROGRESS);
if (intent != null) {
interval = intent.getIntExtra("interval", 0);
for (int i = interval; i >= 0; i--) {
broadcastIntent.putExtra("progress", i);
sendBroadcast(broadcastIntent);
SystemClock.sleep(1000);
}
}
}
}
CardDeatlisActitvty.class
public class CardDetailsActivity extends AppCompatActivity {
private Intent service;
private ResponseReceiver receiver = new ResponseReceiver();
private ProgressBar progressBar;
private TextView secondTimeTextView;
private int interval;
public class ResponseReceiver extends BroadcastReceiver {
// on broadcast received
#Override
public void onReceive(Context context, Intent intent) {
// Check action name.
if (intent.getAction().equals(ProgressBarService.KEY_EXTRA_PROGRESS)) {
int value = intent.getIntExtra("progress", 0);
new ShowProgressBarTask().execute(value);
}
}
}
class ShowProgressBarTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected Integer doInBackground(Integer... args) {
return args[0];
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
progressBar.setProgress(result);
secondTimeTextView.setText(" " + result + " ");
if (result == 0) {
service = new Intent(CardDetailsActivity.this, ProgressBarService.class);
service.putExtra("interval", interval);
startService(service);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
setContentView(R.layout.activity_card_details);
Bundle extras = getIntent().getExtras();
if (extras != null) {
intervalTotpEncrypt = extras.getString("intervalTotp");
}
interval = Integer.parseInt(intervalTotpDecrypt);
progressBar.setMax(interval);
progressBar.setProgress(interval);
service = new Intent(this, ProgressBarService.class);
service.putExtra("interval", interval);
startService(service);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(
ProgressBarService.KEY_EXTRA_PROGRESS));
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
Your ProgressBarService doesn't know that the "Card" CardDetailsActivity was changed. If for (int i = interval; i >= 0; i--) {...} loop doesn't run out and if (result == 0) { } is not true then it will behave as you described becouse ProgressBarService counter still counts.
#Override
protected void onPause() {
// notify ProgressBarService that the card will be changed (reset the counter)
}
Mind that when you call CardDetailsActivity for the second time (next card) onCreate() could be not called.

Handler doesn't work correctly

first of all excuse me if my title doesn't describe my question very well but i couldn't find a better one .
there is a simple stopWatch app that has three button start,stop,reset and a textview to display time . app has just one activity like this:
public class StopwatchActivity extends AppCompatActivity {
private int mNumberOfSeconds = 0;
private boolean mRunning = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
//if if uncomment this runner method and delete the runner inside onClickStart everything will work find
//runner()
}
public void onClickStart(View view){
mRunning = true;
runner();
}
public void onClickStop(View view){
mRunning = false;
}
public void onClickReset(View view){
mRunning = false;
mNumberOfSeconds = 0;
}
public void runner(){
final TextView timeView = (TextView) findViewById(R.id.time_view);
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
int hours = mNumberOfSeconds/3600;
int minutes = (mNumberOfSeconds%3600)/60;
int second = mNumberOfSeconds%60;
String time = String.format("%d:%02d:%02d" , hours , minutes , second );
timeView.setText(time);
if (mRunning){
mNumberOfSeconds++;
}
handler.postDelayed(this , 1000);
}
});
}
}
my problem is when i comment the runner() in onClickStart method and put it in the onCreate method everything is ok . but when i change the code like above the code is still running but after i press stop button and then press start again the second will increment by 4 or 5 very fast.
can anyone explain me what is the difference between this two modes?
declare your handler globally
public void runner(){
timeView = (TextView) findViewById(R.id.time_view);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
int hours = mNumberOfSeconds/3600;
int minutes = (mNumberOfSeconds%3600)/60;
int second = mNumberOfSeconds%60;
String time = String.format("%d:%02d:%02d" , hours , minutes , second );
timeView.setText(time);
if (mRunning){
mNumberOfSeconds++;
}
handler.postDelayed(this , 1000);
}
}
handler.post(runnable);
}
in button function
public void onClickStart(View view){
if(handler != null) {
//restart the handler to avoid duplicate runnable
handler.removeCallbacks(runnable);//or this handler.removeCallbacksAndMessages(null);
}
mRunning = true;
runner();
}
public void onClickStop(View view){
mRunning = false;
handler.removeCallbacks(runnable); // this will stop the handler from working
}

App returns to home screen, when add is displayed using TimerTask()

It's my first app to create , I new to android ,
I am designing an app that displays the Advertisement Screen, every 1 minutes when user opens the app ,
The Advertisement Screen works perfectly as expected ,but the problem is when the Advertisement Screen get exit , the app gets returned to the home screen no matter where the user was currently in the Activity Screen
The app flow
SplashScreen.java --> AdSplash --> DiamondWorldMenus ( Home screen )
DiamondWorldMenus .java
public class DiamondWorldMenus extends TabActivity implements OnClickListener {
on Create(.......){
public void startAdSplashForEvery1Minutes(){
//starting AdSplashTimer.java every 5 minutes
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent viewTargetActivity = new Intent(getBaseContext(), AdSplash.class);
startActivity(viewTargetActivity);
}
});
}
},60000, 60000);
}
}
}
AdSplash.java
public class AdSplash extends Activity
{
protected boolean _active = true;
protected int _splashTime = 8000;
WebView ad;
WebSettings web_settings;
WebViewClient yourWebClient;
#Override
public void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.ad_splash);
String url = "http://some_add_link.aspx";
yourWebClient = new WebViewClient();
ad=(WebView)findViewById(R.id.ad_web);
ad.getSettings().setJavaScriptEnabled(true);
ad.getSettings().setSupportZoom(true);
ad.getSettings().setBuiltInZoomControls(true);
ad.setWebViewClient(yourWebClient);
ad.loadUrl(url);
Thread splashTread = new Thread()
{
#Override
public void run()
{
try
{
int waited = 0;
while(_active && (waited < _splashTime))
{
sleep(100);
if(_active)
waited += 100;
}
}
catch(InterruptedException e)
{}
finally
{
finish();
Intent in1 = new Intent(AdSplash.this,DiamondWorldMenus.class);
startActivity(in1);
}
}
};
splashTread.start();
}
}

how can i load 2 activities, show the first and after faw seconds the second? [duplicate]

This question already has answers here:
Splash screen while loading a url in a webview in android app
(3 answers)
Closed 9 years ago.
I want to load a website (in WebView), but it loads too slow and show a white screen. I want to show a splash screen and in the background load the WebView. After few seconds I want to close the splash screen and show the site that should be ready by then. How can I do it?
Thanks!
I use this code for a splash screen
public class SplashActivity extends Activity {
private boolean isBackButtonPressed;
private static final int SPLASH_DURATION = 2000; // 2 seconds
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.SplashTheme);
getWindow().setWindowAnimations(0);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);
Handler handler = new Handler();
// run a thread after 2 seconds to start the home screen
handler.postDelayed(new Runnable() {
#Override
public void run() {
// make sure we close the splash screen so the user won't come
// back when it presses back key
finish();
if (!isBackButtonPressed) {
// start the home screen if the back button wasn't pressed
Intent intent = new Intent(SplashActivity.this, FragmentActivity.class);
startActivity(intent);
finish();
}
}
}, SPLASH_DURATION);
}
#Override
public void onBackPressed() {
super.onBackPressed();
isBackButtonPressed = true;
}
}
You can use the following code for it.
public class Splash extends Activity {
/** Called when the activity is first created. */
private boolean mSplashActive = true, mPaused;
private long mSplashTime = 1000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new Thread(){
public void run(){
try {
long ms = 0;
while(mSplashActive && ms < mSplashTime) {
sleep(100);
if(!mPaused) {
ms += 100;
}
}
if(Resources.getResources().isUserRegistered(Splash.this)) {
//user is registered so launch main screen
} else {
//user is not registered launch welcome wizard.
Intent intent = new Intent(Splash.this, WelcomeScreen.class);
Splash.this.startActivity(intent);
}
finish();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
#Override
public void onPause(){
super.onPause();
mPaused = true;
}
#Override
public void onResume(){
super.onResume();
mPaused = false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
mSplashActive = false;
}
return true;
}
}
in the webview class you can set something like this.
i setup this for you:
public class WebViewActivity extends Activity {
WebView webView;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
progressDialog = new ProgressDialog(WebViewActivity.this);
progressDialog.setTitle("here your title");
progressDialog.setMessage("message here");
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
// here you can display an imageview fullscreen
// or show and progressdialog
progressDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
// here you can remove the imageview and the user can continue using the webview
// or hide the progressdialog
progressDialog.dismiss();
}
});
}
}
if you have any questions let me know
public class SplashScreen extends Activity {
private Thread mSplashThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash);
final SplashScreen sPlashScreen = this;
// The thread to wait for splash screen events
mSplashThread = new Thread() {
#SuppressWarnings("deprecation")
#Override
public void run() {
try {
synchronized (this) {
// Wait given period of time or exit on touch
wait(5000);
}
} catch (InterruptedException ex) {
}
finish();
// Run next activity
Intent intent = new Intent();
intent.setClass(sPlashScreen, MainActivity.class);
startActivity(intent);
}
};
mSplashThread.start();
}
/**
* Processes splash screen touch events
*/
#Override
public boolean onTouchEvent(MotionEvent evt) {
if (evt.getAction() == MotionEvent.ACTION_DOWN) {
synchronized (mSplashThread) {
mSplashThread.notifyAll();
}
}
return true;
}
}

Android: Splash screen problem

I created a splash screen using the follow code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.splash_layout);
Thread splashThread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
while (_active && (waited < _splashTime)) {
sleep(100);
if (_active) {
waited += 100;
}
}
} catch (InterruptedException e) {
// do nothing
} finally {
_active = false;
finish();
startActivity(new Intent(SplashActivity.this, MyMainActivity.class));
}
}
};
splashThread.start();
}
there is an image view in splash_layout, after the splash screen appears for some time duration, and disappears then MyMainActivity starts, the problem is, after the splash disappears and before MyMainActivity starts, I could see previous screen(irrelevant to my app, e.g. desktop with widgets, or previous running app), how to make the transition fluent so that splash screen directly goes to MyMainActivity?
Thanks!
Can you try this i am not sure this is 100% work but try may be helpful..
protected int _splashTime = 3000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finish();
startActivity(new Intent(SplashActivity.this, MyMainActivity.class));
}
}, _splashTime);
}
Try calling finish() after startActivity().
private static final long SPLASH_SCREEN_MS = 2500;
private long mTimeBeforeDelay;
private Handler mSplashHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
// Create a new Handler.
mSplashHandler = new Handler();
}
#Override
protected void onResume() {
super.onResume();
// The first time mTimeBeforeDelay will be 0.
long gapTime = System.currentTimeMillis() - mTimeBeforeDelay;
if (gapTime > SPLASH_SCREEN_MS) {
gapTime = SPLASH_SCREEN_MS;
}
mSplashHandler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
SplashScreenActivity.this.finish();
}
}, gapTime);
// Save the time before the delay.
mTimeBeforeDelay = System.currentTimeMillis();
}
#Override
protected void onPause() {
super.onPause();
mSplashHandler.removeCallbacksAndMessages(null);
}
For your reference, here is a best example for Android - Splash Screen example.
You can try this code:1
public class MainActivity extends Activity {
private ImageView splashImageView;
boolean splashloading = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
splashImageView = new ImageView(this);
splashImageView.setScaleType(ScaleType.FIT_XY);
splashImageView.setImageResource(R.drawable.ic_launcher);
setContentView(splashImageView);
// interesting music
/**
* Gets your sound file from res/raw
*/
splashloading = true;
Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
splashloading = false;
setContentView(R.layout.activity_main);
}
}, 3000);
}
Best of luck!

Categories

Resources