我有活动和服务,我想获得对服务整数的引用,该服务在服务中不时更新。我的问题是,在我的活动中,我只得到该整数首先声明的值(例如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类静态?
1.是的,我的服务有一个独立的过程,因为没有分离,我没有设法使它不会在我的应用程序关闭时被杀死(当用户在我的应用程序中按下我的应用程序和服务都被杀死(服务已返回粘性)) 2.是的,我之前使用过共享的前缀,但是我遇到了问题,因为我在我的Activity中也使用共享前缀,所以我没有设法为活动和服务使用相同的共享前缀(我使用单独的类来共享首选项,并通过在服务和mainActivity中创建它的对象它以某种方式重置已插入的值) – whiteLT 2013-03-17 15:23:20
嗯,我想你需要弄清楚共享首选项的工作原理(这很简单,但),因为鉴于你有服务在不同的进程,他们有不同的内存空间,活动无法访问其他服务的内存)。 – fedepaol 2013-03-17 15:53:31
也许你可以帮我吗?请看看我编辑的帖子。 – whiteLT 2013-03-17 16:11:59