android登录和设置IP/端口功能

本人第一个android开发功能:登录以及设置IP/端口。

本人是j2ee开发工程师,所以这个可能有一些处理不太完善的地方,欢迎评论在下面,我会认真改进的。

首先是配置strings.xml文件添加用到的参数:res/values/strings.xml

<resources>
	<!-- 登录 -->
	<string name="login_name">帐号:</string>
	<string name="login_pwd">密码:</string>
	<string name="remember_pwd">记住密码</string>
	<string name="auto_login">自动登录</string>
	<string name="login">登录</string>
	<string name="setting">设置</string>
	<string name="ip">IP:</string>
	<string name="port">端口:</string>
	<string name="is_logining_in">正在登录...</string>
	<string name="login_http_error">网络异常,请重新登录</string>
</resources>

其次是布局文件:res/layout/activity_login.xml(背景图片不提供)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:orientation="vertical" 
	android:background="@drawable/login_background">
	
    <LinearLayout android:layout_width="fill_parent"
		android:layout_height="fill_parent"
		android:orientation="horizontal"
		android:layout_weight="1">
		
	</LinearLayout>
    
    <LinearLayout android:layout_width="fill_parent"
		android:layout_height="fill_parent"
		android:orientation="vertical"
		android:layout_weight="1">
	
	    <LinearLayout android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:orientation="horizontal"
			android:gravity="center">
	
			<TextView android:textSize="8pt" 
			    android:id="@+id/tv_login_name" 
			    android:text="@string/login_name"
				android:layout_width="wrap_content" 
				android:layout_height="wrap_content"
				android:textAppearance="@style/AppTheme"
				android:textColor="@color/black"/>
		        
		        <EditText android:id="@+id/et_login_name"
				android:layout_width="200dp"
				android:layout_height="wrap_content"
				android:inputType="text"
				android:singleLine="true"/>
		</LinearLayout>
		      
	    <LinearLayout android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:orientation="horizontal"
			android:gravity="center">
		        
		        <TextView android:textSize="8pt" 
				android:id="@+id/tv_password" 
				android:text="@string/login_pwd"
				android:layout_width="wrap_content" 
				android:layout_height="wrap_content"
				android:textColor="@color/black"/>
		      
			<EditText android:id="@+id/et_password"
				android:layout_width="200dp"
				android:layout_height="wrap_content"
				android:inputType="textPassword"
				android:singleLine="true"/>
		</LinearLayout>
		
	    <LinearLayout android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:orientation="vertical"
			android:gravity="center">	
			
			<CheckBox android:id="@+id/cb_remember_pwd"
				android:layout_width="wrap_content"
				android:layout_height="wrap_content"
				android:text="@string/remember_pwd"
				android:textColor="@color/black" />
		
			<CheckBox android:id="@+id/cb_auto_login"
				android:layout_width="wrap_content"
				android:layout_height="wrap_content"
				android:text="@string/auto_login"
				android:textColor="@color/black" />
		</LinearLayout>
	
	</LinearLayout>
	
	<LinearLayout android:layout_width="fill_parent"
		android:layout_height="fill_parent"
		android:orientation="horizontal"
		android:layout_weight="1"
		android:gravity="center">
	
		<Button android:text="@string/login" 
			android:textSize="9pt" 
			android:id="@+id/btn_login" 
			android:layout_width="wrap_content" 
			android:layout_height="wrap_content"/>
	     
		<Button android:text="@string/cancel" 
			android:textSize="9pt" 
			android:id="@+id/btn_cancel" 
			android:layout_width="wrap_content" 
			android:layout_height="wrap_content"/>
		
		<Button android:text="@string/setting" 
			android:textSize="9pt" 
			android:id="@+id/btn_setting" 
			android:layout_width="wrap_content" 
			android:layout_height="wrap_content"/>
	
	</LinearLayout>	
</LinearLayout>

