how to wake a thread from sleep in android - android

I have an activity thats waiting for the user press on an image. if the user dont press anything in 3 second i want the activity to close (finish()).
thats my code:
private final int delay = 3000;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.after_hangup);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
final ImageView pressToLaunchbrowser = (ImageView) findViewById(R.id.after_hang_up_image);
pressToLaunchbrowser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); // if we want to open the device.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
Thread.interrupted();
}
});
new Thread() {
public void run() {
try {
Thread.sleep(delay);
finish();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}}
My question is how can i wake the Thread if the press was made? i tried Thread.interrupted(); but its not working. the thread still waits 3 seconds if i press or not. Thanks!

Threads are not recommended to use in Android..use Handler to manage time-dependant operations..for example, instead of new Thread().., try
Handler handler = new Handler();
handler.postDelayed('runnable-that-will-finish-activity', 3000);
and in onclicklistener:
handler.remove('runnable-that-will-finish-activity') ;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
public class NewActivity extends Activity {
private final int delay = 3000;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.after_hangup);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
final ImageView pressToLaunchbrowser = (ImageView) findViewById(R.id.after_hang_up_image);
final Handler handler = new Handler();
handler.postDelayed(finishRunnable, delay);
pressToLaunchbrowser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
// // if we want to open the device.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
handler.removeCallbacks(finishRunnable);
}
});
}
private Runnable finishRunnable = new Runnable() {
#Override
public void run() {
finish();
}
};
}

Related

Android Studio Splash screen is looping indefinitely and will not stop

I'm really new to coding and have almost no idea what I'm doing.
I need to get this splash screen to work but it keeps looping infinitely back between the splash screen and mainactivity and I have no idea why, I took the code off some YouTube video and the video had no explanation too so I'm stuck.
This is the code for mainactivity:
package sg.edu.tp.project1;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 1000;
private ImageButton Search01;
private ImageButton Mymusic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Search01 = (ImageButton) findViewById(R.id.Search);
Mymusic = (ImageButton) findViewById(R.id.Mymusic);
}
{ new Handler().postDelayed(new Runnable(){
#Override
public void run() {
Intent homeIntent = new Intent(MainActivity.this,
HomeActivity.class);
startActivity(homeIntent);
finish();
}
},SPLASH_TIME_OUT);
}
public void gotoSearchpage(View view){
Intent intent = new Intent(this, searchpage.class);
this.startActivity ( intent );
}
public void gotoMymusic(View view){
Intent intent = new Intent(this, myMusic.class);
this.startActivity ( intent );
}
public void gotoPlaylist(View view){
Intent intent = new Intent(this, playlist.class);
this.startActivity ( intent );
} }
and this is the code for the splash screen:
package sg.edu.tp.project1;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class HomeActivity extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
{ new Handler().postDelayed(new Runnable(){
#Override
public void run() {
Intent homeIntent = new Intent(HomeActivity.this,
MainActivity.class);
startActivity(homeIntent);
finish();
}
},SPLASH_TIME_OUT);
}
}
First of all... use AsyncTask in Splash screen it is best practice to do background initialization and checks.
Second you don't need handler in MainActivity.
remove this code from MainActivity... it is redirecting u to HomeActivity.
{ new Handler().postDelayed(new Runnable(){
#Override
public void run() {
Intent homeIntent = new Intent(MainActivity.this,
HomeActivity.class);
startActivity(homeIntent);
finish();
}
},SPLASH_TIME_OUT);
and change your HomeActivity(Splash) like this..
public class HomeActivity extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
new Loader().execute();
}
private class Loader extends AsyncTask<Void,Void, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
Thread.sleep(SPLASH_TIME_OUT);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//if(pd!=null) pd.dismiss();
Intent intent = new Intent(HomeActivity.this,MainActivity.class);
startActivity(intent);
HomeActivity.this.finish();
}
}
}

splashscreen next activity not opening

