【问题标题】:Accessing application class from a service从服务访问应用程序类
【发布时间】:2012-10-07 21:32:51
【问题描述】:

要将值存储为全局变量,我读到可以使用 Application 类。我打算从主活动中获取用户名和密码,将它们存储在应用程序类变量中并启动一个新活动,然后在新活动中启动的服务中获取这些值,但是,我在使用我定义的 getter 方法时得到空值在我的应用程序类中。

我的应用类:

public class MyApp extends Application
{
  private String uid;
  private String upwd;

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

  public void setUID(String value)
  {
      uid = value;
  }

  public void setPWD(String value)
  {
      upwd = value; 
  }

  public String getUID()
  {
      return uid;
  }

  public String getPWD()
  {
      return upwd;
  }
}

在我的主要活动中:

  public void setvalues()
  {
        unameval = Unametxtfield.getText().toString();
        pswrdval =  Pswrdtxtfield.getText().toString();     
        ((MyApp)this.getApplicationContext()).setUID(unameval);
        ((MyApp)this.getApplicationContext()).setPWD(pswrdval);
  }

服务内部我的第二个活动:

public void fetchvalues()
{
      String uname = ((MyApp).getApplicationContext()).getUID();
      String upswrd = ((MyApp).getApplicationContext()).getPWD();
}

Android 清单:

<application
        android:name="MyApp"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

    <!-- A Service here -->
     <service
        android:name="Service1"
        android:process=":myapp_service1" >
    </service> 


    <!-- A service in which I do the fetching of uname and pswd -->
     <service 
        android:name="Service2"
        android:process=":myapp_Service2" >
     </service>

    <activity
        android:name=".Second_Activity"
        android:exported="false"
        android:label="@string/activityname" >
        <intent-filter>
            <action android:name="android.intent.action.DEFAULT" />
        </intent-filter>
    </activity>

    <activity
        android:name=".MainActivity"
        android:label="@string/Firstactivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>

注意:我在某处读到,当您在多个进程上使用应用程序类时(我认为我正在这样做),应用程序类将无法工作,这是真的吗?

【问题讨论】:

  • 这是真的。您不能在多个进程中使用此方法。

标签: android global-variables


【解决方案1】:

【讨论】:

  • 我已经切换到共享首选项,并且没有问题,但我想了解为什么早期的方法不起作用,无论如何谢谢
  • 单例也行不通。与 Application 对象相同的原因:不同的进程意味着不同的 VM 实例。它们不能直接通信并共享相同的内存空间。
  • 服务是否作为独立进程运行?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多