Please assist, I have the following code that I have tried executing in diffirent places with the following results:
1) When placed in the on create it keeps resetting to 60 seconds
2) When placed in onResume it seems to work perfectly until the play again button is pressed then it starts counting down from the last onPause position
3) When placed in the playAgain method it crashes
Code:
createTimer Method
public void createTimer(){
countDownTimer = new CountDownTimer(timeRemaining, 1000) {
#Override
public void onTick(long l) {
if (!isFinnish) {
timeRemaining = l;
} else {
timeRemaining = 63200;
}
countDownText.setText(String.valueOf(l/1000-60));
if (l <= 61000) {
timerTextView.setText(String.valueOf(l/1000) + "s");
button0.setEnabled(true);
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
button0.setVisibility(View.VISIBLE);
button1.setVisibility(View.VISIBLE);
button2.setVisibility(View.VISIBLE);
button3.setVisibility(View.VISIBLE);
sumTextView.setVisibility(View.VISIBLE);
countDownText.setVisibility(View.INVISIBLE);
}
if (l/1000 == 30){
if (MainActivity.mplayer7 != null) {
MainActivity.mplayer7.release();
MainActivity.mplayer7 = null;
}
MainActivity.mplayer7 = MediaPlayer.create(getApplicationContext(), R.raw.halfway);
if (MainActivity.muted == false) {
MainActivity.mplayer7.setVolume(0.0f, 0.0f);
}
MainActivity.mplayer7.start();
}
if (l/1000 == 5){
if (MainActivity.mplayer != null) {
MainActivity.mplayer.release();
MainActivity.mplayer = null;
}
MainActivity.mplayer = MediaPlayer.create(getApplicationContext(), R.raw.ticktock);
if (MainActivity.muted == false) {
MainActivity.mplayer.setVolume(0.0f, 0.0f);
}
MainActivity.mplayer.start();
}
}
#Override
public void onFinish() {
timerTextView.setText("0s");
timeRemaining = 63200;
isFinnish = true;
//Log.i("Score", String.valueOf(score));
//Log.i("Number of Questions", String.valueOf(numberOfQuestions));
//Log.i("Percentage", String.valueOf(percentage));
//resultTextView.setText("You scored: " + Integer.toString(score) + "/" + Integer.toString(numberOfQuestions));
if (score > 0) {
percentage = score * 100 / numberOfQuestions;
}
else {
percentage = 0;
}
button0.setEnabled(false);
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
playAgainButton.setVisibility(View.VISIBLE);
returnToMenu.setVisibility(View.VISIBLE);
resultDisplayTextView.setVisibility(View.VISIBLE);
resultTextView.setText(" ");
if (percentage > 80) {
resultDisplayTextView.setText("Fantastic Score! " + Integer.toString(percentage) + "%");
if (MainActivity.mplayer3 != null) {
MainActivity.mplayer3.release();
MainActivity.mplayer3 = null;
}
MainActivity.mplayer3 = MediaPlayer.create(getApplicationContext(), R.raw.fireworks);
if (MainActivity.muted == false) {
MainActivity.mplayer3.setVolume(0.0f, 0.0f);
}
MainActivity.mplayer3.start();
}
else if (percentage >= 60 && percentage < 80) {
resultDisplayTextView.setText("Great Score! " + Integer.toString(percentage) + "%");
}
else if (percentage >= 40 && percentage < 60) {
resultDisplayTextView.setText("Average Score! " + Integer.toString(percentage) + "%");
}
else if (percentage > 1 && percentage < 40) {
resultDisplayTextView.setText("Poor Score! " + Integer.toString(percentage) + "%");
if (MainActivity.mplayer4 != null) {
MainActivity.mplayer4.release();
MainActivity.mplayer4 = null;
}
MainActivity.mplayer4 = MediaPlayer.create(getApplicationContext(), R.raw.poor);
if (MainActivity.muted == false) {
MainActivity.mplayer4.setVolume(0.0f, 0.0f);
}
MainActivity.mplayer4.start();
}
else {
resultDisplayTextView.setText("You did not play?");
if (MainActivity.mplayer5 != null) {
MainActivity.mplayer5.release();
MainActivity.mplayer5 = null;
}
MainActivity.mplayer5 = MediaPlayer.create(getApplicationContext(), R.raw.poor);
if (MainActivity.muted == false) {
MainActivity.mplayer5.setVolume(0.0f, 0.0f);
}
MainActivity.mplayer5.start();
}
}
};
}
playAgain Method
public void playAgain (View view) {
score = 0;
isFinnish = false;
numberOfQuestions = 0;
timerTextView.setText("60s");
pointsTextView.setText("0/0");
resultTextView.setText("");
playAgainButton.setVisibility(View.INVISIBLE);
returnToMenu.setVisibility(View.INVISIBLE);
resultDisplayTextView.setVisibility(View.INVISIBLE);
countDownText.setVisibility(View.VISIBLE);
button0.setVisibility(View.INVISIBLE);
button1.setVisibility(View.INVISIBLE);
button2.setVisibility(View.INVISIBLE);
button3.setVisibility(View.INVISIBLE);
sumTextView.setVisibility(View.INVISIBLE);
if (MainActivity.mplayer3 != null) {
MainActivity.mplayer3.release();
MainActivity.mplayer3 = null;
}
if (MainActivity.mplayer4 != null) {
MainActivity.mplayer4.release();
MainActivity.mplayer4 = null;
}
if (MainActivity.mplayer6 != null) {
MainActivity.mplayer6.release();
MainActivity.mplayer6 = null;
}
MainActivity.mplayer6 = MediaPlayer.create(getApplicationContext(), R.raw.countdown);
if (MainActivity.muted == false) {
MainActivity.mplayer6.setVolume(0.0f, 0.0f);
}
MainActivity.mplayer6.start();
countDownTimer.start();
generateQuestion();
}
onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
createTimer();
// THIS CODE IS TO ENABLE THE ICON IN THE TASKBAR ////////////////////
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
//////////////////////////////////////////////////////////////////////
// SET IT TO ONLY POTRAIT VIEW
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Intent intent = getIntent();
countDownText = (TextView) findViewById(R.id.countDownText);
playAgainButton = (Button) findViewById(R.id.playAgainButton);
returnToMenu = (Button) findViewById(R.id.returnToMenu);
sumTextView = (TextView) findViewById(R.id.sumTextView);
resultTextView = (TextView) findViewById(R.id.resultTextView);
resultDisplayTextView = (TextView) findViewById(R.id.resultDisplayTextView);
pointsTextView = (TextView) findViewById(R.id.pointsTextView);
timerTextView = (TextView) findViewById(R.id.timerTextView);
linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);
button0 = (Button) findViewById(R.id.button0);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
MainActivity.mAdView = (AdView) findViewById(R.id.adView);
MainActivity.mplayer = MediaPlayer.create(getApplicationContext(), R.raw.ticktock);
MainActivity.mplayer1 = MediaPlayer.create(getApplicationContext(), R.raw.pop);
MainActivity.mplayer2 = MediaPlayer.create(getApplicationContext(), R.raw.wrong);
MainActivity.mplayer3 = MediaPlayer.create(getApplicationContext(), R.raw.fireworks);
MainActivity.mplayer4 = MediaPlayer.create(getApplicationContext(), R.raw.poor);
MainActivity.mplayer5 = MediaPlayer.create(getApplicationContext(), R.raw.poor);
MainActivity.mplayer6 = MediaPlayer.create(getApplicationContext(), R.raw.countdown);
MainActivity.mplayer7 = MediaPlayer.create(getApplicationContext(), R.raw.halfway);
if (MainActivity.muted == false) {
MainActivity.mplayer.setVolume(0.0f, 0.0f);
MainActivity.mplayer1.setVolume(0.0f, 0.0f);
MainActivity.mplayer2.setVolume(0.0f, 0.0f);
MainActivity.mplayer3.setVolume(0.0f, 0.0f);
MainActivity.mplayer4.setVolume(0.0f, 0.0f);
MainActivity.mplayer5.setVolume(0.0f, 0.0f);
MainActivity.mplayer6.setVolume(0.0f, 0.0f);
MainActivity.mplayer7.setVolume(0.0f, 0.0f);
}
MainActivity.displayAds();
mHandler.postDelayed(new Runnable() {
public void run() {
playAgain(playAgainButton);
}
}, 1000);
}
onResume and onPause
#Override
public void onResume() {
super.onResume();
countDownTimer.start();
if (MainActivity.mAdView != null) {
MainActivity.mAdView.resume();
}
}
#Override
public void onPause() {
countDownTimer.cancel();
if (MainActivity.mAdView != null) {
MainActivity.mAdView.pause();
}
super.onPause();
}
I have the global var set and assumed that resetting it in the onFinnish within the countdown timer should reset it but it does not.
Thanks
Fields (what you called Global vars) are are not guranteed to be restored on activity recreation and can be GC anytime. You should rather create var in on create, store them in Bundle onPouse and again recreate them from that Bundle in another onCreate or onResume methods.
Here you have Google Dev's docs about how to handle activity creation, recreation and finalization https://developer.android.com/training/basics/activity-lifecycle/recreating.html
So basicly 1) it resets to 60 secs because it is recreated everytime you get back to your activity (from diffrerent app aor different activity)
2) idk where is your "play again" thing and I am not going to go into that code
3) countDownTimer.start(); probably here it crashes with NPE am i right? (I am reading my crystall ball right now)
Read the full Google's tutorial about acitivity lifecycle and you wont have any troubles fixing your code.
https://developer.android.com/training/basics/activity-lifecycle/index.html
Related
I need help with this, I made this calculator, and a progressbar , i need it to when its finish so i can click again and run again, i didnt found a way to do that, and do the same with anothr data or the same data as well
private TextView textResultado;
private TextView editpeso;
private TextView editaltura;
private Button botao;
private ProgressBar pb;
private TextView txt;
int i = 0;
Handler handler = new Handler();
String[] mensagens = {"Preencha todos os campos!"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
iniciar();
botao.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pb.setVisibility(View.VISIBLE);
String peso = editpeso.getText().toString();
String altura = editaltura.getText().toString();
if (peso.isEmpty() || altura.isEmpty()) {
Snackbar snackbar = Snackbar.make(view, mensagens[0], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(getResources().getColor(R.color.white));
snackbar.setTextColor(getResources().getColor(R.color.black));
snackbar.show();
}
new Thread(new Runnable() {
#Override
public void run() {calculadoramm(view);
while (i < 100) {
i += 1;
try {
Thread.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
pb.setProgress(i);
txt.setText(i + "% Verificando...");
if (i == pb.getMax())
Toast.makeText(MainActivity.this, "Completo!", Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}
});
}
private void iniciar() {
textResultado = findViewById(R.id.textResultado);
editpeso = findViewById(R.id.editpeso);
editaltura = findViewById(R.id.editaltura);
botao = (Button) findViewById(R.id.botao);
pb = (ProgressBar) findViewById(R.id.pb);
txt = (TextView) findViewById(R.id.txt);
}
public void calculadoramm(View view) {
double peso = Double.parseDouble(editpeso.getText().toString());
double altura = Double.parseDouble(editaltura.getText().toString());
double resultado = peso / (altura * altura);
//Se
if (resultado <= 18.5) {
textResultado.setText("Abaixo do Peso!");
textResultado.setTextColor(getResources().getColor(android.R.color.holo_blue_bright));
}
if (resultado <= 18.5 || resultado >= 24.9) {
textResultado.setText("Peso normal!");
textResultado.setTextColor(getResources().getColor(android.R.color.holo_green_light));
}
if (resultado <= 25 || resultado >= 29.9) {
textResultado.setText("Excesso de peso!");
textResultado.setTextColor(getResources().getColor(android.R.color.holo_green_light));
if (resultado <= 30 || resultado >= 34.9) {
textResultado.setText("Obesidade nivel I!");
textResultado.setTextColor(getResources().getColor(android.R.color.holo_orange_light));
if (resultado <= 35 || resultado >= 39.9) {
textResultado.setText("Obesidade nivel II!");
textResultado.setTextColor(getResources().getColor(android.R.color.holo_red_light));
if (resultado >= 40) {
textResultado.setText("Obesidade nivel III ou Morbida!");
textResultado.setTextColor(getResources().getColor(android.R.color.holo_red_light));
}
}
}
}
}
}
I've tried to add an Intent to start activity from Main to my results and None seems to work, and updated the code
I added my application to Github to find my bug.
So the bug is like when I open my app for a first time and open "info" then "settings" and click thought all options, then "new measurement" then it goes to previous screen (settings) instead of new measurement. Could anybody help me?
Here is the link to app
Edit:
Here are probably the meaningfull classes:
Stages.java
public class Stages extends BaseActivity {
private final Stage0StageFragment stageZeroFragment = new Stage0StageFragment();
private final Stage1StageFragment stageOneFragment = new Stage1StageFragment();
private final Stage2StageFragment stageTwoFragment = new Stage2StageFragment();
private final Stage3StageFragment stageThreeFragment = new Stage3StageFragment();
private BottomNavigationView bottomNavView;
private int startingPosition, newPosition;
OnSwitchFragmentFromStageTwo onSwitchFragmentFromStageTwo;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Util.setThemeBasedOnPrefs(this);
setContentView(R.layout.stages);
spEditor.putBoolean("wantToClosePxCmInfo", false).apply();
bottomNavView = findViewById(R.id.bottom_navigation);
bottomNavView.setItemIconTintList(null);
bottomNavView.setOnNavigationItemSelectedListener(item -> {
if (bottomNavView.getSelectedItemId() == R.id.navigation_stage_zero) {
if (!sp.getBoolean("correctionDone", false)) {
AlertDialog alertDialog = Util.createAlertDialog(Stages.this, android.R.drawable.ic_dialog_info, R.string.hide_dialog_title, getString(R.string.stage_zero_confirmation), (dialog, which) -> {
spEditor.putBoolean("correctionDone", true).apply();
bottomNavView.setSelectedItemId(item.getItemId());
showFragment(item.getItemId());
});
alertDialog.setOnShowListener(arg0 -> setAlertDialogButtonsAttributes(alertDialog));
alertDialog.show();
return false;
} else {
showFragment(item.getItemId());
return true;
}
} else if (bottomNavView.getSelectedItemId() == R.id.navigation_stage_two) {
try {
if (onSwitchFragmentFromStageTwo.onSwitchFragmentFromFragmentTwo() <= 0.5 && !sp.getBoolean("wantToClosePxCmInfo", false)) {
AlertDialog ad = Util.createAlertDialog(Stages.this, android.R.drawable.ic_dialog_alert, R.string.hide_dialog_title_alert,
getResources().getString(R.string.benchmark_not_drawn), (dialog, which) -> {
spEditor.putBoolean("wantToClosePxCmInfo", true).apply();
bottomNavView.setSelectedItemId(item.getItemId());
showFragment(item.getItemId());
});
ad.setOnShowListener(arg0 -> setAlertDialogButtonsAttributes(ad));
ad.show();
return false;
} else {
showFragment(item.getItemId());
return true;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
} else {
showFragment(item.getItemId());
}
return true;
});
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (!sp.getBoolean("correctionDone", false))
ft.replace(R.id.content_frame, stageZeroFragment);
else {
ft.replace(R.id.content_frame, stageOneFragment);
bottomNavView.setSelectedItemId(R.id.navigation_stage_one);
}
ft.commit();
}
#Override
BaseActivity getActivity() {
return this;
}
private void setAlertDialogButtonsAttributes(AlertDialog alertDialog2) {
alertDialog2.getButton(DialogInterface.BUTTON_NEGATIVE).setBackground(AppCompatResources.getDrawable(this, R.drawable.button_selector));
alertDialog2.getButton(DialogInterface.BUTTON_POSITIVE).setBackground(AppCompatResources.getDrawable(this, R.drawable.button_selector));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
1.0f
);
params.setMargins(10, 0, 10, 0);
alertDialog2.getButton(DialogInterface.BUTTON_NEGATIVE).setLayoutParams(params);
alertDialog2.getButton(DialogInterface.BUTTON_POSITIVE).setLayoutParams(params);
}
public void showFragment(int viewId) {
Fragment fragment = null;
switch (viewId) {
case R.id.navigation_stage_zero:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_zero) {
fragment = stageZeroFragment;
newPosition = 0;
}
break;
case R.id.navigation_stage_one:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_one) {
fragment = stageOneFragment;
newPosition = 1;
}
break;
case R.id.navigation_stage_two:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_two) {
fragment = stageTwoFragment;
newPosition = 2;
}
break;
case R.id.navigation_stage_three:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_three) {
fragment = stageThreeFragment;
newPosition = 3;
}
break;
}
if (fragment != null) {
if (startingPosition > newPosition) {
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right)
.replace(R.id.content_frame, fragment).commit();
}
if (startingPosition < newPosition) {
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
.replace(R.id.content_frame, fragment).commit();
}
startingPosition = newPosition;
}
}
}
Stage0StageFragment.java
public class Stage0StageFragment extends AbstractStageFragment {
private CheckBox checkboxSkip;
private int xCorrection, yCorrection;
private IndicatorSeekBar indicatorSeekBar;
private IndicatorSeekBar indicatorSeekBar2;
private AlertDialog alertDialog;
#Override
int getLayout() {
return R.layout.stage_zero;
}
#Override
public void onResume() {
super.onResume();
new CameraOpenerTask(this).execute();
}
#Override
public void onPause() {
super.onPause();
spEditor.putInt("indicator1", indicatorSeekBar.getProgress());
spEditor.putInt("indicator2", indicatorSeekBar2.getProgress());
spEditor.apply();
if (alertDialog.isShowing())
alertDialog.dismiss();
}
#Override
#SuppressLint({"ClickableViewAccessibility", "CommitPrefEdits"})
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setOnTouchListener((v, event) -> {
int aktX = (int) event.getX();
int aktY = (int) event.getY();
setParamsToDrawRectangle(aktX, aktY);
return true;
});
configureSeekBars(view);
configureInitDialog();
}
#Override
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
Imgproc.cvtColor(inputFrame.rgba(), mRgba, Imgproc.COLOR_RGBA2RGB, 1);
Core.transpose(mGray, mGray);
Core.flip(mGray, mGray, -1);
Imgproc.line(mRgba, p1, p2, Util.BLUE);
Imgproc.line(mRgba, p3, p4, Util.BLUE);
Imgproc.rectangle(mRgba, new Point(touchedYD, touchedXL), new Point(touchedYU, touchedXR), Util.WHITE, 2);
return mRgba;
}
private void setParamsToDrawRectangle(int aktX, int aktY) {
// poziomo
if (-aktX + camLayHeight + (xCorrection * 10) < (camLayHeight / 2)) {
touchedXR = -aktX + camLayHeight + (xCorrection * 10);
if (touchedXR < 0) touchedXR = 0;
} else {
touchedXL = -aktX + camLayHeight + (xCorrection * 10);
if (touchedXL > camLayHeight) touchedXL = camLayHeight;
}
// pionowo
if (aktY - (yCorrection * 10) < (camLayWidth / 2)) {
touchedYU = aktY - (yCorrection * 10);
if (touchedYU < 0) touchedYU = 0;
} else {
touchedYD = aktY - (yCorrection * 10);
if (touchedYD > camLayWidth) touchedYD = camLayWidth;
}
}
public void configureSeekBars(View view) {
indicatorSeekBar = view.findViewById(R.id.percent_indicator);
indicatorSeekBar.setOnSeekChangeListener(new MyOnSeekChangeListener("x"));
indicatorSeekBar2 = view.findViewById(R.id.percent_indicator2);
indicatorSeekBar2.setOnSeekChangeListener(new MyOnSeekChangeListener("y"));
TextView tv = view.findViewById(R.id.info_about_indicators);
if (sp.getInt("indicator1", 0) != 0)
indicatorSeekBar.setProgress(sp.getInt("indicator1", 0));
if (sp.getInt("indicator2", 0) != 0)
indicatorSeekBar2.setProgress(sp.getInt("indicator2", 0));
if (sp.getInt("indicator1", 0) != 0 || sp.getInt("indicator2", 0) != 0)
tv.setVisibility(View.VISIBLE);
}
public void setScrollViewParamsDependingOnFont(View checkboxLayout) {
ScrollView layout = checkboxLayout.findViewById(R.id.scrollView);
ViewGroup.LayoutParams params = layout.getLayoutParams();
String fontPref = sp.getString("font", "Arial");
if (fontPref.equals("Ginger"))
params.height = (int) getResources().getDimension(R.dimen.height_of_checkbox);
if (fontPref.equals("Arial")) params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
layout.setLayoutParams(params);
}
void configureInitDialog() {
View checkboxLayout = View.inflate(getActivity(), R.layout.checkbox, null);
setScrollViewParamsDependingOnFont(checkboxLayout);
alertDialog = new AlertDialog.Builder(getActivity(), R.style.MyStyle).create();
alertDialog.setView(checkboxLayout);
alertDialog.setIcon(android.R.drawable.ic_dialog_info);
alertDialog.setTitle("Info");
alertDialog.setMessage(getResources().getString(R.string.stage_zero_dialog));
alertDialog.setCancelable(false);
alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "Ok", (dialogInterface, i) -> {
String checkBoxResult = "";
checkboxSkip = checkboxLayout.findViewById(R.id.checkboxSkip);
if (checkboxSkip.isChecked())
checkBoxResult = "linia2";
if (checkBoxResult.equals("linia2"))
spEditor.putBoolean("hideDialog", true).apply();
});
alertDialog.setOnShowListener(arg0 -> alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL).setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_selector, null)));
if (!sp.getBoolean("hideDialog", false))
alertDialog.show();
}
public class MyOnSeekChangeListener implements OnSeekChangeListener {
private final String axisCorrection;
MyOnSeekChangeListener(String axisCorrection) {
this.axisCorrection = axisCorrection;
}
#Override
public void onSeeking(SeekParams seekParams) {
if (axisCorrection.equals("x"))
xCorrection = seekParams.progress;
if (axisCorrection.equals("y"))
yCorrection = seekParams.progress;
spEditor.putInt("xCorrection", xCorrection);
spEditor.putInt("yCorrection", yCorrection);
spEditor.apply();
}
#Override
public void onStartTrackingTouch(IndicatorSeekBar indicatorSeekBar) {
}
#Override
public void onStopTrackingTouch(IndicatorSeekBar indicatorSeekBar) {
}
}
Something wrong happen in those classes probably when opening "new measurement".
I'm trying to make a compass and want to print out the current location in a Textview. However, when I do that it gives me the latitude and longitude for Tehran (Iran) which isn't correct.
public class Kompas extends AppCompatActivity implements AnimationListener,
OnSharedPreferenceChangeListener, ConstantUtilInterface {
private boolean faceUp = true;
private boolean gpsLocationFound = true;
private String location_line2 = "";
public Location currentLocation = null;
private double lastTargetAngle = 0;
private double lastNorthAngle = 0;
private double lastTargetAngleFromN = 0;
// This animation is used to rotate north and target images
private RotateAnimation animation;
private ImageView compassImageView;
private ImageView locationImageView;
private final LocationCompassManager locationCompassManager = new LocationCompassManager(this);
private boolean angleSignaled = false;
private Timer timer = null;
private SharedPreferences perfs;
public boolean isRegistered = false;
public boolean isGPSRegistered = false;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message message) {
if (message.what == ROTATE_IMAGES_MESSAGE) {
Bundle bundle = message.getData();
boolean isTargetChanged = bundle.getBoolean(IS_TARGET_CHANGED);
boolean isCompassChanged = bundle
.getBoolean(IS_COMPASS_CHANGED);
double targetNewAngle = 0;
double compassNewAngle = 0;
if (isTargetChanged)
targetNewAngle = (Double) bundle.get(TARGET_BUNDLE_DELTA_KEY);
if (isCompassChanged) {
compassNewAngle = (Double) bundle
.get(COMPASS_BUNDLE_DELTA_KEY);
}
// This
syncTargetAndNorthArrow(compassNewAngle, targetNewAngle,
isCompassChanged, isTargetChanged);
angleSignaled = false;
}
}
};
public void setLocationText(String textToShow) {
this.location_line2 = textToShow;
}
private TimerTask getTimerTask() {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
if (angleSignaled && !ConcurrencyUtil.isAnyAnimationOnRun()) {
// numAnimationOnRun += 2;
Map<String, Double> newAnglesMap = locationCompassManager
.fetchDeltaAngles();
Double newNorthAngle = newAnglesMap
.get(LocationCompassManager.NORTH_CHANGED_MAP_KEY);
Double newTargetAngle = newAnglesMap
.get(LocationCompassManager.TARGET_CHANGED_MAP_KEY);
Message message = mHandler.obtainMessage();
message.what = ROTATE_IMAGES_MESSAGE;
Bundle b = new Bundle();
if (newNorthAngle == null) {
b.putBoolean(IS_COMPASS_CHANGED, false);
} else {
ConcurrencyUtil.incrementAnimation();
b.putBoolean(IS_COMPASS_CHANGED, true);
b.putDouble(COMPASS_BUNDLE_DELTA_KEY, newNorthAngle);
}
if (newTargetAngle == null) {
b.putBoolean(IS_TARGET_CHANGED, false);
} else {
ConcurrencyUtil.incrementAnimation();
b.putBoolean(IS_TARGET_CHANGED, true);
b.putDouble(TARGET_BUNDLE_DELTA_KEY, newTargetAngle);
}
message.setData(b);
mHandler.sendMessage(message);
} else if (ConcurrencyUtil.getNumAimationsOnRun() < 0) {
}
}
};
return timerTask;
}
private void schedule() {
if (timer == null) {
timer = new Timer();
this.timer.schedule(getTimerTask(), 0, 200);
} else {
timer.cancel();
timer = new Timer();
timer.schedule(getTimerTask(), 0, 200);
}
}
private void cancelSchedule() {
if (timer == null)
return;
// timer.cancel();
}
private void onInvalidateLocation(String message) {
}
private void requestForValidationOfLocation() {
// TextView textView = (TextView)
// findViewById(R.id.location_text_line1);
TextView textView2 = (TextView) findViewById(R.id.location_text_line2);
ImageView arrow = ((ImageView) findViewById(R.id.arrowImage));
ImageView compass = ((ImageView) findViewById(R.id.compassImage));
ImageView frame = ((ImageView) findViewById(R.id.frameImage));
FrameLayout targetFrame = ((FrameLayout) findViewById(R.id.targetLayout));
LinearLayout noLocationLayout = ((LinearLayout) findViewById(R.id.noLocationLayout));
if (faceUp && (gpsLocationFound || currentLocation != null)) {
textView2.setVisibility(View.VISIBLE);
textView2.setText(location_line2);
((LinearLayout) findViewById(R.id.textLayout))
.setVisibility(View.VISIBLE);
noLocationLayout.setVisibility(View.INVISIBLE);
targetFrame.setVisibility(View.VISIBLE);
arrow.setVisibility(View.VISIBLE);
compass.setVisibility(View.VISIBLE);
frame.setVisibility(View.VISIBLE);
} else {
if (!faceUp) {
onScreenDown();
} else if (!(gpsLocationFound || currentLocation != null)) {
onGPSOn();
}
}
}
private void onGPSOn() {
gpsLocationFound = false;
onInvalidateLocation(getString(R.string.no_location_yet));
}
public void onScreenDown() {
faceUp = false;
onInvalidateLocation(getString(R.string.screen_down_text));
}
public void onScreenUp() {
faceUp = true;
requestForValidationOfLocation();
}
public void onNewLocationFromGPS(Location location) {
gpsLocationFound = true;
currentLocation = location;
requestForValidationOfLocation();
}
private void onGPSOff(Location defaultLocation) {
currentLocation = defaultLocation;
gpsLocationFound = false;
requestForValidationOfLocation();
}
private String getLocationForPrint(double latitude, double longitude) {
int latDegree = (new Double(Math.floor(latitude))).intValue();
int longDegree = (new Double(Math.floor(longitude))).intValue();
String latEnd = getString(R.string.latitude_south);
String longEnd = getString(R.string.longitude_west);
if (latDegree > 0) {
latEnd = getString(R.string.latitude_north);
}
if (longDegree > 0) {
longEnd = getString(R.string.longitude_east);
}
double latSecond = (latitude - latDegree) * 100;
double latMinDouble = (latSecond * 3d / 5d);
int latMinute = new Double(Math.floor(latMinDouble)).intValue();
double longSecond = (longitude - longDegree) * 100;
double longMinDouble = (longSecond * 3d / 5d);
int longMinute = new Double(Math.floor(longMinDouble)).intValue();
return String.format(getString(R.string.geo_location_info), latDegree,
latMinute, latEnd, longDegree, longMinute, longEnd);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kompas);
registerListeners();
Context context = getApplicationContext();
perfs = PreferenceManager.getDefaultSharedPreferences(context);
perfs.registerOnSharedPreferenceChangeListener(this);
String gpsPerfKey = getString(R.string.gps_pref_key);
TextView text1 = (TextView) findViewById(R.id.location_text_line2);
TextView text2 = (TextView) findViewById(R.id.noLocationText);
getLocationName(currentLocation.getLatitude(), currentLocation.getLongitude());
getSupportActionBar().setTitle("Qiblah");
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8b4513")));
boolean isGPS = false;
try {
isGPS = Boolean.parseBoolean(perfs.getString(gpsPerfKey, "false"));
} catch (ClassCastException e) {
isGPS = perfs.getBoolean(gpsPerfKey, false);
}
if (!isGPS) {
unregisterForGPS();
useDefaultLocation(perfs,
getString(R.string.state_location_pref_key));
} else {
registerForGPS();
onGPSOn();
}
this.locationImageView = (ImageView) findViewById(R.id.arrowImage);
this.compassImageView = (ImageView) findViewById(R.id.compassImage);
}
private void unregisterListeners() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
((LocationManager) getSystemService(Context.LOCATION_SERVICE))
.removeUpdates(locationCompassManager);
((LocationManager) getSystemService(Context.LOCATION_SERVICE))
.removeUpdates(locationCompassManager);
SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor gsensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor msensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.unregisterListener(locationCompassManager, gsensor);
mSensorManager.unregisterListener(locationCompassManager, msensor);
cancelSchedule();
}
public void getLocationName(double lattitude, double longitude) {
}
private void registerForGPS() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
LocationManager locationManager = ((LocationManager) getSystemService(Context.LOCATION_SERVICE));
String provider = locationManager.getBestProvider(criteria, true);
if (provider != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(provider, MIN_LOCATION_TIME,
MIN_LOCATION_DISTANCE, locationCompassManager);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_LOCATION_TIME, MIN_LOCATION_DISTANCE, locationCompassManager);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, MIN_LOCATION_TIME,
MIN_LOCATION_DISTANCE, locationCompassManager);
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
location = ((LocationManager) getSystemService(Context.LOCATION_SERVICE))
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if (location != null) {
locationCompassManager.onLocationChanged(location);
}
}
private void unregisterForGPS() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
((LocationManager) getSystemService(Context.LOCATION_SERVICE))
.removeUpdates(locationCompassManager);
}
private void registerListeners() {
SharedPreferences perfs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
if (perfs.getBoolean(getString(R.string.gps_pref_key), false)) {
registerForGPS();
} else {
useDefaultLocation(perfs,
getString(R.string.state_location_pref_key));
}
SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor gsensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor msensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(locationCompassManager, gsensor,
SensorManager.SENSOR_DELAY_GAME);
mSensorManager.registerListener(locationCompassManager, msensor,
SensorManager.SENSOR_DELAY_GAME);
schedule();
isRegistered = true;
}
#Override
protected void onResume() {
super.onResume();
registerListeners();
}
#Override
protected void onPause() {
super.onPause();
ConcurrencyUtil.setToZero();
ConcurrencyUtil.directionChangedLock.readLock();
unregisterListeners();
}
public void syncTargetAndNorthArrow(double northNewAngle,
double targetNewAngle, boolean northChanged, boolean targetChanged) {
if (northChanged) {
lastNorthAngle = rotateImageView(northNewAngle, lastNorthAngle,
compassImageView);
if (targetChanged == false && targetNewAngle != 0) {
lastTargetAngleFromN = targetNewAngle;
lastTargetAngle = rotateImageView(targetNewAngle + northNewAngle,
lastTargetAngle, locationImageView);
} else if (targetChanged == false && targetNewAngle == 0)
lastTargetAngle = rotateImageView(lastTargetAngleFromN
+ northNewAngle, lastTargetAngle, locationImageView);
}
if (targetChanged) {
lastTargetAngleFromN = targetNewAngle;
lastTargetAngle = rotateImageView(targetNewAngle + lastNorthAngle,
lastTargetAngle, locationImageView);
}
}
private double rotateImageView(double newAngle, double fromDegree,
ImageView imageView) {
newAngle = newAngle % 360;
double rotationDegree = fromDegree - newAngle;
rotationDegree = rotationDegree % 360;
long duration = new Double(Math.abs(rotationDegree) * 2000 / 360)
.longValue();
if (rotationDegree > 180)
rotationDegree -= 360;
FrameLayout frameLayout = (FrameLayout) findViewById(R.id.targetLayout);
float toDegree = new Double(newAngle % 360).floatValue();
final int width = Math.abs(frameLayout.getRight()
- frameLayout.getLeft());
final int height = Math.abs(frameLayout.getBottom()
- frameLayout.getTop());
LinearLayout main = (LinearLayout) findViewById(R.id.mainLayout);
float pivotX = width / 2f;
float pivotY = height / 2f;
animation = new RotateAnimation(new Double(fromDegree).floatValue(),
toDegree, pivotX, pivotY);
animation.setRepeatCount(0);
animation.setDuration(duration);
animation.setInterpolator(new LinearInterpolator());
animation.setFillEnabled(true);
animation.setFillAfter(true);
animation.setAnimationListener(this);
imageView.startAnimation(animation);
return toDegree;
}
public void signalForAngleChange() {
this.angleSignaled = true;
}
public void onAnimationEnd(Animation animation) {
if (ConcurrencyUtil.getNumAimationsOnRun() <= 0) {
} else {
ConcurrencyUtil.decrementAnimation();
}
schedule();
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationStart(Animation animation) {
cancelSchedule();
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
String gpsPerfKey = getString(R.string.gps_pref_key);
String defaultLocationPerfKey = getString(R.string.state_location_pref_key);
if (gpsPerfKey.equals(key)) {
boolean isGPS = false;
try {
isGPS = Boolean.parseBoolean(sharedPreferences.getString(key,
"false"));
} catch (ClassCastException e) {
isGPS = sharedPreferences.getBoolean(key, false);
}
if (isGPS) {
registerForGPS();
currentLocation = null;
onGPSOn();
} else {
useDefaultLocation(sharedPreferences, defaultLocationPerfKey);
unregisterForGPS();
}
} else if (defaultLocationPerfKey.equals(key)) {
sharedPreferences.edit().putBoolean(gpsPerfKey, false);
sharedPreferences.edit().commit();
unregisterForGPS();
useDefaultLocation(sharedPreferences, key);
}
}
private void useDefaultLocation(SharedPreferences perfs, String key) {
int defLocationID = Integer.parseInt(perfs.getString(key, ""
+ LocationEnum.MENU_TEHRAN.getId()));
LocationEnum locationEnum = LocationEnum.values()[defLocationID - 1];
Location location = locationEnum.getLocation();
locationCompassManager.onLocationChanged(location);
onGPSOff(location);
}
#Override
public void onBackPressed() {
finish();
}
}
The way I found out was that I printed out the city name and the latitude/longitude and they gave me Tehran. I've written the correct permissions in the Manifest, and the GPS/Location is turned on, on my device
You want to implement an so called DEG to DMS conversion (decimal degrees to Degrees minutes, seconds).
Your formula seems to be wrong:
Especially the longSecond * 3d / 5d);
For correct formula look at the first lines of:
https://en.wikipedia.org/wiki/Geographic_coordinate_conversion
How can I put the result of the QR "SCAN_RESULT" in different activity, this is my problem.
In the splash screen I need to go to the QRScanner (CaptureActivity), and then, to the ActivityQR who will send the info. to the SQLite.
The problem is: When I get de QRCode in string ("SCAN_RESULT") on "CaptureActivity.java", the app close because the app need "back" to the previous activity with this:
getIntent();
I try to modify this codeline, but this not solve my problem.
How can I put the "SCAN_RESULT" in the ActivityQR? I don't know how open other activity (this case ActivityQR) when the code had gottenm and put this String value on the ActivityQR
I Use "CaptureActivity" of ZXing (ZebraCrossing)
Thanks in advance.
SplashScreen.java :
{
Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, com.google.zxing.client.android.CaptureActivity.class);
startActivity(mainIntent)
}
ActivityQR.java
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(REQUEST_CODE == requestCode && RESULT_OK == resultCode){
txResult.setText(data.getStringExtra("SCAN_RESULT"));
}
}
CaptureActivity.java
public class CaptureActivity extends Activity implements SurfaceHolder.Callback {
private static final String TAG = CaptureActivity.class.getSimpleName();
private static final long DEFAULT_INTENT_RESULT_DURATION_MS = 1500L;
private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;
private static final String[] ZXING_URLS = { "http://zxing.appspot.com/scan", "zxing://scan/" };
public static final int HISTORY_REQUEST_CODE = 0x0000bacc;
private static final Collection<ResultMetadataType> DISPLAYABLE_METADATA_TYPES =
EnumSet.of(ResultMetadataType.ISSUE_NUMBER,
ResultMetadataType.SUGGESTED_PRICE,
ResultMetadataType.ERROR_CORRECTION_LEVEL,
ResultMetadataType.POSSIBLE_COUNTRY);
private CameraManager cameraManager;
private CaptureActivityHandler handler;
private Result savedResultToShow;
private ViewfinderView viewfinderView;
private TextView statusView;
private View resultView;
private Result lastResult;
private boolean hasSurface;
private boolean copyToClipboard;
private IntentSource source;
private String sourceUrl;
private ScanFromWebPageManager scanFromWebPageManager;
private Collection<BarcodeFormat> decodeFormats;
private Map<DecodeHintType,?> decodeHints;
private String characterSet;
private HistoryManager historyManager;
private InactivityTimer inactivityTimer;
private BeepManager beepManager;
private AmbientLightManager ambientLightManager;
ViewfinderView getViewfinderView() {
return viewfinderView;
}
public Handler getHandler() {
return handler;
}
CameraManager getCameraManager() {
return cameraManager;
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.capture);
hasSurface = false;
historyManager = new HistoryManager(this);
historyManager.trimHistory();
inactivityTimer = new InactivityTimer(this);
beepManager = new BeepManager(this);
ambientLightManager = new AmbientLightManager(this);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
}
#Override
protected void onResume() {
super.onResume();
// CameraManager must be initialized here, not in onCreate(). This is necessary because we don't
// want to open the camera driver and measure the screen size if we're going to show the help on
// first launch. That led to bugs where the scanning rectangle was the wrong size and partially
// off screen.
cameraManager = new CameraManager(getApplication());
viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
viewfinderView.setCameraManager(cameraManager);
resultView = findViewById(R.id.result_view);
statusView = (TextView) findViewById(R.id.status_view);
handler = null;
lastResult = null;
resetStatusView();
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
if (hasSurface) {
// The activity was paused but not stopped, so the surface still exists. Therefore
// surfaceCreated() won't be called, so init the camera here.
initCamera(surfaceHolder);
} else {
// Install the callback and wait for surfaceCreated() to init the camera.
surfaceHolder.addCallback(this);
}
beepManager.updatePrefs();
ambientLightManager.start(cameraManager);
inactivityTimer.onResume();
Intent intent = getIntent();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
&& (intent == null || intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));
source = IntentSource.NONE;
decodeFormats = null;
characterSet = null;
if (intent != null) {
String action = intent.getAction();
String dataString = intent.getDataString();
if (Intents.Scan.ACTION.equals(action)) {
// Scan the formats the intent requested, and return the result to the calling activity.
source = IntentSource.NATIVE_APP_INTENT;
decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
decodeHints = DecodeHintManager.parseDecodeHints(intent);
if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
if (width > 0 && height > 0) {
cameraManager.setManualFramingRect(width, height);
}
}
String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
if (customPromptMessage != null) {
statusView.setText(customPromptMessage);
}
} else if (dataString != null &&
dataString.contains("http://www.google") &&
dataString.contains("/m/products/scan")) {
// Scan only products and send the result to mobile Product Search.
source = IntentSource.PRODUCT_SEARCH_LINK;
sourceUrl = dataString;
decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
} else if (isZXingURL(dataString)) {
// Scan formats requested in query string (all formats if none specified).
// If a return URL is specified, send the results there. Otherwise, handle it ourselves.
source = IntentSource.ZXING_LINK;
sourceUrl = dataString;
Uri inputUri = Uri.parse(dataString);
scanFromWebPageManager = new ScanFromWebPageManager(inputUri);
decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);
// Allow a sub-set of the hints to be specified by the caller.
decodeHints = DecodeHintManager.parseDecodeHints(inputUri);
}
characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
}
}
private static boolean isZXingURL(String dataString) {
if (dataString == null) {
return false;
}
for (String url : ZXING_URLS) {
if (dataString.startsWith(url)) {
return true;
}
}
return false;
}
#Override
protected void onPause() {
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
ambientLightManager.stop();
cameraManager.closeDriver();
if (!hasSurface) {
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.removeCallback(this);
}
super.onPause();
}
#Override
protected void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (source == IntentSource.NATIVE_APP_INTENT) {
setResult(RESULT_CANCELED);
finish();
return true;
}
if ((source == IntentSource.NONE || source == IntentSource.ZXING_LINK) && lastResult != null) {
restartPreviewAfterDelay(0L);
return true;
}
break;
case KeyEvent.KEYCODE_FOCUS:
case KeyEvent.KEYCODE_CAMERA:
// Handle these events so they don't launch the Camera app
return true;
// Use volume up/down to turn on light
case KeyEvent.KEYCODE_VOLUME_DOWN:
cameraManager.setTorch(false);
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
cameraManager.setTorch(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.capture, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
switch (item.getItemId()) {
case R.id.menu_share:
intent.setClassName(this, ShareActivity.class.getName());
startActivity(intent);
break;
case R.id.menu_history:
intent.setClassName(this, HistoryActivity.class.getName());
startActivityForResult(intent, HISTORY_REQUEST_CODE);
break;
case R.id.menu_settings:
intent.setClassName(this, PreferencesActivity.class.getName());
startActivity(intent);
break;
case R.id.menu_help:
intent.setClassName(this, HelpActivity.class.getName());
startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_OK) {
if (requestCode == HISTORY_REQUEST_CODE) {
int itemNumber = intent.getIntExtra(Intents.History.ITEM_NUMBER, -1);
if (itemNumber >= 0) {
HistoryItem historyItem = historyManager.buildHistoryItem(itemNumber);
decodeOrStoreSavedBitmap(null, historyItem.getResult());
}
}
}
}
private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
// Bitmap isn't used yet -- will be used soon
if (handler == null) {
savedResultToShow = result;
} else {
if (result != null) {
savedResultToShow = result;
}
if (savedResultToShow != null) {
Message message = Message.obtain(handler, R.id.decode_succeeded, savedResultToShow);
handler.sendMessage(message);
}
savedResultToShow = null;
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
}
if (!hasSurface) {
hasSurface = true;
initCamera(holder);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
/**
* A valid barcode has been found, so give an indication of success and show the results.
*
* #param rawResult The contents of the barcode.
* #param scaleFactor amount by which thumbnail was scaled
* #param barcode A greyscale bitmap of the camera data which was decoded.
*/
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
Intent it = getIntent();
it.putExtra("SCAN_RESULT", rawResult.getText());
it.putExtra("SCAN_FORMAT", rawResult.getBarcodeFormat().toString());
setResult(Activity.RESULT_OK, it);
finish();
inactivityTimer.onActivity();
lastResult = rawResult;
ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
boolean fromLiveScan = barcode != null;
if (fromLiveScan) {
historyManager.addHistoryItem(rawResult, resultHandler);
// Then not from history, so beep/vibrate and we have an image to draw on
beepManager.playBeepSoundAndVibrate();
drawResultPoints(barcode, scaleFactor, rawResult);
}
switch (source) {
case NATIVE_APP_INTENT:
case PRODUCT_SEARCH_LINK:
handleDecodeExternally(rawResult, resultHandler, barcode);
break;
case ZXING_LINK:
if (scanFromWebPageManager == null || !scanFromWebPageManager.isScanFromWebPage()) {
handleDecodeInternally(rawResult, resultHandler, barcode);
} else {
handleDecodeExternally(rawResult, resultHandler, barcode);
}
break;
case NONE:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (fromLiveScan && prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, false)) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.msg_bulk_mode_scanned) + " (" + rawResult.getText() + ')',
Toast.LENGTH_SHORT).show();
// Wait a moment or else it will scan the same barcode continuously about 3 times
restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS);
} else {
handleDecodeInternally(rawResult, resultHandler, barcode);
}
break;
}
}
/**
* Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
*
* #param barcode A bitmap of the captured image.
* #param scaleFactor amount by which thumbnail was scaled
* #param rawResult The decoded results which contains the points to draw.
*/
private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) {
ResultPoint[] points = rawResult.getResultPoints();
if (points != null && points.length > 0) {
Canvas canvas = new Canvas(barcode);
Paint paint = new Paint();
paint.setColor(getResources().getColor(R.color.result_points));
if (points.length == 2) {
paint.setStrokeWidth(4.0f);
drawLine(canvas, paint, points[0], points[1], scaleFactor);
} else if (points.length == 4 &&
(rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A ||
rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) {
// Hacky special case -- draw two lines, for the barcode and metadata
drawLine(canvas, paint, points[0], points[1], scaleFactor);
drawLine(canvas, paint, points[2], points[3], scaleFactor);
} else {
paint.setStrokeWidth(10.0f);
for (ResultPoint point : points) {
if (point != null) {
canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint);
}
}
}
}
}
private static void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b, float scaleFactor) {
if (a != null && b != null) {
canvas.drawLine(scaleFactor * a.getX(),
scaleFactor * a.getY(),
scaleFactor * b.getX(),
scaleFactor * b.getY(),
paint);
}
}
// Put up our own UI for how to handle the decoded contents.
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
statusView.setVisibility(View.GONE);
viewfinderView.setVisibility(View.GONE);
resultView.setVisibility(View.VISIBLE);
ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
if (barcode == null) {
barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),
R.drawable.launcher_icon));
} else {
barcodeImageView.setImageBitmap(barcode);
}
TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
formatTextView.setText(rawResult.getBarcodeFormat().toString());
TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
typeTextView.setText(resultHandler.getType().toString());
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
timeTextView.setText(formatter.format(new Date(rawResult.getTimestamp())));
TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
metaTextView.setVisibility(View.GONE);
metaTextViewLabel.setVisibility(View.GONE);
Map<ResultMetadataType,Object> metadata = rawResult.getResultMetadata();
if (metadata != null) {
StringBuilder metadataText = new StringBuilder(20);
for (Map.Entry<ResultMetadataType,Object> entry : metadata.entrySet()) {
if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
metadataText.append(entry.getValue()).append('\n');
}
}
if (metadataText.length() > 0) {
metadataText.setLength(metadataText.length() - 1);
metaTextView.setText(metadataText);
metaTextView.setVisibility(View.VISIBLE);
metaTextViewLabel.setVisibility(View.VISIBLE);
}
}
TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
CharSequence displayContents = resultHandler.getDisplayContents();
contentsTextView.setText(displayContents);
// Crudely scale betweeen 22 and 32 -- bigger font for shorter text
int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view);
supplementTextView.setText("");
supplementTextView.setOnClickListener(null);
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
PreferencesActivity.KEY_SUPPLEMENTAL, true)) {
SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView,
resultHandler.getResult(),
historyManager,
this);
}
int buttonCount = resultHandler.getButtonCount();
ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
buttonView.requestFocus();
for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
TextView button = (TextView) buttonView.getChildAt(x);
if (x < buttonCount) {
button.setVisibility(View.VISIBLE);
button.setText(resultHandler.getButtonText(x));
button.setOnClickListener(new ResultButtonListener(resultHandler, x));
} else {
button.setVisibility(View.GONE);
}
}
if (copyToClipboard && !resultHandler.areContentsSecure()) {
ClipboardInterface.setText(displayContents, this);
}
}
// Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
private void handleDecodeExternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
if (barcode != null) {
viewfinderView.drawResultBitmap(barcode);
}
long resultDurationMS;
if (getIntent() == null) {
resultDurationMS = DEFAULT_INTENT_RESULT_DURATION_MS;
} else {
resultDurationMS = getIntent().getLongExtra(Intents.Scan.RESULT_DISPLAY_DURATION_MS,
DEFAULT_INTENT_RESULT_DURATION_MS);
}
if (resultDurationMS > 0) {
String rawResultString = String.valueOf(rawResult);
if (rawResultString.length() > 32) {
rawResultString = rawResultString.substring(0, 32) + " ...";
}
statusView.setText(getString(resultHandler.getDisplayTitle()) + " : " + rawResultString);
}
if (copyToClipboard && !resultHandler.areContentsSecure()) {
CharSequence text = resultHandler.getDisplayContents();
ClipboardInterface.setText(text, this);
}
if (source == IntentSource.NATIVE_APP_INTENT) {
// Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
// the deprecated intent is retired.
Intent intent = new Intent(getIntent().getAction());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
byte[] rawBytes = rawResult.getRawBytes();
if (rawBytes != null && rawBytes.length > 0) {
intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes);
}
Map<ResultMetadataType,?> metadata = rawResult.getResultMetadata();
if (metadata != null) {
if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) {
intent.putExtra(Intents.Scan.RESULT_UPC_EAN_EXTENSION,
metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString());
}
Number orientation = (Number) metadata.get(ResultMetadataType.ORIENTATION);
if (orientation != null) {
intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue());
}
String ecLevel = (String) metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL);
if (ecLevel != null) {
intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel);
}
#SuppressWarnings("unchecked")
Iterable<byte[]> byteSegments = (Iterable<byte[]>) metadata.get(ResultMetadataType.BYTE_SEGMENTS);
if (byteSegments != null) {
int i = 0;
for (byte[] byteSegment : byteSegments) {
intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i, byteSegment);
i++;
}
}
}
sendReplyMessage(R.id.return_scan_result, intent, resultDurationMS);
} else if (source == IntentSource.PRODUCT_SEARCH_LINK) {
// Reformulate the URL which triggered us into a query, so that the request goes to the same
// TLD as the scan URL.
int end = sourceUrl.lastIndexOf("/scan");
String replyURL = sourceUrl.substring(0, end) + "?q=" + resultHandler.getDisplayContents() + "&source=zxing";
sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
} else if (source == IntentSource.ZXING_LINK) {
if (scanFromWebPageManager != null && scanFromWebPageManager.isScanFromWebPage()) {
String replyURL = scanFromWebPageManager.buildReplyURL(rawResult, resultHandler);
sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
}
}
}
private void sendReplyMessage(int id, Object arg, long delayMS) {
if (handler != null) {
Message message = Message.obtain(handler, id, arg);
if (delayMS > 0L) {
handler.sendMessageDelayed(message, delayMS);
} else {
handler.sendMessage(message);
}
}
}
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException("No SurfaceHolder provided");
}
if (cameraManager.isOpen()) {
Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
return;
}
try {
cameraManager.openDriver(surfaceHolder);
// Creating the handler starts the preview, which can also throw a RuntimeException.
if (handler == null) {
handler = new CaptureActivityHandler(this, decodeFormats, decodeHints, characterSet, cameraManager);
}
decodeOrStoreSavedBitmap(null, null);
} catch (IOException ioe) {
Log.w(TAG, ioe);
displayFrameworkBugMessageAndExit();
} catch (RuntimeException e) {
// Barcode Scanner has seen crashes in the wild of this variety:
// java.?lang.?RuntimeException: Fail to connect to camera service
Log.w(TAG, "Unexpected error initializing camera", e);
displayFrameworkBugMessageAndExit();
}
}
private void displayFrameworkBugMessageAndExit() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.msg_camera_framework_bug));
builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
builder.setOnCancelListener(new FinishListener(this));
builder.show();
}
public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
}
resetStatusView();
}
private void resetStatusView() {
resultView.setVisibility(View.GONE);
statusView.setText(R.string.msg_default_status);
statusView.setVisibility(View.VISIBLE);
viewfinderView.setVisibility(View.VISIBLE);
lastResult = null;
}
public void drawViewfinder() {
viewfinderView.drawViewfinder();
}
}
your SplashScreen Java should look like this:
{
Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, com.google.zxing.client.android.CaptureActivity.class);
// use startActivityForResult instead of startActivity
startActivityForResult(mainIntent)
}
but I guess you already solved you problem!
I have a runnable timer that update a textview every second, when the activity is onStop (or called into the background) the timer continues to run. The issue i am having is that when i re-launch the activity it starts the same timer again, so the numbers are going up twice as fast as they should. I have it coded so that it will kill both timers before it restarts them but i believe that when the activity is started again the timers are not being killed. Here is an example of my code :
t.cancel();
cd.cancel();
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
That is only a small part but it should kill the timer (t.cancel();) then start a new one, this only happens when the activity is stopped and then restarted. please help this issue is driving me absolutely insane.
=========================================================
For the brave souls willing to read alot, here is my entire activity that i am having the issue with:
public class PayTracker extends Activity {
private static double Reserve;
private static int Reserve1;
public static double money;
public static double counter;
private static int go;
private static int countdown;
public static int convert;
public static double HW;
public static double OTW;
public static double HPD;
public static double DPPS;
public Timer t = new Timer();
public Timer cd = new Timer();
public static String mcountdown = "Time till overtime";
public static String mmoney = "total cash";
public static String mcounter = "ticks";
public static String mReserve = "building total";
public static String mReserve1 = "building total 2";
public static String mHW;
public static String mOTW;
public static String mHPD;
public static String mDPPS;
public static String mgo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_tracker);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Receive messages from options page
double pHW, pOTW, pHPD;
Intent intent = getIntent();
pHW = intent.getDoubleExtra(Options.MESSAGE_HW, 0);
pOTW = intent.getDoubleExtra(Options.MESSAGE_OTW, 0);
pHPD = intent.getDoubleExtra(Options.MESSAGE_HPD, 0);
if(pHW != 0){
HW = pHW;
OTW = pOTW;
HPD = pHPD;
}
// Color buttons
Button buttonc = (Button) findViewById(R.id.clockin);
buttonc.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
Button buttond = (Button) findViewById(R.id.clockout);
buttond.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
// go = 0;
// Calculate pay per second
final double PPS = (HW/3600);
DPPS = (PPS/50);
final double OTPPS = (OTW/3600);
final double DOTPPS = (OTPPS/50);
final double HPDPS = (HPD*3600);
final double DHPDPS = (HPDPS*50);
// Display
final TextView t1 = (TextView) findViewById(R.id.yourpay);
t1.setTextColor(Color.parseColor("#008000"));
final TextView t2 = (TextView) this.findViewById(R.id.payper);
final String result2 = String.format("%.8f", OTPPS);
final String result = String.format("%.8f", PPS);
// if(go != 1){
// go = 1;
// if(go == 1){
t.cancel();
cd.cancel();
// go = 0;
// }
// if(go == 0){
// go = 1;
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if(DHPDPS==0){
money = (DPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
}else if(counter > DHPDPS && DOTPPS != 0 && DHPDPS != 0){
money = (DOTPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
} else{
money = (DPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
}
counter++;
//if(counter == 3000)
// t.cancel();
// Display pay per second
if(counter <= DHPDPS || DHPDPS == 0){
t2.setText("Your pay per second is: $"+result);
}else{
t2.setText("Your pay per second is: $"+result2);
}
}
});
}
}, 20, 20);
// Make countdown to overtime display
final Intent intent1 = new Intent(this, PayTracker.class);
// Create the notification
final Notification notification = new Notification(R.drawable.ic_launcher, "Click here to check your pay!", System.currentTimeMillis());
// Create an Intent for the notification to launch
// Create a PendingIntent for the associated Intent
final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent1, 0);
cd = new Timer();
final TextView count = (TextView) findViewById(R.id.countdown);
convert = (int)HPDPS;
cd.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run(){
countdown = (convert - Reserve1);
int hours = (countdown/3600);
if(OTPPS != 0 && HPDPS != 0){
count.setText("Seconds Remaining to Overtime: " + countdown + "\nAbout " + hours + " Hours");
Reserve1++;
}
// Set the notification's details
final String end = String.format("%.6f", money);
notification.setLatestEventInfo(getApplicationContext(), "Your Current Pay:", "$"+end, pendingIntent);
// Submit the notification to the system
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification);
}
});
}
}, 1000, 1000);
// }
// }
final Button b = (Button) findViewById(R.id.clockout);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(go == 1)
go = 0;
if (t != null){
t.cancel();
cd.cancel();
}
}
});
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore value of members from saved state
countdown = savedInstanceState.getInt(mcountdown);
Reserve = savedInstanceState.getInt(mReserve);
money = savedInstanceState.getInt(mmoney);
counter = savedInstanceState.getInt(mcounter);
Reserve1 = savedInstanceState.getInt(mReserve1);
HW = savedInstanceState.getInt(mHW);
OTW = savedInstanceState.getInt(mOTW);
HPD = savedInstanceState.getInt(mHPD);
DPPS = savedInstanceState.getInt(mDPPS);
go = savedInstanceState.getInt(mgo);
}
#Override
public void onStart(){
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_pay_tracker, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendMessage(View view) {
// Calculate pay per second
final double PPS = (HW/3600);
DPPS = (PPS/50);
final double OTPPS = (OTW/3600);
final double DOTPPS = (OTPPS/50);
final double HPDPS = (HPD*3600);
final double DHPDPS = (HPDPS*50);
// Display
final TextView t1 = (TextView) findViewById(R.id.yourpay);
t1.setTextColor(Color.parseColor("#008000"));
final TextView t2 = (TextView) this.findViewById(R.id.payper);
final String result2 = String.format("%.8f", OTPPS);
final String result = String.format("%.8f", PPS);
//if(go != 1){
// go = 1;
t.cancel();
cd.cancel();
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if(DHPDPS==0){
money = (DPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
}else if(counter > DHPDPS && DOTPPS != 0 && DHPDPS != 0){
money = (DOTPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
} else{
money = (DPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
}
counter++;
if(counter == 3000)
t.cancel();
// Display pay per second
if(counter <= DHPDPS || DHPDPS == 0){
t2.setText("Your pay per second is: $"+result);
}else{
t2.setText("Your pay per second is: $"+result2);
}
}
});
}
}, 20, 20);
// Make countdown to overtime display
final Intent intent1 = new Intent(this, PayTracker.class);
// Create the notification
final Notification notification = new Notification(R.drawable.ic_launcher, "Click here to check your pay!", System.currentTimeMillis());
// Create an Intent for the notification to launch
// Create a PendingIntent for the associated Intent
final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent1, 0);
cd = new Timer();
final TextView count = (TextView) findViewById(R.id.countdown);
convert = (int)HPDPS;
cd.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run(){
countdown = (convert - Reserve1);
int hours = (countdown/3600);
if(OTPPS != 0 && HPDPS != 0){
count.setText("Seconds Remaining to Overtime: " + countdown + "\nAbout " + hours + " Hours");
Reserve1++;
}
// Set the notification's details
final String end = String.format("%.6f", money);
notification.setLatestEventInfo(getApplicationContext(), "Your Current Pay:", "$"+end, pendingIntent);
// Submit the notification to the system
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification);
}
});
}
}, 1000, 1000);
//}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(mcountdown, countdown);
savedInstanceState.putDouble(mReserve, Reserve);
savedInstanceState.putDouble(mmoney, money);
savedInstanceState.putDouble(mcounter, counter);
savedInstanceState.putDouble(mReserve1, Reserve1);
savedInstanceState.putDouble(mHW, HW);
savedInstanceState.putDouble(mOTW, OTW);
savedInstanceState.putDouble(mHPD, HPD);
savedInstanceState.putDouble(mDPPS, DPPS);
savedInstanceState.putInt(mgo, go);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
if(t != null)
t.cancel();
if(cd != null)
cd.cancel();
}
}
This is one way to get around that.
static Timer mTimer = null;
onCreate() {
if (mTimer == null)
mTimer = new Timer();
} else {
// You shouldn't have to do nothing because your timer should be running
}
}
Note that there are several issues in general here. The static is basically saying just to create one instance of that object. As a side effect it also tries to reclaim the same memory address. Either way, once your app is in the background it can be cleaned up by the system at any time so your not guaranteed to get your Timer back. There are a bunch of other ways to get around that, but that is out of scope for this question.