Delay after the splash screen - android

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);
}

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();
}
}
}

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);
}
}

Cant get android activity to stay on when the phone goes to sleep

I am rather new to android and I am attempting an alarm clock app. I am starting an activity through an AlarmManager which works fine as long as the phone is awake. When the phone is asleep it appears to run the code properly and then it runs the onStop function closing the activity. I have tried various combinations of WakeLock and Window flags with no avail.
This does however work on an older phone (2.3) if that helps. Any insight is appreciated.
Here is code for the Alarm activity:
package com.myAlarm.android;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.DigitalClock;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView;
import com.snoozulooze.android.UtilityFunctions;
#SuppressLint("NewApi")
public class Alarm extends Activity{
private int timerDelay = 4000;
private int id;
private double snoozeInt = 1;
private TextView clockText;
private TextView dateText;
private LinearLayout clockLayout;
private DatabaseHandler db;
public static AlarmRow ALARM_DATA;
private Animation animScroll;
private SensorManager mSensorManager;
private ShakeEventListener mSensorListener;
private Runnable alertLoop;
private Handler handler;
private ImageView snooze;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
turnOnScreen();
Log.i("ALARM", "on create ran");
AlarmWakeLock.acquireCpuWakeLock(Alarm.this);
setContentView(R.layout.activity_alarm);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new ShakeEventListener();
handler = new Handler();
alertLoop = new Runnable() {
#Override
public void run() {
playAlarm();
handler.postDelayed(this, timerDelay);
}
};
//Create the clock for text clock of digital clock
LayoutParams clockParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
clockLayout = (LinearLayout)findViewById(R.id.alarmClockLayout);
dateText = (TextView) findViewById(R.id.alarmClockDateTxt);
try{
TextClock tc = new TextClock(Alarm.this);
tc.setLayoutParams(clockParams);
tc.setTextColor(getResources().getColor(R.color.white));
tc.setGravity(Gravity.CENTER);
clockText = (TextClock) tc;
}
catch(Throwable t){
Log.e("Alarm", t.getMessage());
DigitalClock dc = new DigitalClock(Alarm.this);
dc.setLayoutParams(clockParams);
dc.setTextColor(getResources().getColor(R.color.white));
dc.setGravity(Gravity.CENTER);
clockText = (TextView) dc;
}
clockLayout.addView(clockText,0);
UtilityFunctions.assignText(Alarm.this, clockText, "fonts/Roboto-Thin.ttf");
SimpleDateFormat sdf = new SimpleDateFormat("EEE. LLLL dd");
String currentDateandTime = sdf.format(new Date());
dateText.setText(currentDateandTime.toLowerCase());
clockLayout.post(new Runnable(){
public void run(){
float clockHeight = (float) (clockLayout.getHeight()*.35);
float dateHeight = (float) (clockLayout.getHeight()*.15);
if (clockHeight > 45){
clockHeight = 45;
dateHeight = 24;
}
clockText.setTextSize(((float) clockHeight));
dateText.setTextSize(((float) dateHeight));
}
});
//SetupAlarm aSetUp = new SetupAlarm();
//aSetUp.execute();
init();
}
private void init(){
db = new DatabaseHandler(this);
Intent fromIntent = getIntent();
Bundle bundle = fromIntent.getExtras();
id = bundle.getInt("id");
Alarm.ALARM_DATA = db.getAlarmData(id);
snooze = (ImageView) findViewById(R.id.snoozeAlarmBtn);
setupUI();
}
private void setupUI(){
String message = Alarm.ALARM_DATA.getMessage();
if(message != "" && message != null){
TextView tv = new TextView(Alarm.this);
tv.setText(message);
tv.setTextSize(16);
FrameLayout sf = (FrameLayout) findViewById(R.id.snoozFrame);
tv.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
sf.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
sf.addView(tv, tv.getMeasuredWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
animScroll = new TranslateAnimation(sf.getMeasuredWidth(), tv.getMeasuredWidth()*-1, 0, 0);
long durationMulti = ((sf.getMeasuredWidth()+tv.getMeasuredWidth())/sf.getMeasuredWidth());
int duration = (int) (5000*durationMulti);
animScroll.setDuration(duration);
animScroll.setInterpolator(new LinearInterpolator());
animScroll.setRepeatCount(Animation.INFINITE);
tv.startAnimation(animScroll);
}
snooze.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
handler.removeCallbacks(alertLoop);
handler.removeCallbacksAndMessages(null);
AlarmReceiverRepeating.resetPhone(Alarm.this);
AlarmReceiver ar = new AlarmReceiver();
ar.setOnetimeTimer(Alarm.this, Alarm.ALARM_DATA.getId(), (long) (System.currentTimeMillis() + (1000*60*snoozeInt)),Alarm.ALARM_DATA.getId());
Intent mainIntent = new Intent(Alarm.this,Main.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(mainIntent);
finish();
AlarmWakeLock.releaseCpuLock();
}
});
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {
public void onShake() {
handler.removeCallbacks(alertLoop);
handler.removeCallbacksAndMessages(null);
AlarmReceiverRepeating.resetPhone(Alarm.this);
Intent mainIntent = new Intent(Alarm.this,Main.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(mainIntent);
Notifications.setNextAlarmNotification(Alarm.this);
AlarmReceiverRepeating.resetPhone(Alarm.this);
finish();
AlarmWakeLock.releaseCpuLock();
}
});
AlarmReceiverRepeating.setCurrentState(Alarm.this,Alarm.ALARM_DATA.getVolume());
handler.post(alertLoop);
}
//function for playing the ringer and vibrator
public void playAlarm(){
try {
if(AlarmReceiverRepeating.AUDIO_MANAGER == null){
AlarmReceiverRepeating.setCurrentState(Alarm.this, Alarm.ALARM_DATA.getVolume());
}
AlarmReceiverRepeating.REPEAT_COUNT ++;
if(AlarmReceiverRepeating.REPEAT_COUNT > 1){
AlarmReceiverRepeating.REPEAT_COUNT = 0;
if(AlarmReceiverRepeating.CURRENT_VOLUME < AlarmReceiverRepeating.ADJUSTED_MAX_VOLUME)
AlarmReceiverRepeating.CURRENT_VOLUME++;
}
AlarmReceiverRepeating.AUDIO_MANAGER.setStreamVolume(AudioManager.STREAM_RING, AlarmReceiverRepeating.CURRENT_VOLUME, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
AlarmReceiverRepeating.AUDIO_MANAGER.setStreamVolume(AudioManager.STREAM_RING, AlarmReceiverRepeating.CURRENT_VOLUME, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
Uri alarm = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Alarm.this);
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(Alarm.this, alarm);
} catch (Exception e1) {
e1.printStackTrace();
mediaPlayer.release();
return;
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
}
});
try {
mediaPlayer.prepare();
} catch (Exception e1) {
e1.printStackTrace();
mediaPlayer.release();
return;
}
mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
#Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
mediaPlayer.stop();
mediaPlayer.start();
}
});
mediaPlayer.setVolume(AlarmReceiverRepeating.CURRENT_VOLUME, AlarmReceiverRepeating.CURRENT_VOLUME);
mediaPlayer.start();
}
catch (Throwable t) {
Log.i("ALARM", "ERROR PLAYING ALARM");
Toast.makeText(this, "there was a problem in the playAlarm function", Toast.LENGTH_SHORT).show();
}
}//end playAlarm
#Override
protected void onStop(){
super.onStop();
Log.i("ALARM", "on stop ran");
handler.removeCallbacks(alertLoop);
handler.removeCallbacksAndMessages(null);
Notifications.setNextAlarmNotification(Alarm.this);
AlarmReceiverRepeating.resetPhone(this);
finish();
AlarmWakeLock.releaseCpuLock();
}
#Override
protected void onStart(){
super.onStart();
}
#Override
protected void onPause(){
super.onPause();
Log.i("ALARM", "on pause ran");
}
#Override
protected void onDestroy(){
super.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
turnOnScreen();
Log.i("ALARM", "on resume ran");
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
private void turnOnScreen(){
final Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
+ WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
+ WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
+ WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
}
private class SetupAlarm extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... urls) {
init();
return null;
}
protected void onPostExecute(Void args) {
setupUI();
}
}
}
I have figured out what was going on. It was not a wakelock issue. The issue is that, for whatever reason the onStop function was (is still) being called when the phone wakes from sleeping. Since I had a finish() function running it was killing the activity. I placed the code in the onStop override so that the alarm will stop if the user hits the back or home button so I will need to address that unless someone can enlighten me on why the onStop is called an how to avoid it. Thanks
You will need to include this permission in your manifest:
uses-permission android:name="android.permission.WAKE_LOCK" or see this it might helpful to you How do I prevent an Android device from going to sleep programmatically?

