I use Sensor.TYPE_STEP_COUNTER I know it only resets when rebooting. Is there an alternative way to reset the steps to 0 when pressing a button?
Please see my code, you will find the Runactivity.class
Maybe I can do it in another way which resets the steps.
without having me to reboot every time.
public class RunActivity extends AppCompatActivity implements SensorEventListener{
private SensorManager sensorManager;
private TextView count;
boolean activityRunning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle bundle = getIntent().getExtras();
final String naam = bundle.getString("naam");
TextView NaamView = null;
Button stopRun = (Button) findViewById(R.id.stopRun);
count = (TextView) findViewById(R.id.countView);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
NaamView = (TextView) findViewById(R.id.naamRunText);
NaamView.setText(naam);
stopRun.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String countValue = count.getText().toString();
Log.d("countVAL", String.valueOf(countValue));
Intent myIntent = new Intent(RunActivity.this, HomeScreenActivity.class);
Bundle bundle = new Bundle();
bundle.putString("naam", naam);
sensorManager.flush(RunActivity.this);
sensorManager.unregisterListener(RunActivity.this);
count.setText("0");
onStop();
myIntent.putExtras(bundle);
startActivity(myIntent);
}
});
}
#Override
protected void onResume() {
super.onResume();
activityRunning = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if(countSensor != null){
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
}else{
Toast.makeText(this, "Jouw apparaat heeft geen sensor!", Toast.LENGTH_LONG) .show();
}
}
#Override
public void onSensorChanged(SensorEvent event) {
if(activityRunning){
count.setText(String.valueOf(event.values[0]));
}else{
event.values[0] = 0;
}
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
activityRunning = false;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
protected void onDestroy() {
super.onDestroy();
}
}
When you click the reset button in the app save the current step count to SharedPreferences. And you'll need a way to find out when was the last reboot because every time you reboot the saved count number gets invalid.
private Integer stepsInSensor;
private Integer stepsAtReset;
void onCreate() {
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
stepsAtReset = prefs.getInt("stepsAtReset", 0);
}
public void onClick(View v) {
stepsAtReset = stepsInSensor;
if (stepsAtReset != null) {
SharedPreferences.Editor editor =
getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("stepsAtReset", stepsAtReset);
editor.commit();
}
// you can now display 0:
count.setText(String.valueOf(0));
}
#Override
public void onSensorChanged(SensorEvent event) {
if(activityRunning){
stepsInSensor = Integer.valueOf(event.values[0]);
if (stepsAtReset = null) {
stepsAtReset = stepsInSensor;
}
int stepsSinceReset = stepsInSensor - stepsAtReset;
if (stepsSinceReset < 0) {
stepsAtReset = stepsInSensor;
stepsSinceReset = 0;
}
count.setText(String.valueOf(stepsSinceReset));
}else{
event.values[0] = 0;
}
}
I searched on it and tried to do it with different ways. Nothing Helped.
Then I found the most simple way possible.
In onSensorChanged() just add the counter so when ever onSensorChanged() will be called (it will be called on every step), counter will simply count the steps then show this counter to your UI instead of showing the value of event.values[0]
on your Reset button make the counter 0 again.
Nope, based on the Sensor API
A sensor of this type returns the number of steps taken by the user
since the last reboot while activated. The value is returned as a
float (with the fractional part set to zero) and is reset to zero only
on a system reboot.
It can only be reset when the system is rebooted
Related
I am trying to make promo code for my app when the user gives correct value in the EditText I will set a boolean value false and a number will be stored in shared preferences. But don't know why the value is not getting decremented and even if it decreases and even if I do it multiple times then only it moves from 30 to 29.
So I created a test app where I am setting the value in onClick what happens when the promo code is equal. So the decrement thing is when the user open the app the number will get decreased and stored back when the boolean value is false
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button, button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button1 = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences prefs = getSharedPreferences("Admob", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("ShowAd", false);
editor.putLong("daycounter", 30);
editor.commit();
}
});
caller();
}
#Override
protected void onResume() {
super.onResume();
caller();
}
#Override
protected void onPause() {
super.onPause();
caller();
}
public void caller() {
SharedPreferences settings = getSharedPreferences("Admob", 0);
boolean ad_start = settings.getBoolean("ShowAd", true);
long ad = settings.getLong("daycounter", 0);
SharedPreferences prefs = getSharedPreferences("apprater", 0);
SharedPreferences.Editor editor = prefs.edit();
Log.e("toaster", "" + ad_start);
if (!ad_start) {
long ads = ad -1 ;
if (ad > 0) {
editor.putLong("daycounter", ads);
editor.putBoolean("ShowAd", true);
editor.commit();
Toast.makeText(MainActivity.this, "" + ads, Toast.LENGTH_SHORT).show();
textView.setText(ad + "R" + ad_start);
}
}
}
}
In the dummy app I am showing the data in TextView so I am calling onResume and onPause method otherwise I know onCreate is enough. I don't understand whats wrong in the algorithm. I am not getting any error at all and in the toast I am only able to decrease the value till 29 . I have tried all types of decrement operation. Any advice will be helpful.**I am able to save the data onle problem is with the lonng value is not getting saved and not getting decremented **
Put these methods in your utils class and use
public static void cacheBoolean(Context ctx, String k, Boolean v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putBoolean(k, v).apply();
}
public static Boolean getCachedBoolean(Context ctx, String k, Boolean defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getBoolean(k, defaultValue);
}
public static void cacheString(Context ctx, String k, String v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putString(k, v).apply();
}
public static String getCachedString(Context ctx, String k, String defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getString(k, defaultValue);
}
public static void cacheInt(Context ctx, String k, int v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putInt(k, v).apply();
}
public static int getCachedInt(Context ctx, String k, int defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getInt(k, defaultValue);
}
public static void clearCachedKey(Context context, String key) {
getSharedPreferences(context).edit().remove(key).apply();
}
You don't need to put shared preferences everywhere, just initialize it inside onCreate method and access from constant String, so will easy to access it.
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button, button1;
SharedPreferences prefs;
SharedPreferences.Editor editor;
final String pref_name = "Admob";
final String ad_name = "ShowAd";
final String day_count = "daycounter";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button1 = (Button) findViewById(R.id.button2);
prefs = getSharedPreferences(pref_name, 0);
editor = prefs.edit();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putBoolean(ad_name, false);
editor.putLong(day_count, 30);
editor.commit();
}
});
caller();
}
#Override
protected void onResume() {
super.onResume();
caller();
}
#Override
protected void onPause() {
super.onPause();
caller();
}
public void caller() {
boolean ad_start = prefs.getBoolean(ad_name, true);
long ad = prefs.getLong(day_count, 0);
Log.e("toaster", "" + ad_start);
if (!ad_start) {
long ads = ad -1 ;
if (ad < 0) {
editor.putBoolean(ad_name, true);
}
editor.putLong(day_count, ads);
editor.commit();
Toast.makeText(MainActivity.this, "" + ads, Toast.LENGTH_SHORT).show();
textView.setText(ad + "R" + ad_start);
}
}
}
I was making mistake in this method part thx to Ahmed sir My mistake was setting the value equal to
if (ad > 0) so when the value is more than zero the boolean was st as true and the data never get a chance to get decremented more
public void caller() {
SharedPreferences settings = getSharedPreferences("Admob", 0);
boolean ad_start = settings.getBoolean("ShowAd", true);
long ad = settings.getLong("daycounter", 0);
Log.e("toaster", "" + ad_start);
if (!ad_start) {
SharedPreferences prefs = getSharedPreferences("Admob", 0);
SharedPreferences.Editor editor = prefs.edit();
long ads = ad - 1;
if (ad < 0) {
editor.putBoolean("ShowAd", true);
}
editor.putLong("daycounter", ads);
editor.commit();
Toast.makeText(MainActivity.this, "" + ads, Toast.LENGTH_SHORT).show();
textView.setText(ad + "R" + ad_start);
}
}
Purpose of program: I'm trying to make an app that will count how many times the user checked their phone by issuing a broadcast for Intent.ACTION_SCREEN_ON. it then increments a counter and updates the activity with the new counter.
The problem: This all works just fine but as soon as I swipe away the application from the apps tray, the counter goes back to zero.
obviously what is supposed to happen is the counter would continue.
I tried saving the counter value in the service onDestroy and then calling it again onCreate but onDestroy is never called.
Note that in the onCreate() for the activity it sends a broadcast to the service asking for the most recent value of counter and then updates it in the view. I couldn't find a better way to keep them in sync.
CounterService.java
public class CounterService extends Service {
public static boolean RERUN = true;
private int counter = 0;
private SharedPreferences SP;
private BroadcastReceiver mScreenStateBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
counter++;
System.out.println("************************************* \n \n " + counter);
}
sendCounterBroadcast();
}
};
public void sendCounterBroadcast() {
Intent i = new Intent();
i.setAction("com.inc.count");
i.putExtra("counterValue", counter);
sendBroadcast(i);
}
#Override
public void onCreate() {
super.onCreate();
System.out.println("********************** CounterService.onCreate()");
// get counter value from SP -- this is useful for when the service gets recreated
SP = getSharedPreferences("Counter Service Data", MODE_PRIVATE);
counter = SP.getInt("counter", 0);
// wait for screen to be turned on or for the activity to ask you for the counter number
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction("send.counter.to.phonecounteractivity");
registerReceiver(mScreenStateBroadcastReceiver, intentFilter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("***************************************** CounterService.OnDestroy()");
unregisterReceiver(mScreenStateBroadcastReceiver);
// Save counter value for when we restart service
SP = getSharedPreferences("Counter Service Data", MODE_PRIVATE);
SharedPreferences.Editor SPE = SP.edit();
if (RERUN) {
SPE.putInt("counter", counter);
System.out.println("******************************** RESTARTING SERVICE ");
startService(new Intent(getApplicationContext(), CounterService.class));
} else
SPE.putInt("counter", 0);
SPE.apply();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
PhoneCheckerCounter.Java
public class PhoneCheckerCounter extends AppCompatActivity {
private BroadcastReceiver changeCount;
private IntentFilter filter;
private int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_checker_counter);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
switcherOnClick();
assignValuesOnCreate();
System.out.println("**************************** onCreate()");
changeCounterText();
}
public void switcherOnClick() {
final Switch sCounter = findViewById(R.id.switchCounter);
sCounter.setOnClickListener(new View.OnClickListener() {
Intent intent = new Intent(getApplicationContext(), CounterService.class);
#Override
public void onClick(View v) {
if (sCounter.isChecked()) {
startService(intent);
CounterService.RERUN = true;
v.getContext().registerReceiver(changeCount, filter);
Toast.makeText(getApplicationContext(), "Counting has begun", Toast.LENGTH_SHORT).show();
} else {
TextView n = findViewById(R.id.counter);
n.setText("0");
CounterService.RERUN = false;
v.getContext().unregisterReceiver(changeCount);
stopService(intent);
Toast.makeText(getApplicationContext(), "The application stopped counting", Toast.LENGTH_SHORT).show();
}
}
});
}
public void changeCounterText() {
changeCount = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView n = findViewById(R.id.counter);
counter = intent.getIntExtra("counterValue", 0);
System.out.println("************************ RECEIVED!!!! value of: " + counter);
n.setText("" + counter);
}
};
filter = new IntentFilter();
filter.addAction("com.inc.count");
this.registerReceiver(changeCount, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(changeCount);
assignValuesOnDestroy();
System.out.println("**************************** onDestroy()");
}
public void assignValuesOnCreate() {
Switch s = findViewById(R.id.switchCounter);
if (getSwitchValueFromSP() == 1) s.setChecked(true);
else s.setChecked(false);
Intent f = new Intent();
f.setAction("send.counter.to.phonecounteractivity");
sendBroadcast(f);
}
public void assignValuesOnDestroy() {
SharedPreferences SP = getSharedPreferences("data", MODE_PRIVATE);
SharedPreferences.Editor edit = SP.edit();
Switch s = findViewById(R.id.switchCounter);
if (s.isChecked()) edit.putInt("switch", 1);
else edit.putInt("switch", 0);
edit.apply();
}
public int getSwitchValueFromSP() {
SharedPreferences SP = getSharedPreferences("data", MODE_PRIVATE);
int isOn = SP.getInt("switch", 0);
return isOn;
}
}
Sample of the activity
When I press the mute button on action bar that I have created it only stops the last sound being played and not all the sounds.
Also since the sound doesn't stop if I press the button(5-6 times) to play the sound and press mute on the same activity then go back and choose another activity and press that mute button the app crashes. Any ideas why?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
public void pb1(View view) {
mp = MediaPlayer.create(this, R.raw.sound1);
mp.start();
}
//inflates the menu;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menunot, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_sound:
mp.stop();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.stop();
mp.reset();
mp.release();
mp = null;
}
Just make an array list then stop all,
Take a look at the example below:
private static final int steps[] =
{R.raw.step_1, R.raw.step_2, R.raw.step_3, R.raw.step_4, R.raw.step_5, R.raw.step_6, R.raw.step_7, R.raw.step_8, R.raw.step_9, R.raw.step_10
};
private int i = 0;
private ArrayList<MediaPlayer> voices = new ArrayList<>(10);
private Button btnPlay;
private Button btnStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(i==10)i=0;
final MediaPlayer voice = MediaPlayer.create(MainActivity.this, steps[i++]);
voice.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (voice != null) {
voices.remove(voice);
voice.release();
}
}
});
voice.start();
voices.add(voice);
}
});
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int j = voices.size() - 1; j >= 0; j--) {
if (voices.get(j) != null) {
if (voices.get(j).isPlaying())
voices.get(j).stop();
voices.get(j).release();
voices.remove(j);
}
}
}
});
}
Hey please try the following solution,
SoundPool is a much better alternative for this purpose. I would caution strongly against instantiating multiple MediaPlayer instances as most systems do not have the resources to generate many parallel active instances. You will find on many device that hitting the button upwards of 5 times will cause a memory based crash.
As far as stopping all active streams, there is not baked-in function for this, but it's easy to accomplish in a manner to similar to your existing code. As a side note, there is an autoPause() method, which halts all streams, but it doesn't truly end their playback (as the method name insinuates). Here is a simple example to manage your audio streams:
//SoundPool initialization somewhere
SoundPool pool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
//Load your sound effect into the pool
int soundId = pool.load(...); //There are several versions of this, pick which fits your sound
List<Integer> streams = new ArrayList<Integer>();
Button item1 = (Button)findViewById(R.id.item1);
item1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int streamId = pool.play(soundId, 1.0f, 1.0f, 1, 0, 1.0f);
streams.add(streamId);
}
});
Button stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for (Integer stream : streams) {
pool.stop(stream);
}
streams.clear();
}
});
It is much more memory efficient to manage a list of streamID values than MediaPlayer instances, and your users will thank you. Also, note that it is safe to call SoundPool.stop() even if the streamID is no longer valid, so you don't need to check for existing playback.
Happy coding :)
I am working on a pedometer and it runs smoothly. I want to make a button for resetting but its giving me issues.
This is my code below.
public class MainActivity extends Activity implements SensorEventListener {
private TextView textView;
private Button resetButton;
private SensorManager mSensorManager;
private Sensor mStepCounterSensor;
private Sensor mStepDetectorSensor;
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.pedometer);
resetButton = (Button) findViewById(R.id.resetButton);
mSensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
mStepCounterSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mStepDetectorSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
}
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
int value = -1;
if (values.length > 0) {
value = (int) values[0];
}
if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
textView.setText("Step Counter Detected : " + value);
} else if (sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
textView.setText("Step Detector Detected : " + value);
}
}
//check this reset
public void reset(SensorEvent event){
Sensor sensor = event.sensor;
float[] values = event.values;
int value = -1;
if (values.length > 0) {
value = 0;
}
if (sensor.getType() == value) {
textView.setText("Step Counter Detected : " + value);
}
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mStepCounterSensor,
SensorManager.SENSOR_DELAY_FASTEST);
mSensorManager.registerListener(this, mStepDetectorSensor,
SensorManager.SENSOR_DELAY_FASTEST);
}
protected void onStop() {
super.onStop();
mSensorManager.unregisterListener(this, mStepCounterSensor);
mSensorManager.unregisterListener(this, mStepDetectorSensor);
}
}
I am connecting the reset method to my button so that when I click it. It resets my pedometer to zero. I have tried different ways but it is not working for me.
I am also unsure because my teacher has taught me to use View v in the parameters. I don't know if that has anything to do with it.
This piece of code is not clear.
if (sensor.getType() == value) {
textView.setText("Step Counter Detected : " + value);
}
Why are you comparing sensor type with value? You have to compare with Sensor.TYPE_STEP_DETECTOR or Sensor.TYPE_STEP_COUNTER.
value is a local variable. So I am assuming you are resetting only for display purpose.
Who is calling reset() function and how is the SensorEvent passed to it?
I have an android application similar to wheel of fortune where users have the option to purchase one consumable, $1000, and two entitlements, where they unlock two images as wheel styles. I am using the Amazon In-App Purchasing API. The user should be able to purchase as many consumables as they want but once they purchase the entitlements the unlocked image should be the only image that they see and they should no longer see the locked image. These in-app purchases work fine the first instance I initiate these purchases.
However, the consumable field will only update once and even though I can still go through the process of completing purchases for the consumable, the text view containing the score, or money, does not update other then that first initial purchase. Also the wheels return to the locked image rather then remaining as the unlocked image despite the fact that when I initiate the purchase for these entitlements I am told that I already own these items. Therefore I believe it may be something to do with my SharedPreferences. In short my purchases update my views once and then never again, however the backend code i.e the responses I receive from the Amazon client when completing purchases are correct. Can anyone see where I have made a mistake? Why does the textView containing the score update on the 1st purchase and never again from then on? Also how do I save the changes toe the wheel style so that when it reopens they no longer have the option to purchase the wheel? I have three classes and have included the code below. All and any help is greatly appreciated.
Game Class
public class Game extends Activity {
private ImageView wheel;
private int rand;
private int[] amounts = {100,650,-1,650,300,-1,800,250,-1,500};
private int score = 0;
private TextView scoreText;
private AnimatorSet set;
protected boolean animationDone = true;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
prefs.registerOnSharedPreferenceChangeListener(prefsChanged);
wheel = (ImageView) findViewById(R.id.imageView1);
scoreText = (TextView) findViewById(R.id.score);
score = prefs.getInt("score", 0);
scoreText.setText("$" + String.valueOf(score));
}
private OnSharedPreferenceChangeListener prefsChanged = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
if(key.equals("money") && prefs.getBoolean(key, false)) {
score += 1000;
scoreText.setText("$" + String.valueOf(score));
prefs.edit().putBoolean("money", false);
}
}
};
#Override
protected void onStart() {
super.onStart();
InAppObserver obs = new InAppObserver(this);
PurchasingManager.registerObserver(obs);
}
#Override
protected void onPause() {
if(this.isFinishing())
{
prefs.edit().putInt("score", score).commit();
}
super.onPause();
}
#Override
protected void onStop() {
prefs.edit().putInt("score", score).commit();
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode != RESULT_CANCELED) {
String style = data.getStringExtra("wheel");
if(style.equals("camo"))
wheel.setImageResource(R.drawable.camowheel);
if(style.equals("gold"))
wheel.setImageResource(R.drawable.goldwheel);
if(style.equals("normal"))
wheel.setImageResource(R.drawable.wheel);
}
}
public void spinTheWheel(View v) {
if(animationDone) {
wheel.setRotation(0);
rand = (int) Math.round(2000 + Math.random()*360);
set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(wheel, View.ROTATION, rand));
set.setDuration(2000);
set.setInterpolator(new DecelerateInterpolator());
set.start();
animationDone = false;
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
calculateResult();
animationDone = true;
}
});
}
}
private void calculateResult() {
int angle = (int) wheel.getRotation();
angle %= 360;
angle = (int) Math.floor(angle/36);
if(amounts[angle] == -1) {
Intent intent = new Intent(this, GameOver.class);
intent.putExtra("score", score);
prefs.edit().putInt("score", 0).commit();
score = 0;
startActivity(intent);
}
else {
score += amounts[angle];
scoreText.setText("$"+String.valueOf(score));
prefs.edit().putInt("score", 0).commit();
}
}
public void upgradeWheel(View v) {
Intent intent = new Intent(getApplicationContext(), ChangeWheel.class);
startActivityForResult(intent, 1);
}
public void endGame(View v) {
Intent intent = new Intent(getApplicationContext(), GameOver.class);
intent.putExtra("score", score);
prefs.edit().putInt("score", 0).commit();
score = 0;
startActivity(intent);
}
public void addMoney(View v) {
PurchasingManager.initiatePurchaseRequest("money");
}
}
ChangeWheel Class
public class ChangeWheel extends Activity {
private Button buyCamoButton;
private Button buyGoldButton;
private ImageButton goldButton;
private ImageButton camoButton;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_wheel);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
prefs.registerOnSharedPreferenceChangeListener(prefsChanged);
buyCamoButton = (Button) findViewById(R.id.buyCamo);
buyGoldButton = (Button) findViewById(R.id.buyGold);
goldButton = (ImageButton) findViewById(R.id.goldButton);
camoButton = (ImageButton) findViewById(R.id.camoButton);
goldButton.setEnabled(false);
camoButton.setEnabled(false);
}
private OnSharedPreferenceChangeListener prefsChanged = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
if(key.equals("camo") && prefs.getBoolean(key, false)) {
camoButton.setImageResource(R.drawable.camowheel);
camoButton.setEnabled(true);
buyCamoButton.setVisibility(View.INVISIBLE);
}
else if(key.equals("gold") && prefs.getBoolean(key, false)) {
goldButton.setImageResource(R.drawable.goldwheel);
goldButton.setEnabled(true);
buyGoldButton.setVisibility(View.INVISIBLE);
}
}
};
#Override
protected void onStart() {
super.onStart();
InAppObserver obs = new InAppObserver(this);
PurchasingManager.registerObserver(obs);
}
public void camoClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "camo");
setResult(RESULT_OK, intent);
finish();
}
public void goldClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "gold");
setResult(RESULT_OK, intent);
finish();
}
public void normalClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "normal");
setResult(RESULT_OK, intent);
finish();
}
public void buyCamo(View v) {
String req = PurchasingManager.initiatePurchaseRequest("camo");
prefs.edit().putString(req, "camo").commit();
}
public void buyGold(View v) {
String req = PurchasingManager.initiatePurchaseRequest("gold");
prefs.edit().putString(req, "gold").commit();
}
}
InAppObserver Class
public class InAppObserver extends BasePurchasingObserver {
private SharedPreferences prefs;
public InAppObserver(Activity caller) {
super(caller);
prefs = PreferenceManager.getDefaultSharedPreferences(caller.getApplicationContext());
}
#Override
public void onSdkAvailable(boolean isSandboxMode) {
PurchasingManager.initiatePurchaseUpdatesRequest(Offset.BEGINNING);
}
#Override
public void onPurchaseUpdatesResponse(PurchaseUpdatesResponse res) {
for(String sku : res.getRevokedSkus()) {
prefs.edit().putBoolean(sku, false).commit();
}
switch (res.getPurchaseUpdatesRequestStatus()) {
case SUCCESSFUL:
for(Receipt rec : res.getReceipts()) {
prefs.edit().putBoolean(rec.getSku(), true).commit();
}
break;
case FAILED:
// do something
break;
}
}
#Override
public void onPurchaseResponse(PurchaseResponse res) {
switch(res.getPurchaseRequestStatus()) {
case SUCCESSFUL:
String sku = res.getReceipt().getSku();
prefs.edit().putBoolean(sku, true).commit();
break;
case ALREADY_ENTITLED:
String req = res.getRequestId();
prefs.edit().putBoolean(prefs.getString(req, null), true).commit();
break;
case FAILED:
// do something
break;
case INVALID_SKU:
// do something
break;
}
}
}
It could be that you are not using the same editor.
preferences.edit().putString(PreferenceKey.DISTANCE, distance);
preferences.edit().commit();
two different SharedPreferences.Editors are being returned. Hence the
value is not being committed. Instead, you have to use:
SharedPreferences.Editor spe = preferences.edit();
spe.putString(PreferenceKey.DISTANCE, distance);
spe.commit();
From... SharedPreferences not working across Activities