首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Android服务中的公共静态变量

Android服务中的公共静态变量
EN

Stack Overflow用户
提问于 2015-03-30 02:59:16
回答 1查看 154关注 0票数 0

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

代码语言:javascript
运行
复制
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,

代码语言:javascript
运行
复制
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")
}

}

我做错了什么?

EN

Stack Overflow用户

发布于 2015-03-30 03:17:17

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

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29333466

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档