我有一个依赖异步void操作的程序-它们在后台执行,并且任何地方都不需要它们的结果。
但是,有时它们会引发导致整个应用程序崩溃的异常。
我发现有可能在.NET Framework中防止此行为的信息,但是我正在使用.NET Core 2.1,在这种情况下,设置public class MainActivity extends AppCompatActivity {
Connection connection = null;
Channel ch = null;
ConnectionFactory factory = new ConnectionFactory();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupConnectionFactory();
publishToAMQP();
setupPubButton();
}
void setupPubButton() {
Button button = (Button) findViewById(R.id.publish);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
EditText et = (EditText) findViewById(R.id.text);
publishMessage(et.getText().toString());
et.setText("");
}
});
}
public void setupConnectionFactory() {
try {
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
factory.setHost("localhost");
factory.setPort(5672);
Log.d("","foi");
}
catch(Exception e){
Log.d("IOAJSOIUA", e.getMessage());
}
}
public void publishToAMQP()
{
Thread connectChannel = new Thread(new Runnable() {
@Override
public void run() {
try {
connection = factory.newConnection();
ch = connection.createChannel();
ch.queueDeclare("chat", false, false, false, null);
ch.exchangeDeclare("amq.topic", "topic",true);
ch.queueBind("amq.topic", "chat", null);
Log.d("", "isso");
} catch (Exception e) {
Log.d("", "Connection broken: " + e.getClass().getName());
}
}
});
connectChannel.start();
}
void publishMessage(String message) {
Thread publishMessage = new Thread(new Runnable() {
@Override
public void run() {
try {
ch.basicPublish("amq.topic", "chat", null, message.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
});
publishMessage.start();
}
}
似乎无效。
我能够使用E/AndroidRuntime: FATAL EXCEPTION: Thread-4
Process: com.example.youssef.chatbot, PID: 11432
java.lang.NullPointerException: Attempt to invoke interface method 'void com.rabbitmq.client.Channel.basicPublish(java.lang.String, java.lang.String, com.rabbitmq.client.AMQP$BasicProperties, byte[])' on a null object reference
at com.example.youssef.chatbot.Activities.Activities.MainActivity$3.run(MainActivity.java:89)
at java.lang.Thread.run(Thread.java:764)
记录有关这些异常的信息,但不允许我处理这些异常。
还有其他方法可以防止应用程序崩溃吗?