How to make Android method work recurrently? - java

I have designed an app that displays text when tapped once and displays it differently on a Long Press and on a Double Tap. However, I observe that the methods are called once. That is once I either long press or tap once or double tap, the corresponding method is called and then on subsequent tapping or press does not do anything. What can be done to make the app work not just once?
package com.example.hello;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.ViewGroup.LayoutParams;
import android.view.View.OnTouchListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnClickListener;
public class MainActivity extends ActionBarActivity implements OnTouchListener {
private TextView shownamecenter;
private TextView shownamecustom;
private RelativeLayout myimage;
int x, y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
shownamecenter = (TextView)findViewById(R.id.shownamecenter);
shownamecustom = (TextView)findViewById(R.id.shownamecustom);
myimage = (RelativeLayout)findViewById(R.id.myimage);
shownamecenter.setText("");
shownamecustom.setText("");
myimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showNameOnSingleTap();
return;
}
});;
myimage.setOnTouchListener(this); //{
myimage.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showNameInCustomPosition(shownamecustom, x, y);// TODO Auto-generated method stub
return true;
}
});
return;
}
private void showNameOnSingleTap() {
Timer countdown = new Timer(false);
countdown.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
shownamecenter.setVisibility(View.INVISIBLE);
}
});
}
},3000);
shownamecustom.setText("");
shownamecenter.setText("My Text");
shownamecenter.setTextColor(0xff00ff00);
RelativeLayout.LayoutParams layoutparameters = (RelativeLayout.LayoutParams)shownamecenter.getLayoutParams();
layoutparameters.addRule(RelativeLayout.CENTER_IN_PARENT, -1);
shownamecenter.setLayoutParams(layoutparameters);
findViewById(R.id.myimage).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
shownamecenter.setText("");
return;
}
});
return;
}
private void showNameInCustomPosition(TextView customview, int x, int y) {
Timer countdown = new Timer(false);
countdown.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
shownamecustom.setVisibility(View.INVISIBLE);
}
});
}
},3000);
RelativeLayout.LayoutParams relout = (RelativeLayout.LayoutParams) customview.getLayoutParams();
relout.leftMargin = x-50;
relout.topMargin = y-50;
customview.setLayoutParams(relout);
shownamecenter.setText("");
shownamecustom.setText("My Text");
shownamecustom.setTextColor(0xff00ff00);
class GestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onDoubleTap(MotionEvent e) {
shownamecustom.setText("");
showNameOnSingleTap();
return true;
}
}
return;
}
//}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
x = (int)event.getRawX();
y = (int)event.getRawY();
return false;
}
}

The problem is because you are redefining what happens when you click on the image, which isn't terribly good practice because it makes it difficult to keep track of what should be going on. A View can only ever have one Listener of each type, so when you do
private void showNameOnSingleTap() {
//...
findViewById(R.id.myimage).setOnClickListener (new View.OnClickListener() {
#Override public void onClick(View v) {
shownamecenter.setText(""); return;
}
});
}
You are changing what happens every time that you click the image after that. Rather than calling your method showNameOnSingleTap() when it's clicked, it is only setting the text and not calling your method. Instead of reassigning the onClickListener, just keep a boolean variable to determine what you want to do.
boolean textIsVisible = false;
private void showNameOnSingleTap() {
if(textIsVisible) {
//hide text
textIsVisible = false;
shownamecenter.setText(View.INVISIBLE);
}
else {
Timer countdown = new Timer(false);
countdown.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
shownamecenter.setVisibility(View.INVISIBLE);
textIsVisible = false;
}
});
}
},3000);
//show text
textIsVisible = true;
}
}

Related

Sequential display of images automatically