再来是主要的activity:LoginActivity.java
package com.chinawiserv.itsm.android;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.chinawiserv.itsm.android.app.Itsm;
import com.chinawiserv.itsm.android.util.HttpUtil;
import com.chinawiserv.itsm.android.util.PropertiesUtil;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class LoginActivity extends BaseActivity implements OnClickListener {

	private EditText etLoginName, etPassword;
	private Button btnLogin, btnCancel, btnSetting;
	private CheckBox cbRememberPwd, cbAutoLogin;
	private String loginNameValue, passwordValue;
	private Bundle loginBundle = new Bundle();// 传递数据
	private Properties properties;// 保存登录配置信息
	private ProgressDialog pd;// 访问接口等待进度条
	private EditText et_host, et_port;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		findViews();
		setListeners();

		// 判断记住密码多选框的状态
		if ("true".equals(properties.getProperty("isRememberPwd"))) {
			cbRememberPwd.setChecked(true);
			etLoginName.setText(properties.getProperty("loginName"));
			etPassword.setText(properties.getProperty("pwd"));
			// 判断自动登陆多选框状态
			if ("true".equals(properties.getProperty("isAutoLogin"))) {
				// 设置默认是自动登录状态
				cbAutoLogin.setChecked(true);
				// 跳转界面
				login();
			}
		}
		// 监听记住密码多选框按钮事件
		cbRememberPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (cbRememberPwd.isChecked()) {// 记住密码
					properties.setProperty("isRememberPwd", "true");
				} else {// 取消记住密码同时取消记住自动登录
					cbAutoLogin.setChecked(false);
					properties.setProperty("isRememberPwd", "false");
					properties.setProperty("isAutoLogin", "false");
				}
			}
		});
		// 监听自动登录多选框事件
		cbAutoLogin.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (cbAutoLogin.isChecked()) {// 自动登录同时记住密码
					cbRememberPwd.setChecked(true);
					properties.setProperty("isRememberPwd", "true");
					properties.setProperty("isAutoLogin", "true");
				} else {// 取消自动登录
					properties.setProperty("isAutoLogin", "false");
				}
			}
		});
	}

	private void findViews() {
		properties = PropertiesUtil.loadConfig(LoginActivity.this);// 加载资源信息
		etLoginName = (EditText) findViewById(R.id.et_login_name);
		etPassword = (EditText) findViewById(R.id.et_password);
		cbRememberPwd = (CheckBox) findViewById(R.id.cb_remember_pwd);
		cbAutoLogin = (CheckBox) findViewById(R.id.cb_auto_login);
		btnLogin = (Button) findViewById(R.id.btn_login);
		btnCancel = (Button) findViewById(R.id.btn_cancel);
		btnSetting = (Button) findViewById(R.id.btn_setting);
	}

	private void setListeners() {
		btnLogin.setOnClickListener(LoginActivity.this);
		btnCancel.setOnClickListener(LoginActivity.this);
		btnSetting.setOnClickListener(LoginActivity.this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_login, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.btn_login:// 监听登录按钮事件
			Itsm.HOST = properties.getProperty("userHost");
			Itsm.PORT = properties.getProperty("userPort");
			if (Itsm.HOST == null || "".equals(Itsm.HOST) || Itsm.PORT == null || "".equals(Itsm.PORT)) {
				Toast.makeText(LoginActivity.this, R.string.ipAndPortIsNull, Toast.LENGTH_LONG).show();
			} else {
				login();
			}
			break;
		case R.id.btn_cancel:// 监听取消按钮事件
			finish();
			break;
		case R.id.btn_setting:// 监听设置按钮事件
			showAlertDialog();
			break;
		default:
			break;
		}
	}

	/** 弹出对话框 */
	public void showAlertDialog() {
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.activity_config,
				(ViewGroup) findViewById(R.id.dialog));
		et_host = (EditText) layout.findViewById(R.id.et_host);
		et_port = (EditText) layout.findViewById(R.id.et_port);
		String userHost = properties.getProperty("userHost");
		String userPort = properties.getProperty("userPort");
		if (userHost != null && !"".equals(userHost) && userPort != null && !"".equals(userPort)) {
			et_host.setText(userHost.substring(7));
			et_port.setText(userPort);
		}
		new AlertDialog.Builder(this).setTitle("设置").setView(layout).setPositiveButton("确定", setSureDialogListener()).setNegativeButton("取消", setCancelDialogListener()).show();
	}

	/** 设置弹出框取消事件 */
	public android.content.DialogInterface.OnClickListener setCancelDialogListener() {
		return new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		};
	}

	/** 设置弹出框确定事件 */
	public android.content.DialogInterface.OnClickListener setSureDialogListener() {
		return new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				try {
					CharSequence hostValue = et_host.getText();
					CharSequence portValue = et_port.getText();
					if (hostValue != null && portValue != null) {
						Itsm.HOST = "http://" + hostValue.toString();
						Itsm.PORT = portValue.toString();
						properties.setProperty("userHost", Itsm.HOST);
						properties.setProperty("userPort", Itsm.PORT);
						PropertiesUtil.saveConfig(LoginActivity.this, properties);
						dialog.dismiss();
					} else {
						Toast.makeText(LoginActivity.this, getString(R.string.ipAndPortIsNull), Toast.LENGTH_LONG).show();
					}
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
			}
		};
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				Bundle errorBundle = (Bundle) msg.obj;
				int error = errorBundle.getInt("error");
				String errorMsg = errorBundle.getString("errorMsg");
				Toast.makeText(LoginActivity.this, "错误编号:" + error + "\n错误信息:" + errorMsg, Toast.LENGTH_LONG).show();
				break;
			case 1:
				Bundle successBundle = (Bundle) msg.obj;
				Intent toMainActivityIntent = new Intent();
				toMainActivityIntent.putExtras(successBundle);
				toMainActivityIntent.setClass(LoginActivity.this, IndexActivity.class);
				startActivity(toMainActivityIntent);
				break;
			case -1:
				Toast.makeText(LoginActivity.this,getText(R.string.login_http_error), Toast.LENGTH_LONG).show();
				break;
			default:
				break;
			}
		}
	};

	private void login() {
		loginNameValue = etLoginName.getText().toString();
		passwordValue = etPassword.getText().toString();
		if (loginNameValue == null || "".equals(loginNameValue)) {
			Toast.makeText(LoginActivity.this, "请先输入帐号!", Toast.LENGTH_LONG).show();
		} else if (passwordValue == null || "".equals(passwordValue)) {
			Toast.makeText(LoginActivity.this, "请先输入密码!", Toast.LENGTH_LONG).show();
		} else {
			final String loginInUrl = Itsm.HOST + Itsm.COLON + Itsm.PORT + Itsm.LOGIN_IN;
			pd = ProgressDialog.show(LoginActivity.this, "", getString(R.string.is_logining_in));
			new Thread() {
				public void run() {
					Looper.prepare();
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("loginName", loginNameValue));
					params.add(new BasicNameValuePair("pwd", passwordValue));
					Message msg = new Message();
					try {
						String loginResult = HttpUtil.doPost(params, loginInUrl);
						JSONObject loginJson = new JSONObject(loginResult);
						boolean flag = loginJson.getBoolean("flag");
						if (!flag) {
							int error = loginJson.getInt("error");
							String errorMsg = loginJson.getString("errorMsg");
							loginBundle.putInt("error", error);
							loginBundle.putString("errorMsg", errorMsg);
							msg.what = 0;
						} else {
							/** 登录成功判断是否记住密码和自动登录 */
							if (cbRememberPwd.isChecked()) {
								properties.setProperty("isRememberPwd", "true");
								properties.setProperty("loginName", loginNameValue);
								properties.setProperty("pwd", passwordValue);
							}
							if (cbAutoLogin.isChecked()) {
								properties.setProperty("isAutoLogin", "true");
							}
							PropertiesUtil.saveConfig(LoginActivity.this,properties);// 登录成功才保存资源信息
							msg.what = 1;
							String userId = loginJson.getString("userId");
							String userName = loginJson.getString("userName");
							String orgId = loginJson.getString("orgId");
							JSONArray roleJson = loginJson.getJSONArray("roles");
							Itsm.USER_ID = userId;
							Itsm.ORG_ID = orgId;
							loginBundle.putString("userId", userId);
							loginBundle.putString("userName", userName);
							loginBundle.putString("orgId", orgId);
							loginBundle.putString("roleJson", roleJson.toString());
						}
						msg.obj = loginBundle;
						handler.sendMessage(msg);
					} catch (JSONException e) {
						msg.what = -1;
						handler.sendMessage(msg);
						e.printStackTrace();
					} finally {
						pd.dismiss();
						Looper.loop();
					}
				}
			}.start();
		}
	}

}

