Android public static var in service

时间:2015-03-29 18:59:16

标签: android static-variables

我正在尝试在我的应用中使用statuc变量来跟踪某个变量,我的服务代码,我只粘贴了必要的内容

public class TestService extends Service {

    public static HashMap<Long, Integer> testMap;

    @Override
    public void onCreate() {

        registerReceiver();
        testMap = new HashMap<Long, Integer>();
    }


    private final BroadcastReceiver testReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(UPDATE)) {

                long key = intent.getLongExtra("key", -1);
                int value = intent.getIntExtra("value", -1);
                //Make sure I insert it once for testing purposes 
                 if (testMap.get(key) == null)
                    testMap.put(key, value); 

                  //This one prints the value fine
                  Log.i(TAG,testMap.get(key));
                }               
            }         
    };
}

然后我尝试在我的游标适配器中访问它,但我总是得到null,

private static class MyCursorAdapter extends CursorAdapter {

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    return inflater.inflate(R.layout.test_layout, parent, false);
}

@Override
public void bindView(View view, final Context context, Cursor cursor) {

    Integer value = TestService.testMap.get(key);
    //When I check value here, it's always null
    if (value != null)
        Log.i(TAG, value) 
    else 
        Log.i(TAG, "Key value is NULL")
}

}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

确保您没有完成服务,因为每次调用onCreate()时,您都要重新初始化静态变量。顺便说一句,这不是一个好方法,此外,静态全局变量并不是一个好主意。您应该通过Intents与您的服务进行通信或绑定到它而不是共享静态变量。