Check game state in activity - android

I'm trying to make a simple android game. I have a surfaceview named: surfaceviewgame, which is responsible for the drawing, updating and handling touch events of the game. At this point I'm checking if the gamestate is "game-over" in this surfaceview by setting the "pause" boolean to true. Now, I want to read this pause variable like this:
SurfaceViewGame v;
if(v.pause == true){
setcontentview(R.Layout.pause)
}
But I can't simply paste that if statement in the activity below. Does someone know how to approach this problem?
public class StartGame extends Activity {
SurfaceViewGame v;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
v = new SurfaceViewGame(this);
setContentView(v);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
v.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
v.resume();
}
}

You can pass some callback object from your activity to your SurfaceView, or make your activity such a callback and notify it about any changes in game flow. Then in your callback method you can resolve next behaviour.

Related

Difference between oncreate and onRestoreInstanceState method in activity

Guys I am stuck in a problem with these two methods:-
When I change the orientation of device and set the text in edit text after retriving the text from bundle,it does't work.But the same code is working in onrestoreStoreInstante method.
Please have a look at my code:-
public class LifeCycleActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText user;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
user=(EditText)findViewById(R.id.et_user);
if(savedInstanceState!=null){
String s =savedInstanceState.get("Key").toString();
user=(EditText)findViewById(R.id.et_user);
user.setText(savedInstanceState.get("Key").toString());
Toast.makeText(this, s,Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "onCreate",Toast.LENGTH_SHORT).show();
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Toast.makeText(this, "onSaveInstanceState",Toast.LENGTH_SHORT).show();
outState.putString("Key", "Deepak");
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//String s =savedInstanceState.get("Key").toString();
//user.setText(s);
Toast.makeText(this, "onRestoreInstanceState",Toast.LENGTH_SHORT).show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(this, "onStart",Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(this, "onResume",Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(this, "onPause",Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(this, "onStop",Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "onDEstroy",Toast.LENGTH_SHORT).show();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Toast.makeText(this, "onRestart",Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent(LifeCycleActivity.this,SecondActivity.class));
}
}
when I set the text in edit text in oncreate method after getting the value from Bundle,it doesn't work.But the same code works in onRestoreInstanceState() method.
According to me , it should work for oncreate also as we can get the Bundle class object there.
Please help me to sort out this problem..
EditText and most of other views have their own methods to save/restore their own data. So in general it's not necessary to save/restore them on your code.
You can see this here on the Android TextView source code (remember that EditText extends from TextView) on line 3546:
if (ss.text != null) {
setText(ss.text);
}
so the reason you can't set it onCreate and can do it onRestoreInstanceState it's because during your activity super.onRestoreInstanceState(savedInstanceState) the activity calls the EditText.onRestoreInstanceState and the EditText restore it self to the previous value.
You can see it happening on the Activity source code on line 940
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (mWindow != null) {
Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
if (windowState != null) {
mWindow.restoreHierarchyState(windowState);
}
}
}
hope it helps.
Overview
onSaveInstanceState() is used to put the data to bundle
onRestoreInstanceState() is used to set the data available in
bundle to your activity
So do as follows:
i Guess until the activity is created onorientation change the
bundle is not available, that's way you are not able to retrieve it
in oncreate
Let the activity create in oncreate
Then restore the instance in onRestoreInstanceState
Hope this helps !

Reduce app CPU Usage in Android

My app shows a splash screen for 4 seconds and then opens another activity with a web view.
I am using a thread to splash the screen and finish() the first activity as soon as web view activity is started. I have also used animations like fade in and fade out.
It's CPU usage is fluctuating between 8% to 23%.What could be the reason. I want to reduce the CPU usage.
My first activity that shows splash screen and starts web view activity-
public class MainActivity extends Activity {
Thread splashThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.animation.fadein,R.animation.fadeout);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
//-----------------------------------------
splashThread=new Thread(){
public void run()
{
try
{
sleep(1000);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
Intent intent = new Intent(getApplicationContext(),OpenWeb.class);
startActivity(intent);
}
}
};
splashThread.start();
//-----------------------------------------
super.onStart();
overridePendingTransition(R.animation.fadein, R.animation.fadeout);
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
finish();
super.onRestart();
}
}
Could be that you used alot of imports something like. I heard that uses alot of cpu?
import android.graphics.*
Are you using a AVD?

Values in onClick not fix in onResume