I am using the code below to display images sequentially via button click. Now I want to display these images automatically after a particular time period. They should be displayed and change after a particular time and where the addition will be needed in the same code.
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private static ImageView imgView;
private static Button ButtonSbm;
private int current_image_index;
int [] images={R.mipmap.ic_launcher,R.mipmap.ic_launcher1};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab=(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action",Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
buttonClick();
}
public void buttonClick(){
imgView =(ImageView)findViewById(R.id.imageView);
ButtonSbm=(Button)findViewById(R.id.button);
ButtonSbm.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v){
current_image_index++;
current_image_index=current_image_index %images.length;
imgView.setImageResource(images[current_image_index]);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Hi you can use he following code
public class TestService extends IntentService {
Context ctx;
private CountDownTimer countDownTimer;
public static final String Tag="TestService";
private long startTime= 2 * 1000;
int index = 0;
private final long interval = 1 * 1000;
public TestService() {
super("TestService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
countDownTimer = new MyCountDownTimer(startTime, interval);
countDownTimer.start();
Looper.loop();
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
// do as per you required
}
#Override
public void onTick(long millisUntilFinished) {
Log.v(Tag,"Inside OnTick()");
// do as per you required
}
}
}

MediaRecorder illegalstateexception the second time

It's self explanatory. mediarecorder class's start method throws an illegalstateexception the second it's called. First time I press the button it all works fine. The second time it does not. I thread a lot of things and Idk what's wrong. I tried solutions from other questions regarding the media recorder but they didn't help. The permissions are place in the manifest. so that isn't the issue obviously since it works the first time.
MAIN
package com.boomer.omer.notetoself;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class Activity_Main extends Activity implements View.OnTouchListener {
ProgressBar progressBar_record;
Button button_record;
Recorder recorder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar_record = (ProgressBar)findViewById(R.id.progressBar_recorder);
button_record = (Button)findViewById(R.id.button_record);
button_record.setOnTouchListener(this);
recorder = null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(v.getId()){
case R.id.button_record:
if(event.getAction() == MotionEvent.ACTION_DOWN){
button_record.setText("RECORDING");
startRecorder();
}else if (event.getAction() == MotionEvent.ACTION_UP){
button_record.setText("RECORD");
stopRecorder();
}
break;
}
return false;
}
public void startRecorder(){
recorder = new Recorder(this,progressBar_record);
recorder.execute();
}
public void stopRecorder(){
progressBar_record.setProgress(0);
recorder.cancel(true);
recorder = null;
}
}
RECORDER CLASS
public class Recorder extends AsyncTask<Void,Integer,Void> {
public static final String LOG_TAG = "NTS:";
static final int MAX_LENGTH = 30;
MediaRecorder mRecorder;
String mFileName = null;
ProgressBar recordBar;
Activity parentActivity;
int mLength = 0;
public Recorder(Activity activity,ProgressBar progressBar) {
super();
mFileName = activity.getFilesDir().getAbsolutePath();
mFileName += "/recentRecord.3gp";
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recordBar = progressBar;
parentActivity =activity;
}
public void startRecording(){
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
public void stopRecording(){
mRecorder.stop();
mRecorder.reset();
mRecorder.release();
mRecorder = null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
startRecording();
}
#Override
protected Void doInBackground(Void... params) {
long secondMillis = System.currentTimeMillis();
while(mLength < MAX_LENGTH){
if((System.currentTimeMillis() - secondMillis) >= 1000){
secondMillis = System.currentTimeMillis();
mLength++;
publishProgress(mLength);
}
}
stopRecording();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
stopRecording();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
recordBar.setProgress(values[0]);
}
#Override
protected void onCancelled(Void aVoid) {
super.onCancelled(aVoid);
stopRecording();
}
#Override
protected void onCancelled() {
super.onCancelled();
stopRecording();
}
}

launching Activity only once(First app use) Using Boolean flags

So i got my firstScreen that i want to be shown just on the first app use.
and i have my mainActivity which will follow the firstScreen.
Im only starting with android and i don't want to use the solutions brought in here: How to launch activity only once when app is opened for first time? AND Can I have an android activity run only on the first time an application is opened? because i dont know SharedPreferrences yet.
So how can i achieve that using Boolean flags?
I have got:boolean firstTimeUse = false; In my firstScreenActivity
And when i start myMainActivity i set the flag to true;
firstTimeUse = true;
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
startActivity(intent);
The problem is the MainActivity doesn't recognize the Boolean variable.
Am i doing it wrong? Or i can still make some modifications and do it with flags?
EDIT
FirstScreen.java:
package com.example.predesignedmails;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class FirstScreen extends AppCompatActivity
{
TextView welcomeTextTextView;
String welcomeText;
ImageButton goToMainImageButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_screen);
viewsInitialization();
welcomeText = "Welcome to Pre Designed Mails.\n"
+ "In here you will have a tons of Emails templates for about every purpose you will need.\n"
+ "Just fill the small details and click Send.\n\n"
+ "Send E-mails fast and efficient!";
welcomeTextTextView.setText(welcomeText);
welcomeTextTextView.setMovementMethod(new ScrollingMovementMethod());
goToMainImageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume()
{
super.onResume();
if (SettingsManager.getBoolean(this, SettingsManager.FIRST_LAUNCH, true))
{
SettingsManager.saveBoolean(this, SettingsManager.FIRST_LAUNCH, false);
// First launch code
Log.d("FirstLaunchCheckUp","First Launch");
}
}
private void viewsInitialization()
{
welcomeTextTextView = (TextView) findViewById(R.id.welcome_text_text_view_id);
goToMainImageButton = (ImageButton) findViewById(R.id.go_to_main_button_id);
}
}
The onResume() method i added manually. It wasn't added automatically when i crated a new activity in Eclipse.
MainActivity.java:
package com.example.predesignedmails;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
{
Button hatefullMailButton;
Button loveMailsButton;
Button welcomeScreenButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.main_activity_background_color)); // Setting background color
viewsInitialization();
hatefullMailButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,HatefulMailsActivity.class);
startActivity(intent);
}
});
loveMailsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,LoveMailsActivity.class);
startActivity(intent);
}
});
welcomeScreenButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,FirstScreen.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
private void viewsInitialization()
{
hatefullMailButton = (Button) findViewById(R.id.hateful_email_button_id);
loveMailsButton = (Button) findViewById(R.id.love_email_button_id);
welcomeScreenButton = (Button) findViewById(R.id.welcome_screen_button_id);
}
}
In your Activity
#Override
protected void onResume() {
super.onResume();
if (SettingsManager.getBoolean(this, SettingsManager.FIRST_LAUNCH, true)){
SettingsManager.saveBoolean(this, SettingsManager.FIRST_LAUNCH, false);
//your first launch code
}
}
SharedPreference helper class
public class SettingsManager
{
public static final String FIRST_LAUNCH= "first_lauch";
public static String getString(Context context, String key, String defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getString(key, defValue);
}
public static int getInt(Context context, String key, int defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getInt(key, defValue);
}
public static boolean getBoolean(Context context, String key, boolean defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(key, defValue);
}
public static void saveString(Context context, String key, String value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).commit();
}
public static void saveInt(Context context, String key, int value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(key, value).commit();
}
public static void saveBoolean(Context context, String key, boolean value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(key, value).commit();
}
}
For the future you can write more simple methods on this SettingsManager, like
public static int getFirstLaunch(Context context) {
return getBoolean(context, FIRST_LAUNCH, true);
}
public static int saveFirstLaunch(Context context, boolean value) {
return saveBoolean(context, FIRST_LAUNCH, value);
}
And use it like
#Override
protected void onResume() {
super.onResume();
if (SettingsManager.getFirstLaunch(this)){
SettingsManager.saveFirstLaunch(this, false);
//your first launch code
}
}
The reason why firstScreen does not recognize boolean firstTimeUse in mainActivity is because it does not yet exist. Only after you have executed the line startActivity(intent) will there exist an object of class mainActivity. Basically, you cannot set a boolean on something that does not yet exist.
Instead, what you can do is pass extra information to an activity that is to be started. When the just-started-activity is initializing itself it can read the extra information and act on it.
So build your intent for the activity you want to start and also set extra information in the 'extras':
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
intent.putExtra("firstTimeUse", true);
startActivity(intent);
Now for your MainActivity to know the value of firstTimeUse it must read the extras:
public class MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstTimeUse = getIntent().getBooleanExtra("firstTimeUse", false);
// do processing dependent on whether it's the first time or not
}
}
This should solve your problem of "the MainActivity doesn't recognize the Boolean variable".

