The splash screen's supposed to work every time I use my app But once I clear the application from task manager and restart it.
The animation doesn't appear and it goes straight to the login screen with no animation occurring.
package com.example.promilek;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
#SuppressLint("CustomSplashScreen")
public class SplashScreen extends AppCompatActivity {
private static final int SPLASH_SCREEN = 2000;
//Variables
Animation topAnim;
ImageView ImageViewButla;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow() .setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash_screen);
topAnim= AnimationUtils.loadAnimation(this, R.anim.top_animation);
ImageViewButla = findViewById(R.id.imageViewButla);
ImageViewButla.setAnimation(topAnim);
new Handler() .postDelayed(() -> {
Intent intent = new Intent(SplashScreen.this, Login.class);
startActivity(intent);
finish();
},SPLASH_SCREEN);
}
}
In my solution, I will use the Thread class to do this. At least this will give you more control in the activity lifecycle methods.
I have also included a SessionManager to help you incase you need it now or later.
Activity with animation
#SuppressLint("CustomSplashScreen")
public class SplashScreen extends AppCompatActivity {
private static final int SPLASH_SCREEN = 2000;
//Variables
Animation topAnim;
ImageView ImageViewButla;
private Thread counterThread;
Context mContext;
private SessionManager sessionManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow() .setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash_screen);
mContext = getApplicationContext(); // Get application context
topAnim = AnimationUtils.loadAnimation(this, R.anim.top_animation);
ImageViewButla = findViewById(R.id.imageViewButla);
ImageViewButla.setAnimation(topAnim);
sessionManager = new SessionManager(mContext); // Initialize Session manager object
// Counter thread
counterThread = new Thread() {
#Override
public void run() {
try {
int wait = 0; // Thread wait time
// Loop
while (wait < SPLASH_SCREEN) {
sleep(100); // Sleep
wait += 100;
}
Intent intent;
if (sessionManager.isSignedIn()) {
// Launch MainActivity
intent = new Intent(SplashActivity.this, MainActivity.class);
} else {
// Launch Signin or SignUp activity
intent = new Intent(SplashActivity.this,
SignInSignUpActivity.class);
}
startActivity(intent); // Start activity
finish(); // Exit Activity
} catch (Exception ignored) {
} finally {
finish(); // Exit Activity
}
}
};
}
}
#Override
public void onBackPressed() {
super.onBackPressed(); // Exit
counterThread.start(); // Start thread
}
#Override
public void onResume() {
super.onResume();
counterThread.start(); // Start thread
}
#Override
protected void onStop() {
super.onStop();
counterThread.interrupt(); // Interrupt thread on activity exit
}
#Override
protected void onDestroy() {
super.onDestroy();
counterThread.interrupt(); // Interrupt thread on activity exit
}
SessionManager class
Below is the code for the session manager
public class SessionManager {
private static final String KEY_IS_SIGNED_IN = "isSignedIn";
private static String PREFERENCE_NAME; // Shared Preference File Name
// Shared Preference
private final SharedPreferences sharedPreferences;
private final SharedPreferences.Editor editor;
// Shared Preference mode
int PRIVATE_MODE = 0;
#SuppressLint("CommitPrefEdits")
public SessionManager(Context context) {
this.sharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, PRIVATE_MODE);
this.editor = sharedPreferences.edit();
PREFERENCE_NAME = context.getResources().getString(R.string.app_name) +
"_SessionManagerPreference";
}
public boolean isSignedIn() {
return sharedPreferences.getBoolean(KEY_IS_SIGNED_IN, false);
}
public void setSignedIn(boolean isLoggedIn) {
editor.putBoolean(KEY_IS_SIGNED_IN, isLoggedIn);
editor.commit(); // Commit Changes
}
}
Related
I have problem with Runnable. It don't want to works, and i don't know what is the problem, because it is works in my other app... Can somebody help me?
Just example, there are "healt" with deafult value=5, for the test i made a button, when i click button, healt value -1... and i want start Runnable when health<5... and add +1 to health.... for the test i setted the Runnable 1 secunds
Here is the code:
MainActivity.java
package com.mygame.test;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import static com.mygame.test.variables.coin;
import static com.mygame.test.variables.health;
public class Main2Activity extends AppCompatActivity {
public static final String PREFS_NAME_MAIN = "mainpref";
TextView coinText, healthText, textView;
Button button3;
private final Context app = this;
private final Handler update = new Handler();
private final Runnable updateHealth = new Runnable()
{
public void run()
{
if (variables.run)
{
healthText.setText(""+health);
update.postDelayed(updateHealth, 500);
}
else if (!variables.run) update.removeCallbacksAndMessages(null);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main2);
coinText = findViewById(R.id.coinText);
healthText = findViewById(R.id.healthText);
healthText.setText(String.valueOf(health));
button3 = findViewById(R.id.button3);
textView = findViewById(R.id.textView);
Button closeButton = findViewById(R.id.closeButton);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//finishAffinity();
startActivity(new Intent(Main2Activity.this, ExitActivity.class));
}
});
Button coinsplusButton = findViewById(R.id.coinsplusButton);
coinsplusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//finishAffinity();
startActivity(new Intent(Main2Activity.this, StoreActivity.class));
}
});
Button level1Button = findViewById(R.id.level1Button);
level1Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//finishAffinity();
startActivity(new Intent(Main2Activity.this, Level1Activity.class));
}
});
}
public void buttontest(View button3)
{
if (health > 0) {
health = health-1;
healthText.setText(""+health);
}
variables.run = true;
Intent activeClick = new Intent(this, ClickService.class);
this.startService(activeClick);
update.post(updateHealth);
save();
}
#Override
protected void onStart()
{
super.onStart();
load();
textupgrade();
if (!variables.run)
{
variables.run = true;
Intent activeClick = new Intent(this, ClickService.class);
this.startService(activeClick);
}
}
protected void onResume()
{
super.onResume();
load();
textupgrade();
update.post(updateHealth);
}
private void load()
{
SharedPreferences varReader = app.getSharedPreferences(PREFS_NAME_MAIN, MODE_PRIVATE);
variables.run = varReader.getBoolean("run", false);
coin = varReader.getInt("coin", 0);
health = varReader.getInt("health", 5);
}
private void save()
{
SharedPreferences.Editor varReader = app.getSharedPreferences(PREFS_NAME_MAIN, 0).edit();
varReader.putBoolean("run", variables.run);
varReader.putInt("coin", coin);
varReader.putInt("health", health);
varReader.apply();
}
private void textupgrade(){
coinText.setText(""+coin);
healthText.setText(""+health);
}
}
ClickService.java
package com.mygame.test;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
public class ClickService extends IntentService
{
private final Handler handler = new Handler();
private final Runnable addHealth = new Runnable()
{
public void run()
{
variables.health++;
if (!variables.run) handler.removeCallbacksAndMessages(null);
else if (variables.run) handler.postDelayed(addHealth, 1000);
}
};
public ClickService()
{
super("ClickService");
}
#Override
protected void onHandleIntent(Intent activeClick)
{
handler.postDelayed(addHealth, 500);
}
}
variables.java
package com.mygame.test;
public class variables {
static int coin;
static int health;
static boolean run;
}
Oh, i fixed it :D ClickService was not registered in AndroidManifest
<service
android:name=".ClickService"
android:exported="false" />
Upon starting my game, the game does not utilise the entire android screen. This only happens with the game itself, shown by the image as the user is unable to reach the bottom of the screen. Have tried to find a solution however all attempts I have tried seems not to work. Unsure which code to supply, and therefore do not want to provide a large amount of code. Let me know which code to post. Any help would be appreciated.
Image of game
package com.example.spaceattack;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity
{
private SpaceShipView gameView;
private Handler handler = new Handler();
private final static long Interval = 30;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new SpaceShipView(this);
setContentView(gameView);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run()
{
handler.post(new Runnable() {
#Override
public void run()
{
gameView.invalidate();
}
});
}
}, 0, Interval);
}
}
You need to hide the status/system by getting the window of your app and set below flags:
More from Documentation
// hide status bar
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
So in your code:
public class MainActivity extends AppCompatActivity
{
private SpaceShipView gameView;
private Handler handler = new Handler();
private final static long Interval = 30;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new SpaceShipView(this);
setContentView(gameView);
// hide status bar
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mUiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
getWindow().getDecorView().setSystemUiVisibility(mUiOptions);
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run()
{
handler.post(new Runnable() {
#Override
public void run()
{
gameView.invalidate();
}
});
}
}, 0, Interval);
}
}
I have an activity named Player Activity in which I am streaming music with the help of MediaPlayer API. Whenever my activity is created a notification is displayed which has some basic control of the music player.
So when I tap on my notification it jumps back to the Player Activity, but the state of the activity is lost.
Before tapping on notification :
After tapping on notification :
Here is the code of my notification's Pending Intent
Intent notifyIntent = new Intent(context, PlayerActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
notifyIntent.setAction("android.intent.action.MAIN");
notifyIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Here is the code for PlayerActivity.java :
package com.example.user.musicplayer;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.concurrent.TimeUnit;
import de.hdodenhof.circleimageview.CircleImageView;
public class PlayerActivity extends AppCompatActivity implements MediaPlayer.OnBufferingUpdateListener,MediaPlayer.OnCompletionListener{
private static Button btn_play_pause;
private Button btnToggleRepeat;
private Button btnStop;
private SeekBar seekBar;
private TextView textView;
public static MediaPlayer mediaPlayer;
private int mediaFileLength;
private int realtimeLength;
private String musicUrl;
private String imageUrl;
final Handler handler = new Handler();
private boolean isRepeat;
private CircleImageView musicImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Log.d("TAG", "onCreate");
NotificationGenerator.customBigNotification(getApplicationContext());
musicUrl = getIntent().getStringExtra("musicUrl");
imageUrl = getIntent().getStringExtra("imageUrl");
seekBar = (SeekBar)findViewById(R.id.seekbar);
seekBar.setMax(99); // 100% (0~99)
seekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(mediaPlayer.isPlaying())
{
SeekBar seekBar = (SeekBar)v;
int playPosition = (mediaFileLength/100)*seekBar.getProgress();
mediaPlayer.seekTo(playPosition);
}
return false;
}
});
textView = (TextView)findViewById(R.id.txtTime);
btnToggleRepeat = findViewById(R.id.btnRepeat);
btnStop = findViewById(R.id.btnStop);
musicImage = findViewById(R.id.musicImgView);
Picasso.get().load(imageUrl).placeholder(R.drawable.music).error(R.drawable.music).into(musicImage);
btn_play_pause = (Button) findViewById(R.id.btnTogglePlay);
btn_play_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog mDialog = new ProgressDialog(PlayerActivity.this);
AsyncTask<String,String,String> mp3Play = new AsyncTask<String, String, String>() {
#Override
protected void onPreExecute() {
mDialog.setMessage("Please wait");
mDialog.show();
}
#Override
protected String doInBackground(String... params) {
try{
mediaPlayer.setDataSource(params[0]);
mediaPlayer.prepare();
}
catch (Exception ex)
{
}
return "";
}
#Override
protected void onPostExecute(String s) {
mediaFileLength = mediaPlayer.getDuration();
realtimeLength = mediaFileLength;
if(!mediaPlayer.isPlaying())
{
playMusic();
}
else
{
pauseMusic();
}
updateSeekBar();
mDialog.dismiss();
}
};
mp3Play.execute(musicUrl); // direct link mp3 file
}
});
btnToggleRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isRepeat){
isRepeat = false;
mediaPlayer.setLooping(false);
btnToggleRepeat.setText("Repeat");
}
else{
isRepeat = true;
mediaPlayer.setLooping(true);
btnToggleRepeat.setText("Single");
}
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.pause();
mediaPlayer.stop();
}
catch (Exception e){
Toast.makeText(PlayerActivity.this, "Opps! sorry something bad happened", Toast.LENGTH_SHORT).show();
}
}
});
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
public void pauseMusic() {
mediaPlayer.pause();
btn_play_pause.setText("Play");
}
public void playMusic() {
mediaPlayer.start();
btn_play_pause.setText("Pause");
}
private void updateSeekBar() {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / mediaFileLength)*100));
if(mediaPlayer.isPlaying())
{
Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
realtimeLength-=1000; // declare 1 second
textView.setText(String.format("%d:%d",TimeUnit.MILLISECONDS.toMinutes(realtimeLength),
TimeUnit.MILLISECONDS.toSeconds(realtimeLength) -
TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(realtimeLength))));
}
};
handler.postDelayed(updater,1000); // 1 second
}
}
#Override
protected void onResume() {
super.onResume();
Log.d("TAG", "onResume");
}
#Override
protected void onStart() {
super.onStart();
Log.d("TAG", "onStart");
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
if(!mediaPlayer.isLooping())
btn_play_pause.setText("Play");
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onPause() {
super.onPause();
}
public static class DownloadCancelReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("notificationPlayer","Received Cancelled Event");
}
}
}
Thanks in advance. Pardon me if the explanation is not clear, because if i might have right words to explain it, I would have googled it.
Add this to your PlayerActivity activity in manifest :
android:launchMode="singleTask"
And use these flags in the intent for pendingintent :
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
I believe I have my code set up correctly but when I try to debug it, after it transitions from the splash screen it just goes right to a black screen. I know I imported the layout correctly but it still goes black.
This is the code for the splash screen
package com.example.equate.jones;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class EJ_Splash extends Activity {
protected boolean _active = true;
protected int _splashTime = 3000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ej__splash);
// thread for displaying the SplashScreen
Thread splashTread = new Thread() {
#Override
public void run() {
try {
synchronized(this){
wait(4000);
}
}
catch(InterruptedException e) {
// do nothing
} {
finish();
Intent i = new Intent(getApplicationContext(),EJ_Board.class);
startActivity(i);
}
}
};
splashTread.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_ej__splash, menu);
return true;
}
}
This is the code for the screen it is supposed to transition to.
package com.example.equate.jones;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class EJ_Board extends Activity {
private ImageView button1;
final MediaPlayer mp = MediaPlayer.create(this, R.raw.warm);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ej_board);
button1=(ImageView)findViewById(R.id.imageView1);
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
mp.start();
}
});
}
}
This is the xml for EJ_Board
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</LinearLayout>
I think your problem is with the ImageView. You need to add an image to your drawable folder, then change your android:src="#drawable/ic_launcher" to the name of the image you saved. This will give you the image you need for your button. Hope that helps
Edit:
For your splash screen, try something like this:
public class SplashActivity extends Activity {
private long splashDelay = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
TimerTask task = new TimerTask()
{
#Override
public void run() {
finish();
Intent homeIntent = new Intent().setClass(SplashActivity.this, HomeActivity.class);
startActivity(homeIntent);
}
};
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}
Then in your home activity you can set your menu:
public class HomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.locationButton:
Intent locationIntent = new Intent(this, LocationActivity.class);
startActivity(locationIntent);
return true;
case R.id.diningButton:
Intent diningIntent = new Intent(this, DiningActivity.class);
startActivity(diningIntent);
return true;
case R.id.topXXVButton:
Intent topIntent = new Intent(this, DiningActivity.class);
startActivity(topIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Try this:
public class SplashActivity extends Activity {
private long splashDelay = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
TimerTask task = new TimerTask()
{
#Override
public void run() {
finish();
Intent mainIntent = new Intent().setClass(EJ_Splash.this, EJ_Board.class);
startActivity(mainIntent);
}
};
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}
I have the following three classes:
When I try to show a progressDialog when the WorkingThread is running, the ProgressDialog only shows up after the WorkingThread is done. What am I doing wrong?
I am not interested in using an AsyncTask!
-StartActivity:
public class StartActivity extends Activity implements OnClickListener
{
public ProgressDialog pgd;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgv = (ImageView)findViewById(R.id.imageView1);
tv = (TextView)findViewById(R.id.textview);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(this);
}
public void onClick(View v)
{
pgd = ProgressDialog.show(StartActivity.this, "", "Loading picture"); // Start ProgressDialog before starting activity
Intent ActivityIntent = new Intent(this, FirstActivity.class);
startActivityForResult(ActivityIntent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK)
{
pgd.dismiss(); //Stop ProgressDialog when FirstActivity is "done"
}
}
}
-
-FirstActivity:
public class FirstActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
WorkingThread wt = new WorkingThread();
wt.start();
try
{
wt.join();
Intent ActivityIntent = getIntent();
setResult(RESULT_OK, ActivityIntent);
finish();
}
catch (Exception e)
{
}
}
}
-WorkingThread:
public class WorkingThread extends Thread
{
#Override
public void run()
{
super.run();
try
{
Thread.sleep(5000);
}
catch (Exception e)
{
}
}
}
The problem is ProgressDialog always need current Activity context for display.But in your case ProgressDialog is little unfortunate
The reason is as soon as you fire ProgressDialog the next couple of lines take out Context from Current activity and starts Next Activity i.e FirstActivity.So your progressDialog gets no chance to present itself on the Screen.
Use an AsyncTask. Here's an example:
package com.example.test;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
ProgressDialog activityProgressDialog;
private Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
new TestAsyncTask().execute();
}
});
}
private class TestAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
//Called before doInBackground.
//Initialize your progressDialog here.
activityProgressDialog = ProgressDialog.show(context,
"Test",
"Doing heavy work on background...", false,
false);
}
#Override
protected Void doInBackground(Void... v) {
//Do your work here
//Important!!! Update any UI element on preExcecute and
//onPostExcecute not in this method or else you will get an
//exception.
//The below code just make the thread inactive for 5 seconds.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().notify();
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void v) {
//Dismiss the progessDialog here.
activityProgressDialog.dismiss();
}
}
}
I just show your edit that you don't want to use an AsyncTask. I will not delete this answer (unless you want me to) since it is another way of doing what you wanted to do.
try
{
wt.join();
Intent ActivityIntent = getIntent();
setResult(RESULT_OK, ActivityIntent);
finish();
}
here is your problem. The UI thread is waiting the Working Thread to finish becaouse of the join().