我有活动和服务,我想获得对服务整数的引用,它会在服务中不时更新。我的问题是,在我的活动中,我只得到了第一个声明的整数值(例如 0)。
我的主要目标是在每次启动程序时了解服务的更新值。
主要活动:
if(Service.doesCounter>0){
//do something
//in this state Service.doesCounter always is 0(checked by log)
}
服务:
public static int doesCounter=0; // declared after class as class memeber
//code where I start my method does();
.....
public void does(){
doesCounter++;
Log.e("cccccc","Service Counter "+doesCounter); // everything ok, value is changing as suppose to.
}
编辑
我的共享首选项类:
public class AppPreferences extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
private static final String APP_SHARED_PREFS = "com.aydabtu.BroadcastSMS_preferences"; // Name of the file -.xml
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public AppPreferences(Context context)
{
this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public boolean getAnything() {
return appSharedPrefs.getBoolean("Anything", false);
}
public void setAnything(Boolean text) {
prefsEditor.putBoolean("Anything", text);
prefsEditor.commit();
}
然后从主要活动:
public class MainActivity extends Activity {
protected AppPreferences appPrefs;
appPrefs = new AppPreferences(getApplicationContext());
appPrefs.setAnything(fasle);
然后从服务:
appPrefs = new AppPreferences(getApplicationContext());
当发生这种情况时,所有之前所做的更改都会被重置,如何让服务和 MainActivity 使用相同的首选项?也许我可以以某种方式使 AppPrefs 类静态?