How to keep IOIO connected when android screen goes off?

I am using the following code with IOIO to act as a motion detector, the problem is the IOIO is disconnected whenever my phone screen goes off! I do not want the screen to stay on all the time to keep the IOIO connected!
any solution please?
package com.LookHin.ioio_pir_motion_sensor;
import ioio.lib.api.AnalogInput;
import ioio.lib.api.DigitalOutput;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends IOIOActivity {
private ToggleButton toggleButton1;
private TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_about:
//Toast.makeText(getApplicationContext(), "Show About", Toast.LENGTH_SHORT).show();
Intent about = new Intent(this, AboutActivity.class);
startActivity(about);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class Looper extends BaseIOIOLooper {
private DigitalOutput digital_led0;
private AnalogInput deigital_input;
int i = 0;
private float InputStatus;
#Override
protected void setup() throws ConnectionLostException {
digital_led0 = ioio_.openDigitalOutput(0,true);
deigital_input = ioio_.openAnalogInput(45);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "IOIO Connect", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void loop() throws ConnectionLostException {
try{
digital_led0.write(!toggleButton1.isChecked());
InputStatus = deigital_input.getVoltage();
runOnUiThread(new Runnable() {
#Override
public void run() {
textView1.setText(String.format("%.02f",InputStatus)+" v.");
if(InputStatus >= 3.0){
textView1.setBackgroundColor(Color.RED);
if (i == 0){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
i = 1;
};
}else{
textView1.setBackgroundColor(Color.TRANSPARENT);
i = 0;
}
}
});
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
}
Option 1) Lock the screen so it always stays awake
public void onCreate(Bundle savedInstanceState) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Option 2) Fix your response to onPause().
When the screen goes off the onPause() method is called and you should handle it as otherwise your activity will be closed.
#Override
protected void onPause() {
// Your code
super.onPause();
}
The onPause() normally calls the ioio.disconnect() so this should be overrode.
IOIOService let´s you run your code on the background even if application goes to the background.

Running things outside UI Thread

I am trying to create a simple Android stopwatch application. I was having trouble with the application freezing every time I would hit the start button. I learned from reading various things online that the reason it hangs is that I ran a while loop in the UI thread and in order for the application not to crash, that while loop had to be somewhere different. A post on the XDA forums suggested that someone encountering this problem should use an AsyncTask to accomplish this. I am having trouble understanding exactly how to use AsyncTask to do this.
TL;DR: I am trying to count time and then have it update a textview with the corresponding time
Original code with while loop in UI thread
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity
{
Button start, stop, reset;
TextView time;
boolean timeStopped = false;
long timeInNanoSeconds, startTimeInNanoSeconds;
double timer;
public double getTimeInSeconds()
{
timeInNanoSeconds = System.nanoTime() - startTimeInNanoSeconds;
double timeSeconds = (double) timeInNanoSeconds / 1000000000.0;
double roundOff = Math.round(timeSeconds * 100.0) / 100.0;
return roundOff;
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById(R.id.stopButton);
reset = (Button) findViewById(R.id.resetButton);
time = (TextView) findViewById(R.id.timeField);
start.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
startTimeInNanoSeconds = System.nanoTime();
while(timeStopped == false)
{
double timer = getTimeInSeconds();
String stringTimer = Double.toString(timer);
CharSequence sequenceTimer = stringTimer;
time.setText(sequenceTimer);
}
}
});
stop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
}
});
reset.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
time.setText("");
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
EDIT: Working version using Handler
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button start, stop, reset;
TextView time;
Handler m_handler;
Runnable m_handlerTask;
int timeleft = 0;
boolean timeStopped;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.buttonStart);
stop = (Button) findViewById(R.id.buttonStop);
reset = (Button) findViewById(R.id.buttonReset);
time = (TextView) findViewById(R.id.textTime);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
timeStopped = false;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
public void run() {
if(timeStopped == false){
if(timeleft > -1) {
Log.i("timeleft","" + timeleft);
time.setText(String.valueOf(timeleft));
timeleft++;
}
else{
m_handler.removeCallbacks(m_handlerTask);
}
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeStopped = true;
m_handler.removeCallbacks(m_handlerTask);
}
});
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeStopped = true;
m_handler.removeCallbacks(m_handlerTask);
timeleft = 0;
time.setText(String.valueOf(timeleft));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
doInbackground is invoked on the background thread. you cannot update ui from a background
time.setText(sequenceTimer);
// should be in a ui thread.
Use runOnUithread or setText in onPostExecute.
You can use a Handler , a timer task or a CountDowntimer depending on your requirement.
Android Thread for a timer
Edit:
Using Handler
public class MainActivity extends Activity
{
Button start;
TextView time;
Handler m_handler;
Runnable m_handlerTask ;
int timeleft=100;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.button1);
time = (TextView)findViewById(R.id.textView1);
start.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
if(timeleft>=0)
{
// do stuff
Log.i("timeleft",""+timeleft);
time.setText(String.valueOf(timeleft));
timeleft--;
}
else
{
m_handler.removeCallbacks(m_handlerTask); // cancel run
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
}
});
}
}
In my opinion AsyncTask is not fit for you, as this in my mind is a single shot action.
I would suggest something like this:
private ScheduledExecutorService exec;
private void startExec() {
shutDownExec();
exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleWithFixedDelay(new Runnable() {
#Override
public void run() {
// this starts immediately and is run once every minute
double timer = getTimeInSeconds();
String stringTimer = Double.toString(timer);
CharSequence sequenceTimer = stringTimer;
runOnUiThread(new UpdateUI(R.id.yourtime_textview, sequenceTimer));
}
}, 0, 1, TimeUnit.MINUTES); // adjust how often run() is executed here
}
private void shutDownExec() {
if (exec != null && !exec.isTerminated()) {
exec.shutdown();
}
}
private class UpdateUI implements Runnable {
private String mText;
private TextView mTv;
public UpdateUI(int textviewid, String text) {
this.mTv = (TextView) findViewById(textviewid);
this.mText = text;
}
#Override
public void run() {
mTv.setText(mText);
}
}
I had to do a similar task lately I used created a separate thread with the following code. It lets you update at set time intervals which I think would be suited to your task.
Hope it helps.
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
public class AutomationTreadClass {
Activity refToUIActivity;
//Declare the timer
Timer t = new Timer();
//pass UI activity so you can call update on it
AutomationTreadClass( Activity callingActivity ){
refToUIActivity = callingActivity;
startTimerTread();
}
private void startTimerTread(){
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//do any updates to the time you need to do here
updateLevelMeter();
}
},
//Start Time of thread
0,
//interval of updates
30);
}
private void updateLevelMeter() {
refToUIActivity.runOnUiThread(new Runnable() {
public void run() {
//access what ever UI comment you need to here. like giving you textview a value.
}
});
}
}

Categories

Resources