Android why doesn't activity finish - android

I have a problem with my game - when the live is 0 it should show the game-over screen and finish the game-activity, but the screen freezes instead.
The code in the surface is:
if(live <= 0){
try {
gameThread.setGameRunning(false);
gameThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
gameOverHandler.post(new Runnable() {
#Override
public void run() {
gameOver.onGameOver(score);
}
});
}
And the Interface in the GameActivity:
#Override
public void onGameOver(int score) {
Intent gameOver = new Intent(this, GameOver.class);
gameOver.putExtra("score", score);
startActivity(gameOver);
gameEngine.stop();
this.finish();
}
The Game-thread loops the canvas drawing and the Engine the movements of the Characters.
I hope you can help me.
Thanks!

You must have initialised gameOverHandler somewhere in the code using
gameOverHandler = new Handler();
or
gameOverHandler = new GameOverHandler();
Try replacing it with
gameOverHandler = new Handler(Looper.getMainLooper());
or
gameOverHandler = new GameOverHandler(Looper.getMainLooper());
depending on what class you have actually used.

Sry my internet was down about the weekend i've solved it with the constructor
public GameSurface(Context context, OnGameOver onGameOver){
...
}
and in the MainActivity
gameSurface = new GameSurface(this, this);
and implementing OnGameOver
a litte bit rewrite for my code but its works...

Related

Stop thread in android application

public class CallEvent extends BroadcastReceiver{
public LEDController ledController = new LEDController();
public ApplicationSettings applicationSettings = new ApplicationSettings();
public boolean ring = false;
#Override
public void onReceive(Context context, Intent intent){
if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)){
ring = true;
blink();
}else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE) ||
intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
ring = false;
}
}
public void blink(){
Runnable r = new Runnable() {
#Override
public void run() {
while(ring){
ledController.turnOnFlash();
try {
Thread.sleep(applicationSettings.getDelayOn());
} catch (InterruptedException e) {
e.printStackTrace();
}
ledController.turnOffFlash();
try {
Thread.sleep(applicationSettings.getDelayOff());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread blinkThread = new Thread(r);
blinkThread.start();
}
}
I want to create led messenger when phone is ring. But I can't stop blinkThread. I dont know it is not working. Led start when call income but don't stop when call decline. Variable ring is changing on 'false' when call decline, but thread still working
In general, you don't forcibly stop threads because it's dangerous. You set a flag that tells the thread in question to exit from it's thread loop under controlled circumstances.
Your thread loop looks something along these lines:
void run() {
while (shouldContinue) {
doThreadWorkUnit();
}
}
And somewhere else you set the shouldContinue variable and wait for the thread to finish:
...
thread.shouldContinue = false;
thread.join();
...
(All this is likely not correct Java, since I don't do Java. View it as pseudo code and modify for your actual language/thread library/etc.)
Source: How to stop a thread?

Android Create an activity with no buttons

I am very confused as to why I cannot get this to work. I want to have a screen with no buttons run for 5 seconds while I do some things in the background, then navigate back to another screen. Is this not possible?
I have tried to put the code to run the background items in onCreate, onStart, and onResume, and all of these methods are fired before the screen actually displays. Is there another way to do this?
Edit The most recent version of my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync);
}
protected void onResume(){
super.onResume();
commitSync();
}
private void commitSync(){
TextView monthDayYear = (TextView)findViewById(R.id.month_day_year);
TextView hourMinuteSecond = (TextView)findViewById(R.id.hour_minute_second);
_application = (App)getApplicationContext();
try {
CountDownLatch latch = new CountDownLatch(1);
latch.await(5, TimeUnit.SECONDS);
//Ensure that we have flash
if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
Camera androidCamera = Camera.open();
Camera.Parameters p = androidCamera.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
androidCamera.setParameters(p);
//Flash and then turn off
androidCamera.startPreview();
latch.await(50, TimeUnit.MILLISECONDS);
androidCamera.stopPreview();
//Flash screen white
//Get date and time
Module syncModule = _application.getModule();
syncModule.start();
Calendar syncTime = syncModule.getDateAndTime();
//http://stackoverflow.com/questions/21988004/get-time-in-hhmmss-from-seconds-in-java
monthDayYear.setText(new SimpleDateFormat("MM/dd/yyyy").format(syncTime.getTime()));
hourMinuteSecond.setText(new SimpleDateFormat("HH:mm:ss:00").format(syncTime.getTime()));
//Navigate back to MainActivity
Intent mainActivityIntent = new Intent(SyncActivity.this, MainActivity.class);
startActivityForResult(mainActivityIntent, 1);
} else {
throw new Exception("Cannot access Android Flash");
}
} catch (Exception ex) {
Util.appendLog("Exception occured in Sync: " + ex.getMessage());
}
}
Maybe this help you:
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run() {
// Do some work like:
finish();
}
}, 500);
This run a code after some delay and you can put this code in your desired screen.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//The code you want to execute
}
}, timeUntilExecution);
This code should execute that run() method after the timeUntilExecution variable (in milliseconds) you could use this to execute what you want to do after the delay. Hope this helps.

