So I have an app that uses a surface view that runs a separate thread for the UI. It was taken almost directly from the Lunar Landing sample app. The app also uses Bluetooth service on another thread but I am sure that this is not related to the problem because I can disable bluetooth all together and it still happens.
The problem in my app is that the app when closed and then reopened does not start running the UI thread afterthread.start() except it throws an error. In the Lunar example they have thread.start() in the onSurfaceCreated method. The problem is when I restart my app (it calls onPause then onSurfaceDestroy) the thread is already running and I get an error when I try to start it. My code for onSurfaceCreated, onPause, onResume and onSurfaceDestroyed is all the same as the example. I know I can use if (this.getState() == Thread.State.NEW) { but that seems like it will mask some of my other issues. I want to master the activity life cycle.
My question is how does the Lunar Lander stop the thread? And why is mine not stopping with the same code and running at the onSurfaceCreated method. Obviously I am missing something. As far as I know in the Lunar example the only thing that is called on the thread on a destroy is thread.join().
Edit 3: Here is the Lunar Lander Example Code if needed.
So these are the three override methods in my surfaceview...
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
Log.d(TAG, "surfaceCreated");
// start the bluetooth service
thread.startBluetoothService();
// start the game
//if (this.getState() == Thread.State.NEW) {
Log.d(TAG, "thread start");
// start running the thread
this.start();
//}
Log.d(TAG, "running to true");
// release the thread lock
setRunning(true);
}
// surfaceChanged is called at least once after surfaceCreated
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.d(TAG, "surfaceChanged");
// reset the surface size
thread.setSurfaceSize(width, height);
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
Log.d(TAG, "surfaceDestroyed");
// make sure to shut down the thread cleanly
boolean retry = true;
// stop the running thread
thread.setRunning(false);
// continuously try to shut down the thread
while (retry){
try{
// blocks calling thread until termination
thread.join();
// stop the bluetooth service
//thread.stopBluetoothService();
retry = false;
}catch(InterruptedException e){
//try to shut it down again
}
}
}
I am really pretty lost with all of this. Any help would be very appreciated, thanks!
Edit:
So I did a little more testing. When the user hits home(which exits the app completely) onPause, then onSurfaceDestroy like I said before. Then when it restarts I get onResume followed by onSurfaceCreated. I think my issue is that it is not calling onCreate when you reenter the app.
Some more questions...
What distinguishes the difference between a onPause and a onDestroy? I think my problem is that since onCreate is not being called I don't have a newly created UI thread which seems like it is still running.
Should the thread be stopped even on a onPause? Because then I am not garenteed to run onCreate which re instantiates the thread. Here is the onCreate code...
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wobble);
// get view and thread
wobbleView = (WobbleView) findViewById(R.id.wobble);
wobbleThread = wobbleView.getThread();
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
// alert the user of bluetooth failure
Toast.makeText(this, "Bluetooth is not available, using internal devices sensors", Toast.LENGTH_LONG).show();
// set the data source to internal sensors - so we'll just use the devices accel
wobbleThread.setDataSource(WobbleThread.INTERNAL_SENSORS);
// bluetooth is supported so make sure its enabled and
}else{
// make sure bluetooth is enabled on the device
if (!mBluetoothAdapter.isEnabled()) {
Log.d(TAG, "starting request to enable bluetooth");
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
// all is well with bluetooth - use bluetooth
Log.d(TAG, "setting bluetooth to bluetooth");
wobbleThread.setDataSource(WobbleThread.BLUETOOTH);
}
// give the LunarView a handle to the TextView used for messages
wobbleView.setTextView(
(TextView) findViewById(R.id.text_accel),
(TextView) findViewById(R.id.game_msg),
(TextView) findViewById(R.id.text_score),
(TextView) findViewById(R.id.bluetooth_status)
);
if (savedInstanceState == null) {
// we were just launched: set up a new game
//wobbleThread.setState(wobbleThread.STATE_READY);
} else {
//wobbleThread.setRunning(true);
// we are being restored: resume a previous game
//wobbleThread.restoreState(savedInstanceState);
}
}
Edit 2:
Some logcat output
So this is what I get when the thread.start() is called after reopening the app.
11-18 22:50:44.104 4868-4868/com.bme.shawn.wobble E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalThreadStateException: Thread already started
at java.lang.Thread.checkNotStarted(Thread.java:871)
at java.lang.Thread.start(Thread.java:1025)
at com.bme.shawn.wobble.WobbleThread.startGame(WobbleThread.java:213)
at com.bme.shawn.wobble.WobbleView.surfaceCreated(WobbleView.java:94)
at android.view.SurfaceView.updateWindow(SurfaceView.java:580)
at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:240)
at android.view.View.dispatchWindowVisibilityChanged(View.java:7903)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1071)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1071)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1071)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1071)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1289)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1050)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5750)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:561)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5406)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
And if I use the thread.getState check and bypass the error I get this when I close then reopen the app. (logs in basically everything) In this case when the app reopens the thread is not drawing at all. Which is very weird since without the check I get an error saying that the thread is already running.
11-18 22:59:13.444 5345-5345/com.bme.shawn.wobble D/WobbleActivity﹕ onPause
11-18 22:59:13.584 5345-5345/com.bme.shawn.wobble D/WobbleView﹕ surfaceDestroyed
11-18 22:59:17.794 5345-5345/com.bme.shawn.wobble D/WobbleActivity﹕ onResume
11-18 22:59:17.804 5345-5345/com.bme.shawn.wobble D/WobbleView﹕ surfaceCreated
11-18 22:59:17.804 5345-5345/com.bme.shawn.wobble D/WobbleThread﹕ running to true
11-18 22:59:17.804 5345-5345/com.bme.shawn.wobble D/WobbleView﹕ surfaceChanged
11-18 22:59:17.804 5345-5345/com.bme.shawn.wobble D/WobbleThread﹕ setting surface sizes
11-18 22:59:17.824 5345-5345/com.bme.shawn.wobble D/dalvikvm﹕ GC_FOR_ALLOC freed 3343K, 2% free 6585K/6668K, paused 13ms, total 13ms
11-18 22:59:17.844 5345-5345/com.bme.shawn.wobble E/IMGSRV﹕ :0: PVRDRMOpen: TP3, ret = 44
11-18 22:59:17.854 5345-5345/com.bme.shawn.wobble E/IMGSRV﹕ :0: PVRDRMOpen: TP3, ret = 50
Create a new instance of the thread in surfaceCreated() and start it. And call thread.join() in surfaceDestroyed()to destroy it.
Related
I have been able to set up a connection between my socket server (running on ruby) and my client, which is an Android(java) application. I will explain what my goal is.
I have to send a string to my server through the socket. Depending on the contents of the string, the server would execute a process in the database (store, delete, view data, etc).
The first option is to validate the user name/password. Im able to send the correct string, and the server receives it and replies back to me with the correct response (after validating whether or not my username is capable of logging into the application). Now, depending on this response i need to change the current activity (loginActivity) with the next activity (MenuActivity) so that the user can proceed to use the application menu.
Since the socket has to run on a different thread other than the UIThread, im running it using the AsyncTask way. However im having problems triggering the activity change thing after the AsyncTask process is over.
What im doing is, after the whole Async task is done (onPostExecute method) im trying to call up the activity, but its not working. This is what i've tried (based on similar cases i've found during research):
(AsyncTask class)
Context context;
private void AppContext(Context context) {
this.context = context.getApplicationContext();
}
OnPostExecute
Intent NewActivity = new Intent();
NewActivity.setClass(context.getApplicationContext(),MainActivity.class);
context.startActivity(NewActivity);
However this is not working and its causing my app to crash with a "thread exciting with uncaught exception"
I've tried showing only a Toast message that says "Granted" or "Denied" just to test it with a simpler task, but i keep getting the same error so im assuming its got to do with handling the change between the thread on which the Async task is running and the UI thread. Any ideas?
P.S: I've checked the other questions that are similar to mine and tried the suggested code, but nothing's worked.
ERROR LOG
09-29 09:59:11.387: E/AndroidRuntime(2856): FATAL EXCEPTION: main
09-29 09:59:11.387: E/AndroidRuntime(2856): java.lang.NullPointerException
09-29 09:59:11.387: E/AndroidRuntime(2856): at com.example.prescoterm.SocketClass.onPostExecute(SocketClass.java:111)
09-29 09:59:11.387: E/AndroidRuntime(2856): at com.example.prescoterm.SocketClass.onPostExecute(SocketClass.java:1)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.AsyncTask.finish(AsyncTask.java:602)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.AsyncTask.access$600(AsyncTask.java:156)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.Handler.dispatchMessage(Handler.java:99)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.Looper.loop(Looper.java:137)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.app.ActivityThread.main(ActivityThread.java:4424)
09-29 09:59:11.387: E/AndroidRuntime(2856): at java.lang.reflect.Method.invokeNative(Native Method)
09-29 09:59:11.387: E/AndroidRuntime(2856): at java.lang.reflect.Method.invoke(Method.java:511)
09-29 09:59:11.387: E/AndroidRuntime(2856): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-29 09:59:11.387: E/AndroidRuntime(2856): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-29 09:59:11.387: E/AndroidRuntime(2856): at dalvik.system.NativeStart.main(Native Method)
Ok so i found a workaround this, now i would like to hear from you guys if you think this'd be a suitable solution.
Since the problem was that the context was coming up null at my AsyncTask class, i decided to load the value on a variable from the moment the application start.
context = this.getApplicationContext();
new SocketReception().setContext(context);
On my SocketReception Class i had a setContext(context) method.
public void setContext(Context context)
{
SocketReception.appContext= context;
};
Now, on my AsyncTask post.execute i call the new activity like this:
SocketReception.appContext.startActivity(NewActivity);
Its now working, but i want to know if this is a convenient approach or if i should keep looking for a different solution.
P.S: I had to add the unpopular "FLAG_ACTIVITY_NEW_TASK", will research on how to avoid this later on.
I have used this asynctask directly in activity and work fine, may be help. When i try call Intent i = new Intent(getApplicationContext(), VyberIcoActivitySD.class); in class without context ( class extended not Activity, Fragment... ) i have not result...
class SynchroAllIcosSD extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SynchroIcoActivitySD.this);
pDialog.setMessage(getString(R.string.progdata));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
//do something
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
Intent i = new Intent(getApplicationContext(), VyberIcoActivitySD.class);
Bundle extras = new Bundle();
extras.putString("odkade", "100");
extras.putString("page", "1");
i.putExtras(extras);
startActivity(i);
finish();
}
});
}
}
Background
I have created a game loop to run the UI, but when I push the back button from the game screen (SingleGameActivity) I get to the level-selector menu called (StartLvlActivity). If I try to reenter the game or push the back button from StartLvlActivity I get a keyDispatchingTimedOut error (ANR).
When I wrote Log messages, the game activity (SingleGameActivity) was only paused, not stopped when I pushed the back button. And the game loop was never destroyed when I closed the activity.
08-03 09:56:12.130: I/Process(346): Sending signal. PID: 5763 SIG: 3
08-03 09:56:12.130: I/dalvikvm(5763): threadid=3: reacting to signal 3
08-03 09:56:12.333: I/dalvikvm(5763): Wrote stack traces to '/data/anr/traces.txt'
08-03 09:56:12.341: E/ActivityManager(346): ANR in com.coderogden.pongtennis (com.coderogden.pongtennis/.activities.StartLvlActivity)
08-03 09:56:12.341: E/ActivityManager(346): Reason: keyDispatchingTimedOut
Questions
1. Why isn't the game loop destroyed when I push the back button from the game menu? I mean, why isn't surfaceDestroyed called when onPaused is called (onStop is never called and I don't know why....).
How do I access "/data/anr/traces.txt"
How do I handle the errors?
If you can answer any of these questions I would appreciate it very much!
EDIT
This is the surface view class from where I start and destroy the thread (or apperently I'm just starting it as it won't shut down when I press "back"-button).
#Override
public void surfaceCreated(SurfaceHolder holder) {
thread.setRunning(true);
thread.start();
Log.d(TAG, " surface created");
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d(TAG, " surface destroyed");
}
EDIT 2 (with solution!)
The bug was fixed by changing this piece of code:
boolean retry = true;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
to this:
thread.setRunning(false);
WHY?
Is it because I need to stop the thread before destroying it?
I am trying to set the background colour of a different activity from the activity main but I am getting a null pointer.
This is the main:
View activity;
activity = findViewById(R.layout.activity_connect_four);
The button:
Button highScoreButton1 = (Button) findViewById(R.id.bgc);
highScoreButton1.setOnClickListener(new OnClickListener() {
public void onClick (View v) {
// null pointer on below line
activity.findViewById(android.R.id.content)
.setBackgroundColor(Color.BLACK);
}
});
The logcat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.con4.MainActivity$4.onClick(MainActivity.java:80)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Where the logCat is pointing to, I don't know what to change. Any help I would be grateful
You're receiving a NPE because that activity and view is not inflated, therefore it returns as null. The way you're setting the background color is flawed by nature. By setting it as you are, even without the NPE, you're storing a setting in the memory of the device. The moment that the device kills your activity, you'll lose that information. As an alternative, you need to store this setting on the device for later retrieval. For what you're attempting to do, I would recommend using SharedPreferences.
In your settings Activity:
Button highScoreButton1 = (Button) findViewById(R.id.bgc);
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
highScoreButton1.setOnClickListener(new OnClickListener() {
public void onClick (View v) {
prefs.edit().putInt(BACKGROUND_COLOR, Color.BLACK).commit();
}
});
BACKGROUND_COLOR is a key variable that could be set to "background_color". Then when you start you other activity:
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
int color = prefs.getInt(BACKGROUND_COLOR, Color.WHITE);
And use that color to set the background. Using this method, the background color will be saved to the device until it gets overridden (settings change) or the app is uninstalled.
If you want this to be the background of all of your activity, I suggest having all activities extending a base activity and implementing that code there.
You can check out other storage methods here: http://developer.android.com/guide/topics/data/data-storage.html
I have a really simple 2 activity app, title screen and main game. I'm trying to make it so that when the user presses the lock button, the app will reappear in the title screen when they unlock the phone. The problem I'm having is that over half the time, I'm getting an exception in the title screen activity when I unlock the phone again. Here's what I've got so far, I know this is probably not the best way, but I was struggling a little. Here's what I'm doing in the main game activity
// On pause, return to main title page
#Override
public void onPause() {
super.onPause();
// Create intent to go back to the title menu
Intent intent = new Intent(this, ActivityTitle.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
And here's what's causing the error in the title bar
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_title_screen);
// Make sure that the volume buttons change the media volume in the app
setVolumeControlStream(AudioManager.STREAM_MUSIC);
radioGroupSound = (RadioGroup) findViewById(R.id.radioGroupSound);
radioGroupText = (RadioGroup) findViewById(R.id.radioGroupText);
// Make the start text blink
TextView myText = (TextView) findViewById(R.id.textViewStart );
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(500); //You can manage the time of the blink with this parameter
anim.setStartOffset(500);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
myText.startAnimation(anim);
}
It's the very last line that's causing the exception - myText.startAnimation(anim).
Here's the error log
07-19 19:49:52.729 26036-26036/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.chrisbjohnson.colorbubbles/com.chrisbjohnson.colorbubbles.ActivityTitle}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1664)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1680)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:945)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3719)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:895)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:653)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.chrisbjohnson.colorbubbles.ActivityTitle.onCreate(ActivityTitle.java:44)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1628)
Any thoughts would be appreciated. Either a different way to handle it, or a way to fix what I'm doing.
Thanks.
After all the time spent trying to figure this out, I realized I was just wasting my time. I fixed it by just making the lock screen not work in my app. Kind of a workaround, but the best thing I could find without wasting weeks of my life.
When testing several games with a standard game thread in Android 4.0 it works well until the Activity is shut down (pressing the home button etc), leaving the activity the application crashes with a nullPointer.
This even happens in the sample LunarLander that Google has programmed.
The problem is that Canvas becomes null when leaving the activity and that makes the application crash.
The error message from the LogCat is just below.
02-27 18:07:58.974: V/MainThread(2667): CANVAS android.view.Surface$CompatibleCanvas#4102bcf0
02-27 18:07:59.164: V/MainThread(2667): CANVAS null
02-27 18:07:59.164: W/dalvikvm(2667): threadid=14: thread exiting with uncaught exception (group=0x409c01f8)
02-27 18:07:59.174: E/AndroidRuntime(2667): FATAL EXCEPTION: Thread-108
02-27 18:07:59.174: E/AndroidRuntime(2667): java.lang.NullPointerException
02-27 18:07:59.174: E/AndroidRuntime(2667): at com.joakimengstrom.pong.MainThread.run(MainThread.java:49)
This is the code when starting a thread, with the Log.v you see above.
while(this.running){
canvas = null;
try {
canvas = this.surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
Log.v(TAG, "CANVAS " + canvas);
canvas.drawColor(Color.BLACK);
...
And below is when creating the thread and shutting it down when the surface is destroyed.
#Override
public void surfaceCreated(SurfaceHolder holder) {
thread = new MainThread(getHolder());
thread.setRunning(true);
thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
thread.setRunning(false);
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
How do I exit the thread in a safe way without making canvas null?
In Android 4.0, SurfaceHolder.lockCanvas can return null when the surface is destroyed. So here:
try {
canvas = this.surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
Log.v(TAG, "CANVAS " + canvas);
canvas.drawColor(Color.BLACK);
Just surround your synchronized (surfaceHolder) block with if (canvas != null). This should not cause any issues with the behaviour of your application as it occurs when drawing is not needed.