如何在处理程序中使用ApplicationContext
我真的是Android的新手,我试图将线程类与消息处理程序一起使用,在那里,我需要使用ApplicationContext,但是当我尝试运行它时,这是使应用程序崩溃的
if (!connected.isState()) {
client = new MqttAndroidClient(myContext.context, SERVERURI, CLIENTID);
try {
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
//we are connected
connected.setState(true);
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
//we are not connected
}
});
} catch (Exception e) {
e.printStackTrace();
}
return;
}
代码mycontext类
class myContext extends Application {
public static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
} 我该怎么办来解决这个问题?
i am really new to Android and i was trying to use the Thread class with a message handler, in there i need to use the ApplicationContext but when i try to run it it crashes, here is the code that makes the application crash
if (!connected.isState()) {
client = new MqttAndroidClient(myContext.context, SERVERURI, CLIENTID);
try {
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
//we are connected
connected.setState(true);
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
//we are not connected
}
});
} catch (Exception e) {
e.printStackTrace();
}
return;
}
here is the myContext class
class myContext extends Application {
public static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
}
what can i do to fix the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能没有告诉Android使用您的自定义
application
类,因此myContext.oncreate()
未被调用。为此You probably haven't told Android to use your custom
Application
class, somyContext.onCreate()
isn't being called. To do this you need to add this to your<application>
declaration in your manifest:OP在这里。
最后,我通过发送包含message.obj中applicationContext的消息来解决它,这是现在的代码,
感谢大家的建议并跟上我的不经验
:--)
OP here.
in the end i solved it by sending a message containing the applicationContext in message.obj, here is the code now
thanks to everybody for the suggestions and for keeping up with my inexperience
:-)