I am very new to Android, I am developing an application. I want to run the splash screen, but somewhere wrong in my code, the splash screen is just opening and staying at the same page, but it is not opening the next activity, please anyone help me. My main aim is, "For a new user, it should first open the splash screen with Setpassword.java Activity (and the password should store in sharedpreference), but when a user sets password and closes the app and when he reopens, it should open the splashscreen with directly enterpassword.java Activity,i.e skipping setpassword. Java activity:
package com.example.shiva.secretbook;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.logging.Handler;
/**
* Created by shiva on 8/12/2017.
*/
public class SplashScreenActivity extends Activity {
String password;
ImageView imageViewSplash;
TextView txtAppName;
RelativeLayout relativeLayout;
Thread SplashThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
// load password
SharedPreferences settings = getSharedPreferences("PREFS", 0);
password = settings.getString("password", "");
imageViewSplash = (ImageView) findViewById(R.id.imageViewSplash);
txtAppName = (TextView) findViewById(R.id.txtAppName);
relativeLayout = (RelativeLayout) findViewById(R.id.relative);
startAnimations();
}
private void startAnimations(){
Animation rotate = AnimationUtils.loadAnimation(this,R.anim.rotate);
Animation translate = AnimationUtils.loadAnimation(this,
R.anim.translate);
rotate.reset();
translate.reset();
relativeLayout.clearAnimation();
imageViewSplash.startAnimation(rotate);
txtAppName.startAnimation(translate);
SplashThread = new Thread(){
#Override
public void run() {
super.run();
int waited = 0;
while (waited < 3500) {
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
waited += 100;
}
if (password.equals("")){
// if there is no password
SplashScreenActivity.this.finish();
Intent intent = new
Intent(SplashScreenActivity.this,setpassword.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
} else {
//if there is a password
Intent intent = new
Intent(SplashScreenActivity.this,enterpassword.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
} SplashThread.start();
}
};
}}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (password.equals(""))
{
// if there is no password
Intent intent = new Intent(SplashScreenActivity.this,setpassword.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
} else
{
//if there is a password
Intent intent = new Intent(SplashScreenActivity.this,enterpassword.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
}
}
}, 3500);
Try Below Code
public void StartAnimation(){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (password.equals("")){
// if there is no password
SplashScreenActivity.this.finish();
Intent intent = new
Intent(SplashScreenActivity.this,setpassword.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
} else {
//if there is a password
Intent intent = new
Intent(SplashScreenActivity.this,enterpassword.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
}
}
}, 5000);
}
try this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new SplashEnvironment(this, this));
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (password.equals("")){
// if there is no password
SplashScreenActivity.this.finish();
Intent intent = new
Intent(SplashScreenActivity.this,setpassword.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
} else {
//if there is a password
Intent intent = new
Intent(SplashScreenActivity.this,enterpassword.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
}
// close this activity
}
}, 3000);// time for spalsh screen
You started your thread(SplashThread.start();) inside thread creation.
Due to this your thread unable to start.So just put this line on proper place I.e.
SplashThread = new Thread() {
};
SplashThread.start();
Try below code
package com.wikitude.samples;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* Created by shiva on 8/12/2017.
*/
public class SplashScreenActivity extends Activity {
String password;
ImageView imageViewSplash;
TextView txtAppName;
RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
// load password
SharedPreferences settings = getSharedPreferences("PREFS", 0);
password = settings.getString("password", "");
imageViewSplash = (ImageView) findViewById(R.id.imageViewSplash);
txtAppName = (TextView) findViewById(R.id.txtAppName);
relativeLayout = (RelativeLayout) findViewById(R.id.relative);
startAnimations();
}
private void startAnimations() {
Animation rotate = AnimationUtils.loadAnimation(this, R.anim.rotate);
Animation translate = AnimationUtils.loadAnimation(this,R.anim.translate);
rotate.reset();
translate.reset();
relativeLayout.clearAnimation();
imageViewSplash.startAnimation(rotate);
txtAppName.startAnimation(translate);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
runOnUiThread(launchNextScreen);
}
}, 3500);
}
public Runnable launchNextScreen = new Runnable() {
#Override
public void run() {
if (password.equals("")) {
// if there is no password
SplashScreenActivity.this.finish();
Intent intent = new Intent(SplashScreenActivity.this, setpassword.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
} else {
//if there is a password
Intent intent = new Intent(SplashScreenActivity.this, enterpassword.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
}
}
};
}

Splash screen Android App has stopped

I want to make a splash screen for my android app. I have written following codes in welcomescreen.java in android studio. But after running the app, the app has stopped. :( What shall I Do now?
package com.mateors.welcomescreen;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class WelcomeScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_screen);
Thread myThread = new Thread(){
#Override
public void run() {
try {
sleep(5000);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
myThread.start();
}
}
private static int SPLASH_TIME_OUT = 1500;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(WelcomeScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
try the above code snippet
Try with following code:
package com.mateors.welcomescreen;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class WelcomeScreen extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 5000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_screen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(WelcomeScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}

Delay after the splash screen

My problem is, if I set my splash as a Dialog by adding this line in the manifest there's a delay: android:theme="#android:style/Theme.Holo.Dialog.NoActionBar"
After the splash screen disappears it takes around 6 seconds or more to the main activity to appear.
How can I make this delay disappear?
Splash code:
public class SplashActivity extends Activity {
private final int DURATION = 3000;
private Thread mSplashThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mSplashThread = new Thread() {
#Override
public void run() {
synchronized (this) {
try {
wait(DURATION);
} catch (InterruptedException e) {
} finally {
finish();
Intent intent = new Intent(getBaseContext(),
MainActivity.class);
startActivity(intent);
}
}
}
};
mSplashThread.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
synchronized (mSplashThread) {
mSplashThread.notify();
}
}
return true;
}
}
Rather than using splash as dialogue you can do all your background work in a splash screen activity and then start your main activity..if you need dialogue animation then you can use animation like this.
overridePendingTransition( R.anim.come_up, R.anim.go_down );
By this you can manage your activity switching time.
i am not sure that this answer is appropriate but i have done it like this :
#Override
public void run()
{
// TODO Auto-generated method stub
startActivity( new Intent ( SplashActivity.this , MainActivity.class ) ) ;
}
#Override
protected void onStart()
{
super.onStart();
if(!isClosed)
splashHandler.postDelayed(this, "putYourTimeHere");
}
This is working for me at its best..
final int splashTimeOut = 3000;
Thread splashThread = new Thread(){
int wait = 0;
#Override
public void run() {
try {
super.run();
while(wait < splashTimeOut){
sleep(100);
wait += 100;
}
} catch (Exception e) {
}finally{
startActivity(new Intent(SplashScreen.this,LoginActivity.class));
finish();
}
}
};
splashThread.start();
this is the code for splashscreen display with some time delay
..
here set splash image in drawable in splash_screen.xml.
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
public class SplashScreen extends Activity {
LocationManager locationManager;
String provider, formattedDate, imeid;
double lat, lon;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_screen);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formattedDate = df.format(c.getTime());
new Handler().postDelayed(new Runnable() {
public void run() {
Log.i("JO", "run");
Intent in = new Intent(SplashScreen.this,SecondActivity.class);
//in.putExtra("refreshclick", clickRefreshButton);
//in.putExtra("Current_Date", formattedDate);
// in.putExtra("ImeiId", imeid);
//Log.i("JO", "Current_Date"+formattedDate+";
ImeiId"+imeid+";lat"+lat+"lon"+lon);
startActivity(in);
finish();
}
}, 1000);
}
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}, DURATION);
}