其中自定义的:HttpUtil.java
package com.chinawiserv.itsm.android.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

import com.chinawiserv.itsm.android.app.Itsm;

public class HttpUtil {
	
	public static String doPost(List<NameValuePair> params, String url) {
		HttpPost post = new HttpPost(url);
		String str = "";
		Log.d(Itsm.TAG, "调用post请求方法,请求接口为:" + url);
		HttpClient httpClient = new DefaultHttpClient();
		HttpParams params1 = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params1, 10000);
		HttpConnectionParams.setSoTimeout(params1, 15000);
		try {
			post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

			HttpResponse response = httpClient.execute(post);
			Log.d(Itsm.TAG, "状态:" + response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == 200) {
				str = EntityUtils.toString(response.getEntity(), "UTF-8");
				Log.d(Itsm.TAG, "结果:" + str);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return Itsm.HTTP_ERROR;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return Itsm.HTTP_ERROR;
		} catch (IOException e) {
			e.printStackTrace();
			return Itsm.HTTP_ERROR;
		}
		return str;
	}

}


自定义的:PropertiesUtil.java

package com.chinawiserv.itsm.android.util;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;

import android.content.Context;

public class PropertiesUtil {
	public static Properties loadConfig(Context context) {
		Properties properties = new Properties();
		InputStream s = null;
		try {
			s = context.openFileInput("itsm_cfg.properties");
			properties.load(s);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return properties;
	}

	public static void saveConfig(Context context, Properties properties) {
		try {
			FileOutputStream s = context.openFileOutput("itsm_cfg.properties",Context.MODE_PRIVATE);
			properties.store(s, "");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

至于Itsm,其中只是定义了一些参数,可以声明在当前的LoginActivity里面:

public static final String HTTP_ERROR = "-1";//访问链接错误
public static String HOST = "http://192.168.1.157";
public static String COLON = ":";
public static String PORT = "8090";
public static final String LOGIN_IN = "/itsm/http/loginMobLoginResultAction.action";//接口链接

这个接口里面只是一个简单的登录功能,就不贴出来了。



希望这些简单的布局以及简单的登录功能,可以帮上初学者,因为我也是刚摸索出来的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

莫欺少年穷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值