应用变量在服务中

时间:2016-08-30 05:31:43

标签: android service process

我使用前台服务创建应用程序。该服务在另一个进程和线程中运行。

Application类有一个Array,并有公共方法getArray。服务可以访问Application和调用方法getArray。

应用已启动,阵列填充和服务已启动。 如果app更改了数组,则服务返回在启动应用程序中创建的数组。

我如何更新服务中的数组?

服务:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if(mThread != null)
        mThread.interrupt();
    mApplication = (Application) getApplication();
    mTaskManager = mApplication.getTaskManager();

    TaskArray lTasks = mTaskManager.getAll();

    // always return same size
    Log.d(mLogTag, "onStartCommand " + lTasks.size());

    createThread();

    mThread.start();
    super.onStartCommand(intent, flags, startId);
    return START_STICKY;
}

结果:

我在我的应用程序中找到了获取应用程序对象副本的原因。发生这种情况是因为getApplicationContext()返回当前进程的单个全局Application对象的上下文。

为每个进程创建一个应用程序对象的副本。

1 个答案:

答案 0 :(得分:1)

通过在服务类中使用getApplicatonContext()获取Application类的上下文,方法是编写此行((YourApplicatonClassName)getApplicationContext())。getArray()并设置新数据值。 如果可能的话,最好分享您的代码,以便我能够理解您的确切需求。 谢谢

相关问题