每当运行服务时,我都会尝试从 MainActivity.class SharedPrefs 修改变量(幸福)。我似乎无法弄清楚如何做到这一点。请在我的代码下面找到,我的结果以幸福 = -1 结束,这是因为我理解 prefEditor.putInt 但不确定如何继续修改和返回值。
public class MainActivity extends Activity {
int Health = 100;
private static final int Happiness = 100;
int Hunger = 0;
int Level = 1;
EditText happiness_display,
health_display,
hunger_display,
level_display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences("APP_PREFS",
MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putInt("HAPPINESS", Happiness);
prefEditor.commit();
WebView myWebView = (WebView) findViewById(R.id.pet_display);
myWebView.loadUrl("file:///android_asset/renamon.gif");
myWebView.setInitialScale(10000);
ShowToast();
TextView happiness = (TextView) findViewById(R.id.happiness_display);
happiness.setText(Integer.toString(Happiness));
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, chronos.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
}
private void ShowToast() {
Toast.makeText(getApplicationContext(), "Toast method invoked from on create " + Happiness, Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
public class chronos extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedPreferences settings = getSharedPreferences("APP_PREFS",
MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putInt("HAPPINESS", - 1);
prefEditor.commit();
Toast.makeText(getBaseContext(), "Chronos running" + settings.getInt("HAPPINESS", 0), Toast.LENGTH_LONG).show();
return super.onStartCommand(intent, flags, startId);
}
}
如果我的方法是错误的(可能是:P),任何帮助表示赞赏或指向正确的方向
这可能是我的不连贯,但我基本上想修改幸福,健康等的值。每次运行服务时,就像一个游戏循环,但对于虚拟宠物。
我的 IntentService 中的示例代码
happiness = happiness - 1;
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putInt("HAPPINESS", happiness);
prefEditor.commit();
我只希望每次服务运行时从一些变量中减去一定数量。