一个android应用,先保存用户的手机号、确认网络连接打开、GPS打开,然后跟远程服务器建立连接,自己GPS定位。
保存用户的手机号、提示打开网络连接、提示打开GPS,用了3个Dialog。在Activity的onCreate()方法里面先判断前面3个条件是否满足,不满足就显示Dialog,为了不让3个Dialog挤在一起,用了下面的代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if((myPhoneNumber = getMyPhoneNumber()) == null){
showDialog(DIALOG_MY_PHONE_NUMBER);
} else if (!isNetworkConnected()){
showDialog(DIALOG_NETWORK);
} else if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showDialog(DIALOG_GPS);
} else {
……
//跟远程服务器建立连接
//GPS定位
……
}
}
Dialog定义在
@Override
protected Dialog onCreateDialog(int id){
Dialog dialog = null;
switch(id){
case DIALOG_MY_PHONE_NUMBER:
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
final View dialogView = factory.inflate(R.layout.phone_number_dialog, (ViewGroup)findViewById(R.id.layout_root));
dialog = new AlertDialog.Builder(MainActivity.this)
.setTitle("手机号码设置")
.setView(dialogView)
.setPositiveButton("设置", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
EditText text = (EditText)dialogView.findViewById(R.id.my_phone_number);
SharedPreferences settings = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("myPhoneNumber", text.getText().toString());
editor.commit();
Intent intent = new Intent();
intent.setClass(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(intent);
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MainActivity.this.finish();
}
})
.create();
break;
case DIALOG_NETWORK:
dialog = new AlertDialog.Builder(MainActivity.this)
.setTitle("网络设置提示")
.setMessage("网络连接不可用,是否进行设置?")
.setPositiveButton("设置", new DialogInterface.OnClickListener() {