animation in android activities not working

I have made 4 activities in android they all are same. They just have a relative layout and that layout has 4 different images as backgroud,i have set animation on that for 2000miliseconds for example 1st screen should come from right.second from left...etc..I have implemented as below but its not working pls help me..!
screen1.java
Thread splashThread = new Thread() {
public void run() {
try {
sleep(2000);
} catch (Exception e) {
}
startAnimatedActivity(new Intent(SplashActivity1.this,
SplashActivity2.class),
CustAnimatedActivity.SLIDE_FROM_RIGHT);
finish();
}
};
splashThread.start();
same code for 3 activity also..!
i have used "handler" in place of "thread" .I have tried following code..and its working like butter..!
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
handler.sendEmptyMessage(1);
}
}, 2000);
}
private Handler handler = new Handler()
{
#SuppressWarnings("deprecation")
#Override
public void handleMessage(android.os.Message msg)
{
try
{
Intent intent = null;
intent = new Intent(SplashActivity1.this,
SplashActivity2.class);
startActivity(intent);
overridePendingTransition(R.anim.animated_activity_slide_left_in, R.anim.animated_activity_slide_right_out);
finish();
} catch (Exception e) {
}
}
};

Android Progress Dialog Box While updating GUI

So I've been at this for 2 days and still I can't get it working.
I've tried solutions of implementing runnable, asynctask but it just never seems to work with my code. Perhaps I implemented it the wrong way...
Anyway, I have the following code written. When I create this activity I want to show a progressdialog with the text "Loading". Problem is, you can't update GUI-elements from another thread. That is where I'm stuck.
Hope you can help me out!
PS: The reason i need a ProgressDialog is because the line
ArrayList<String> genres = MysqlHandler.getAllGenres();
Can take quite some time to load. Also i have some other activities which need to do the same, and there it can take up to 5 seconds to load.
public class GenreActivity extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_genre);
try {
ArrayList<String> genres = MysqlHandler.getAllGenres();
LinearLayout layout = (LinearLayout) findViewById(R.id.AllGenreLayout);
for(int i = 0; i < genres.size(); i++)
{
Button myButton = new Button(this);
myButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.yellow_button));
myButton.setTextAppearance(this, R.style.ButtonText);
myButton.setText(genres.get(i));
myButton.setOnClickListener(this);
layout.addView(myButton);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/// try :)
progressgialog.post(new Runnable(){
run ()
{
progressgialog.setMessage("asd");
}
})
//// catch :)
activity.runOnUiThread(new Runnable()
{
progressgialog.setMessage("asd");
});
I found a work-around and thought I would share it.
Since I was making another thread inside the oncreate method, I figured I could also make a thread when i was starting the intent. So instead of this code:
Intent inte = new Intent(FirstSearchActivity.this, GenreActivity.class);
startActivity(inte);
Now I'm doing:
//start the progress dialog
progressDialog = ProgressDialog.show(FirstSearchActivity.this, "", "Loading...");
new Thread()
{
public void run()
{
Intent inte = new Intent(FirstSearchActivity.this, GenreActivity.class);
startActivity(inte);
progressDialog.dismiss();
}
}.start();

