如何将活动上下文放入非活动类机器人中?

2022-09-03 16:50:02

我有一个活动类,从中我将一些信息传递给帮助者类(非活动)类。在帮助器类中,我想使用 .但我无法使用它,因为它需要活动上下文。getSharedPreferences()

这是我的代码:

  class myActivity extends Activity
    {
    @Override
        protected void onCreate(Bundle savedInstanceState) 
        {

            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.home);


            Info = new Authenticate().execute(ContentString).get();
            ItemsStore.SetItems(Info);

        }

    }

class ItemsStore
{
  public void SetItems(Information info)
 {
  SharedPreferences  localSettings = mContext.getSharedPreferences("FileName", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = localSettings.edit();
            editor.putString("Url", info.Url);
            editor.putString("Email", info.Email);
 }
}

ANy的想法如何实现这一点?


答案 1

您可以尝试此解决方案,而不是创建内存泄漏(通过在类字段中保存活动上下文),因为共享首选项不需要活动上下文,但...任何上下文:)对于长寿命对象,您应该使用 ApplicationContext。

创建应用程序类:

public class MySuperAppApplication extends Application {
    private static Application instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static Context getContext() {
        return instance.getApplicationContext();
    }
}

在清单中注册

<application
    ...
    android:name=".MySuperAppApplication" >
    ...
</application>

然后你可以做这样的事情

public void persistItems(Information info) {
    Context context = MySuperAppApplication.getContext();
    SharedPreferences sharedPreferences = context.getSharedPreferences("urlPersistencePreferences", Context.MODE_PRIVATE);
    sharedPreferences.edit()
        .putString("Url", info.Url)
        .putString("Email", info.Email);
}

方法签名以这种方式看起来更好,因为它不需要外部上下文。这可以隐藏在某些界面下。您还可以轻松地将其用于依赖关系注入。

呵呵


答案 2

试试这个:

class myActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {

        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);


        Info = new Authenticate().execute(ContentString).get();
        ItemsStore.SetItems(Info, getApplicationContext());

    }

}

class ItemsStore
{
   public void SetItems(Information info, Context mContext)
   {
            SharedPreferences  localSettings = mContext.getSharedPreferences("FileName",
            Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = localSettings.edit();
            editor.putString("Url", info.Url);
            editor.putString("Email", info.Email);
   }
}

推荐