Showing ProgressDialog while a Service is being started

I'm having serious problems when showing a ProgressDialog while a service is getting ready... The service takes time to get ready as it's a bit heavy, so I want to show the ProgressDialog meanwhile it's started.
The thing is that it shows the ProgressDialog right before the next activity starts... I really don't find what it is...
package org.pfc;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class ConnectActivity extends Activity {
// FIELDS------------------------------------------------------------------
protected LocalService mSmeppService;
private ProgressDialog progressDialog;
private Thread tt;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// Gets the object to interact with the service
mSmeppService = ((LocalService.LocalBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
mSmeppService = null;
}
};
// For getting confirmation from the service
private BroadcastReceiver serviceReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "receiver onReceive...");
if (progressDialog.isShowing())
progressDialog.dismiss();
// Change activity
Intent groupsActivityIntent = new Intent(ConnectActivity.this,
GroupsActivity.class);
startActivity(groupsActivityIntent);
}
};
// METHODS ----------------------------------------------------------------
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (LocalService.isRunning) {
// TODO start ListActivity
Log.i(TAG, "Starting GroupsScreen");
Intent i = new Intent(ConnectActivity.this, GroupsActivity.class);
startActivity(i);
} else {
setContentView(R.layout.connect_screen);
// Add listener to the button
Button buttonConnect = (Button) findViewById(R.id.button_connect);
buttonConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
processThread();
}
});
}
}
// PRIVATE METHODS --------------------------------------------------------
private void processThread() {
progressDialog = ProgressDialog.show(ConnectActivity.this, "",
"Loading. Please wait...", true, false);
tt = new Thread() {
public void run() {
// Register broadcastReceiver to know when the service finished
// its creation
ConnectActivity.this.registerReceiver(serviceReceiver,
new IntentFilter(Intent.ACTION_VIEW));
// Starts the service
startService(new Intent(ConnectActivity.this,
LocalService.class));
Log.i(TAG, "Receiver registered...");
}
};
tt.start();
}
}
The service executes by the end of the onStart method this:
// Send broadcast so activities take it
Intent i = new Intent(Intent.ACTION_VIEW);
sendOrderedBroadcast(i, null);
So the onReceive method runs and we go to the next activity
The problem is that you are not running ProgressDialog in a UI thread.
Add a handler that will handle messages in your UI thread.
private static final int UPDATE_STARTED = 0;
private static final int UPDATE_FINISHED = 1;
private Handler handler = new Handler(){
#Override public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_STARTED:
progressDialog = ProgressDialog.show(ConnectActivity.this, "",
"Loading. Please wait...", true, false);
break;
case UPDATE_FINISHED:
if(progressDialog.isShowing()){
progressDialog.dismiss();
}
break;
}
}
};
private void processThread() {
Message m = new Message();
m.what = UPDATE_STARTED;
handler.sendMessage(m);
//Your working code
m = new Message();
m.what = UPDATE_FINISHED;
handler.sendMessage(m);
}
good luck!

Categories

Resources