Starting new activity triggered by boolean in GameThread (android)

I am making a "Defend the castle" style android application. The game is complete, however I just need help closing my surfaceview and starting a new activity for when the the player has lost the game.
The condition for losing the game is just a boolean variable in my GameThread class. The variable is called "lost" and is by default set to false. When the life of the castle drops below 1, lost is set to true and a sound effect plays.
Ideally, I would like to stop the currently looping sound effects and open a new activity (which is already made and working) upon lost=true.
The main activity is as follows:
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends Activity {
Button btn_startGame;
Activity activity;
GameView mGameView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
activity = this;
setContentView(R.layout.main);
btn_startGame = (Button) findViewById(R.id.btnStartGame);
btn_startGame.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
mGameView = new GameView(activity);
setContentView(mGameView);
mGameView.mThread.doStart();
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
try {
mGameView.mThread.onTouch(event);
} catch(Exception e) {}
return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// ignore orientation/keyboard change
super.onConfigurationChanged(newConfig);
}
}
The surfaceview is created in this class called GameView:
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
public class GameView extends SurfaceView implements Callback {
Context mContext;
GameThread mThread;
public GameView(Context context) {
super(context);
this.mContext = context;
getHolder().addCallback(this);
mThread = new GameThread(getHolder(), mContext, new Handler() {
#Override
public void handleMessage(Message m) {
// Use for pushing back messages.
}
});
setFocusable(true);
}
//#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.d(this.getClass().toString(), "in SurfaceChanged()");
}
//#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(this.getClass().toString(), "in SurfaceCreated()");
mThread.running = true;
mThread.start();
}
//#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(this.getClass().toString(), "in SurfaceDestroyed()");
boolean retry = true;
mThread.running = false;
while (retry) {
try {
mThread.join();
retry = false;
} catch (InterruptedException e) {
}
GameThread.music.stop();
GameThread.groan1.stop();
GameThread.groan2.stop();
GameThread.walk.stop();
GameThread.music.release();
GameThread.groan1.release();
GameThread.groan2.release();
GameThread.walk.release();
GameThread.shoot.release();
}
}
}
The GameThread class contains all of the drawing, the logic and all a run method (below).
#Override
public void run() {
// check if condition here
if(lost){
mContext.runOnUiThread(new Runnable() {
#Override
public void run() {
//start Activity here
Intent intent = new Intent(mContext, LoseActivity.class);
mContext.startActivity(intent);
}
});
}
else{
if (running == true) {
while (running) {
Canvas c = null;
try {
c = mHolder.lockCanvas();
if (width == 0) {
width = c.getWidth();
height = c.getHeight();
player.x = 50;
player.y = 45;
}
synchronized (mHolder) {
long now = System.currentTimeMillis();
update();
draw(c);
ifps++;
if (now > (mLastTime + 1000)) {
mLastTime = now;
fps = ifps;
ifps = 0;
}
}
} finally {
if (c != null) {
mHolder.unlockCanvasAndPost(c);
}
}
}
}
}
The activity that I want to start is called LoseActivity.class. Thank you in advance for any and all help. If anybody needs any further code/explanations, I will be more than happy to post it.
Use runOnUiThread for starting Activity from Thread as:
Change your main Activity as:
public class MainActivity extends Activity {
Button btn_startGame;
Activity activity;
GameView mGameView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
activity = this;
setContentView(R.layout.main);
btn_startGame = (Button) findViewById(R.id.btnStartGame);
btn_startGame.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
mGameView = new GameView(activity,MainActivity.this);
setContentView(mGameView);
mGameView.mThread.doStart();
}
});
}
///your code.....
Change your GameView class as:
public class GameView extends SurfaceView implements Callback {
Context mContext;
Activity contextx;
GameThread mThread;
public GameView(Context context,Activity contextx) {
super(context);
this.mContext = context;
this.contextx=contextx;
getHolder().addCallback(this);
mThread = new GameThread(getHolder(), mContext, new Handler() {
#Override
public void handleMessage(Message m) {
// Use for pushing back messages.
}
});
setFocusable(true);
}
//your code here..........
#Override
public void run() {
// check if condition here
if(lost){
contextx.runOnUiThread(new Runnable() {
#Override
public void run() {
//start Activity here
Intent intent = new Intent(contextx, LoseActivity.class);
contextx.startActivity(intent);
}
});
}
else{
//your code here.........

how to wake a thread from sleep in 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();
}
};
}

Categories

Resources