I am new in android. I write a program that ball moves via accelerometer sensor and this good works. I use Timer and schedule method for this(schedule(mTimerTask, delay,period);) I have two buttons in my screen and i want when user click in positive button, period and delay value increases and when clicked in negative button, these values decreases. I write this code but the changes values in onClick method not fix in onResume method. I know onResume method called as a part of the life cycle but i dont know how can i solve my problem! please help me :) thanks
public class MainActivity extends Activity {
float result=0;
BallView ball=null;
Handler redrawHandler=new Handler();
//
Timer mTimer;
TimerTask mTimerTask;
//
int mSrcWidth,mSrcHeight;
PointF mBallPos,mBallSpd;
//
Button positiveBtn;
Button negativeBtn;
//
int delay=10;
int period=10;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
positiveBtn=(Button)findViewById(R.id.positiveBtn);
negativeBtn=(Button)findViewById(R.id.negativeBtn);
Log.e("onclick", "in oncreate");
getWindow().setFlags(0xFFFFFFFF, LayoutParams.FLAG_FULLSCREEN|LayoutParams.FLAG_KEEP_SCREEN_ON);
final FrameLayout frame=(FrameLayout)findViewById(R.id.main_view);
//
Display display=getWindowManager().getDefaultDisplay();
mSrcWidth=display.getWidth();
mSrcHeight=display.getHeight();
mBallPos=new PointF();
mBallSpd=new PointF();
mBallPos.x=mSrcWidth/2;
mBallPos.y=mSrcHeight/2;
mBallSpd.x=0;
mBallSpd.y=0;
ball=new BallView(this,mBallPos.x,mBallPos.y,10);
frame.addView(ball);
//
ball.invalidate();
positiveBtn.setOnClickListener(onClickListener);
negativeBtn.setOnClickListener(onClickListener);
SensorManager sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
sm.registerListener(new SensorEventListener(){
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
//
mBallSpd.x=-event.values[0];
mBallSpd.y=event.values[1];
}
//
},sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0), SensorManager.SENSOR_DELAY_NORMAL);
Log.e("onclick", "in onsensor");
}
private OnClickListener onClickListener=new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.negativeBtn:
if(delay<=5&&period<=5)
delay=period=5;
else{
delay=delay-10;
period=period-10;
}
break;
case R.id.positiveBtn:
if(delay>=50&&period>=50)
delay=period=150;
else{
delay=delay+10;
period=period+10;
}
break;
}
Log.e("delay","="+ delay);
Log.e("period","="+ period);
}
} ;
#Override
public void onPause(){
mTimer.cancel();
mTimer=null;
mTimerTask=null;
super.onPause();
}
#Override
public void onResume(){
mTimer=new Timer();
mTimerTask=new TimerTask(){
public void run(){
//Log.e("in ", "onResume()");
//positiveBtn.setOnClickListener(onClickListener);
//negativeBtn.setOnClickListener(onClickListener);
mBallPos.x+=mBallSpd.x;
mBallPos.y+=mBallSpd.y;
if(mBallPos.x>=mSrcWidth)
mBallPos.x=mSrcWidth;
if(mBallPos.y>=mSrcHeight)
mBallPos.y=mSrcHeight;
if(mBallPos.x<=0)
mBallPos.x=0;
if(mBallPos.y<=0)
mBallPos.y=0;
ball.x=mBallPos.x;
ball.y=mBallPos.y;
redrawHandler.post(new Runnable(){
public void run() {
// TODO Auto-generated method stub
ball.invalidate();
}
});
}
};
mTimer.schedule(mTimerTask, delay,period);
super.onResume();
}
Implement onSaveInstanceState like so:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt("STATE_DELAY", delay);
savedInstanceState.putInt("STATE_PERIOD", period);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
and then inside your onCreate try to restore them (if they have been set) like so:
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
delay = savedInstanceState.getInt("STATE_DELAY");
period = savedInstanceState.getInt("STATE_PERIOD");
}
And finally as I wrote in the comments of the question have a look at the Recreating an Activity training page.

Android: How do you start a wallpaperservice from a button?

I have a test live wallpaper that I wish to start from an activity. At the moment, it immediately finds itself in the live wallpaper chooser as I run the project on my emulator. Having searched everywhere, I still can't find a way to make it show up there only after a button in my main activity is pressed.
I tried introducing a static boolean in my main activity, isnotpressed, and setting it to false in the button onClick(). Then I used stopSelf() in my wallpaperservice class while isnotpressed is true. Unfortunately, none of this was to any avail and I don't think I'm going about it in the right way anyway. I also tried this, but it didn't work either. Any help would be deeply appreciated here.
Here's the main activity:
public class TestProjectActivity extends Activity{
static boolean isnotPressed;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
isnotPressed = true;
final Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
isnotPressed = false;
}
});
}
}
And here's part of the wallpaperservice:
public class MyWallpaperService extends WallpaperService {
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
while(TestProjectActivity.isnotPressed){stopSelf();}
}
Try this :
Intent i = new Intent();
if (Build.VERSION.SDK_INT > 15)
{
i.setAction(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
String pkg = MyPreferencesActivity.class.getPackage().getName();
String cls = MyPreferencesActivity.class.getCanonicalName();
i.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(pkg, cls));
}
else
{
i.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
}
startActivityForResult(i, 0);

Android: OnResume causes force close

I'm trying to make a simple notepad application and I would like to refresh the notes when the New Note activity finishes and the main screen resumes. However I get force close when trying to open the application with this code. If I remove the OnResume thing it doesn't force close. Help?
public class NotePadActivity extends Activity implements View.OnClickListener {
TextView tw;
String data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tw = (TextView)findViewById(R.id.uusi);
tw.setOnClickListener(this);
Note note = new Note(this);
note.open();
data = note.getData();
note.close();
tw.setText(data);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.uusi:
try {
startActivity(new Intent(PadsterActivity.this, Class.forName("com.test.notepad.NewNote")));
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Note note = new Note(this);
note.open();
data = note.getData();
note.close();
tw.setText(data);
}
}
The problem is you have two different TextViews called tw see my comments on your code...
public class NotePadActivity extends Activity implements View.OnClickListener {
TextView tw; // This never gets instantiated
...
Another here...
public void onCreate(Bundle savedInstanceState) {
...
// This is instantiated but is local to onCreate(...)
TextView tw = (TextView)findViewById(R.id.uusi);
Then in onResume(...) you attempt to use the instance member tw which is null...
protected void onResume() {
...
tw.setText(data);
Change the line in onCreate to...
tw = (TextView)findViewById(R.id.uusi);
...and it should fix the problem.
BTW, you don't need to duplicate everything in onCreate(...) again in onResume() as onResume() is always called after onCreate(...) when an Activity is created.

Categories

Resources