我对这个机器人的事情很新鲜,所以我仍然对某些概念感到困惑。我想要做的是,当我在我的启动画面时,当用户没有连接到互联网时显示AlertDialog。我试图在很多方面做到这一点,但我永远不会持有线程,所以我总是得到一个例外,因为活动在关闭对话框之前关闭。我试过用Handler做这个但没有成功......部分代码在这里:
public class Splash extends Activity {
public void openDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
// set title
alertDialogBuilder.setTitle(R.string.app_name);
// set dialog message
alertDialogBuilder
.setMessage(R.string.dialogo_net)
.setCancelable(false)
.setPositiveButton("Sair",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Splash.this.finish();
}
})
.setNegativeButton("Definições",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Intent intent = new Intent(Settings.ACTION_SETTINGS);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(intent);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
Handler mHandler = new Handler()
{
public void handleMessage(Message msg)
{
openDialog();//Display Alert
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread logoTimer = new Thread() {
public void run(){
try{
int logoTimer = 0;
while(logoTimer < 2000){
sleep(100);
logoTimer = logoTimer +100;
};
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnectedOrConnecting()) {
//opens the dialog in this case
mHandler.sendEmptyMessage(0);
} else {
//goes to main activity
startActivity(new Intent("pt.aeist.mobile.START")); }
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
finish();
}
}
};
logoTimer.start();
}
}
答案 0 :(得分:0)
Thread logoTimer = new Thread()
{
public void run(){
try{
sleep(2000);
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnectedOrConnecting())
{
mHandler.sendEmptyMessage(0);
} else
{
startActivity(new Intent("pt.aeist.mobile.START")); }
finish();
}
}catch(Exception e)
{
e.printStackTrace();
}
}
};
logoTimer.start();
答案 1 :(得分:0)
//分别处理finish()。
.setNegativeButton("Definições",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Intent intent = new Intent(Settings.ACTION_SETTINGS);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(intent);
finish();
}
});
答案 2 :(得分:0)
从所有地方删除finish()。检查一下。
您必须确定要放置finish()的情况;