Reduce app CPU Usage in Android - 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?

Related

Android Black Screen after Unlocking

I'm having trouble with resuming an app's activity after locking the device screen.
Here's the typical situation:
1. App is running.
2. Lock device.
3. Unlock device.
4. Instead of returning to running app, it shows a black screen.
I checked how the activity lifecycle is running and it seems this is what's happening when it unlocks:
1. Create
2. Start
3. Resume
4. Pause
Why is it stuck on pause? I'm sure this is really simple but as I'm still learning Android I'm super confused. Thanks for any help given!
EDIT:
I don't think I'm doing anything out of the ordinary but here's the basic code I'm using...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Java", "Create");
// Initialize NDK audio properties here
// Initialize the Content View
setContentView(R.layout.activity_main);
// Setup toolbar
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolBar);
setSupportActionBar(myToolbar);
// Start thread
thread = new Thread() {
public void run() {
setPriority(Thread.MAX_PRIORITY);
// Audio Thread is running here
}
};
thread.start();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onPause() {
super.onPause();
if (thread != null) {
try {
thread.join();
}
catch (InterruptedException e) {
// e.printStackTrace();
}
thread = null;
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStop() {
super.onStop();
}
Try this (it will instruct your app to save state):
protected void onSaveInstanceState(Bundle icicle) {
icicle.putLong("param", 1);
super.onSaveInstanceState(icicle);
}
I am not thread expert. but here it seems you are blocking ui thread in onpause. thread.join causes the current thread(in this case ui thread) to pause execution until thread terminates.

Check game state in activity

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.

MainActivity starts before SplashScreen ends

I have a SplashScreen activity at my android app that lasts for 3 seconds, and then it switches to MainActivity.
MainActivity plays a sound, and it has a button. My problem is that the sound plays when the SplashScreen activity is visible.
onResume at MainActivity calls for run(), run() sleeps for 2 seconds and plays the sound.
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
m.start();
try {
Thread.sleep((int) randomValue * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.seekTo(0);
m.start();
cpu.setText(EranThatWillShortYourDouble(randomValue));
btn.setClickable(true);
}
#Override
protected void onResume() {
super.onResume();
run();
}
Instead of SplashScreen displaying for 3 seconds and switches to MainAcivity, It lasts 5 seconds and plays the sound when SplashScreen is visible.
What do I do?
EDIT: This is my SplashScreen activity:
public class SplashScreen extends Activity {
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
Please take a look at AsyncTasks, Android Runnables and the ability to use a Handler to postDelayed.
Don't do thread.sleep in the main thread, it's really bad. :)
Do not use splash screens in Android. They are against the design guidelines and provide a poor UX.
http://developer.android.com/design/patterns/help.html#your-app

How to wait for an activity to fully load?

I'm making an activity where I'm planning to display a progress bar and move to a second activity after five seconds. I used Thread.sleep to do this.
Here is the code for the activity with the spinner.
public class WaitScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.waitscreen);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
try{
for(int i=0;i<5;i++){
Thread.sleep(1000);
}
Toast.makeText(getApplicationContext(), "Spinner complete!", Toast.LENGTH_LONG).show();
}
catch(InterruptedException e){
}
Intent i = new Intent("emergency.app.NEWACTIVITY");
startActivity(i);
}
}
My main activity only has a button that leads to this page on being clicked. Problem is, it displays the main activity for five seconds, then this activity very briefly and then the third activity. How do I make the thread start after WaitScreen is fully loaded? As you can see, I tried using the onStart method to do the trick. Or if you could tell me another way to introduce a five second delay, that would be helpful too!
Use a Handler to post a Runnable, like so:
public class WaitScreen extends Activity {
private Runnable task = new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Spinner complete!", Toast.LENGTH_LONG).show();
Intent i = new Intent("emergency.app.NEWACTIVITY");
startActivity(i);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waitscreen);
Handler handler = new Handler();
handler.postDelayed(task, 5000);
}
}
The Runnable task will execute after 5 seconds.
http://developer.android.com/reference/android/os/Handler.html

Force splash to show from onCreate Activity

My app has the following Activities:
DashboardActivity
SplashActivity
MainActivity
This how the flow is required:
The dash board has a button that starts up the MainActivity. The onCreate() method of the main activity checks if a user-profile was previously created, if yes, then it starts normally (this is fast, no GUI delay).
If no user-profile is found, then it's required to display a splash screen having instructions/how-to for the mainActivity, meanwhile the onCreate() of the main activity creates a new user-profile file(slow and GUI blocking).
What I'm currently see is the splash/instructions showing delayed after the slow user-profile creation ends.
Here is a code snippet from MainActivity.
private void showUsage(){
Thread splashTread = new Thread() {
public void run() {
try {
Intent instructionIntent = new Intent(MainActivity.this,
InstructionsActivity.class);
startActivity(instructionIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
};
splashTread.start();
}
#Override //MainActivity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (!IsProfileExists()){
showUsage();
try{
createUserProfile(); //slow!
} catch (Exception e) { }
}
/*Continue with MainActivity*/
}
The Splash dismisses itself by a click:
public class InstructionsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.instructions_layout);
ImageView instructions = (ImageView) findViewById(R.id.ivInstructions);
instructions.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
The problem:
The Instructions Activity (splash) shows after the GUI gets block from the MainActivity onCreate().
Any clues?
Do the condition check (IsProfileExists()) from dashBoardActivity and call the Splash activity if profile doesn't exist.

Categories

Resources