Can't start an activity in application onCreate

I am trying to start an activity after n seconds with a handler. The application was crashing on the startActivity call, so I put the handler code in my application's onCreate, and it is still crashing (which makes me think that the error comes from me not using startActivity well) :
#Override
public void onCreate(){
String roomName = this.getSettingValue(R.string.PREFERENCES_ROOM_NAME, "");
Room room;
try {
room = this.getRoomWithName(roomName);
} catch (ReservatorException ex) {
Toast err = Toast.makeText(this, ex.getMessage(),
Toast.LENGTH_LONG);
err.show();
return;
}
Intent i = new Intent(this, RoomActivity.class);
i.putExtra("room", room);
this.startActivity(i);
}
Strange thing is that this work when called from a view, by using exactly the same code, but different context :
Intent i = new Intent(getContext(), RoomActivity.class);
// ...
I am pretty new to Android ... so there may be information missing in that question, or I might even be trying to do something completely stupid who knows ?
EDIT
Link to the stacktrace : http://pastebin.com/vh2QC3xz
EDIT2
Here is the handler version of my code (so what I am trying to do in the end) :
public class ReservatorApplication extends Application {
private GoToFavouriteRoom goToFavouriteRoomRunable;
class GoToFavouriteRoom implements Runnable {
ReservatorApplication app;
public GoToFavouriteRoom(ReservatorApplication anApp){
app = anApp;
}
#Override
public void run() {
String roomName = app.getSettingValue(R.string.PREFERENCES_ROOM_NAME, "");
Room room;
try {
room = app.getDataProxy().getRoomWithName(roomName);
} catch (ReservatorException ex) {
Toast err = Toast.makeText(app, ex.getMessage(),
Toast.LENGTH_LONG);
err.show();
return;
}
RoomActivity.startWith(app, room);
}
}
private final ReservatorAppHandler handler = new ReservatorAppHandler();
class ReservatorAppHandler extends Handler{
#Override
public void handleMessage(Message msg){
return;
}
}
#Override
public void onCreate(){
String serverAddress = getSettingValue(R.string.PREFERENCES_SERVER_ADDRESS, "mail.futurice.com");// TODO: change to mail.futurice.com before delivery
proxy = new SoapDataProxy(serverAddress);
// proxy = new DummyDataProxy();
proxy = new CachedDataProxy(proxy);
addressBook = new FumAddressBook();
try {
addressBook.prefetchEntries();
} catch (ReservatorException e) {
// TODO: DIE!
}
goToFavouriteRoomRunable = new GoToFavouriteRoom(this);
handler.postDelayed(goToFavouriteRoomRunable, 20000);
}
Ok ... I finally solved my problem, mainly thanks to #Drax
Apparently, you just can't start an activity from an application ... you need an instance of an activity. So :
public class ReservatorApplication extends Application {
#Override
public void onCreate(){
Intent i = new Intent(this, RoomActivity.class);
this.startActivity(i);
}
}
Is just not valid, and causes a RunTimeException ...
As far as crashing is concern when you start activity in handler with "this". it will take handler's context. and when you do getContext() it will take activity context.
Intent i = new Intent(YourActivityName.this, RoomActivity.class);
or
Intent i = new Intent(getBaseContext(), RoomActivity.class);
It`s hard to answer without seeing the stack trace from logcat, but I found that sometimes you need to pass the application context to the a new Intent before starting an Activity.
Try this line:
Intent i = new Intent(getApplicationContext(), RoomActivity.class);

Categories

Resources