我需要在使用 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/