线程中的android应用程序类

标签 android multithreading

我需要在使用 InterService 启动的线程中使用我的应用程序类。 在我的 IntentService 中,我有以下代码:

    protected void onHandleIntent(Intent intent) {
    final ResultReceiver receiver = intent.getParcelableExtra("receiver");
    context = getBaseContext();
    app = (AppLoader)getApplicationContext();
    ConnectionThread thread = new ConnectionThread(receiver, context, app.getNewApp());

这是我的主题:

    public ConnectionThread (ResultReceiver receiver, Context context, AppLoader app)
    {

      this.receiver = receiver;
      this.context = context;
      this.activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
      this.app = app;
    }

    @Override
    public void run() {
    Log.d("ConnectionThread","Starting Server Connection");
        try {
            while(isThereActivityRunning()) {
                if(app.isInternetOn())
                {
                    Log.d("ConnectionThread", app.getText());
                    results = sendGetMessage();
                    b.putString("results", results);
                    receiver.send(2, b);
                }

这是我的申请:

public class AppLoader extends Application{
private AppLoader newApp;

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

public AppLoader getNewApp()
{
  if(newApp == null)
     newApp = new AppLoader();   
  return newApp;    
}

我得到一个 java.lang.NullPointerException,我不知道为什么..

最佳答案

您不能创建自己的 Application 实例,即

newApp = new AppLoader();

不应该被调用。 Android 会为您创建应用程序,或者至少如果您在 list 中声明应用程序类,Android 会为您创建应用程序,即

<application ... android:label="@string/app_name" android:name="AppLoader" android:debuggable="true">

它会编译,但您无法访问 Android 实例化应用程序通常会访问的任何内容。

假设您有上面的 list ,您已经可以通过调用访问应用程序实例:

app = (AppLoader)getApplicationContext();

所以使用它并删除 getNewApp() 方法。

关于线程中的android应用程序类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9874283/

相关文章:

android - 如何在没有 root 设备的情况下在 system/app 目录中安装 android 应用程序,以便用户无法卸载该应用程序

c++ - 在单独的线程中处理 vector 元素

multithreading - Kotlin 协程 : Waiting for multiple threads to finish

c# - Excel VSTO 异步按钮 - 用户交互的奇怪行为?

cocoa - 核心数据损坏的多线程

java - 如果我在非 EDT 的单个线程上处理 GUI,它仍然是线程安全的吗?

java - Android 应用程序因 RecyclerView 而崩溃

android - Jetpack 撰写 : LazyColumn align each item separately

android - IntelliJ "Make"阶段做了什么?

java - Json AsyncTask - 获取页面内容而不解析