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=""> </LinearLayout> <LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight=""> <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=""
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());
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 :
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 :
Bundle successBundle = (Bundle) msg.obj;
Intent toMainActivityIntent = new Intent();
toMainActivityIntent.putExtras(successBundle);
toMainActivityIntent.setClass(LoginActivity.this, IndexActivity.class);
startActivity(toMainActivityIntent);
break;
case -:
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 = ;
} 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 = ;
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 = -;
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, );
HttpConnectionParams.setSoTimeout(params1, );
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() == ) {
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;
} }
至于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";//接口链接
这个接口里面只是一个简单的登录功能,就不贴出来了。
android 登录和设置IP/端口功能的更多相关文章
- windows 10 防火墙设置规则:允许特定ip端口
本例中以如何设置ip为10.242.62.239的电脑通过3306端口访问我的电脑 为例 1, 打开防火墙高级设置,如图所示,操作如下 入站规则->新建规则->自定义->下一步 2, ...
- [administrator][netctl] 给未插线未UP端口设置IP
以下内容均为使用netctl配置工具前提下: 需求: Tstation管理口做日常使用.没有千兆交换.所以加一个一块千兆的卡.这块卡是为了做数据传输专用的. 目前主要就是每周给T7备份使用.但是由于是 ...
- (转)建站知识:域名/ 空间/ IP/ 端口之间的关系
先说域名解析吧,比如说你的域名是 www.sunnymould.com,这个域名对应着一个IP地址,域名解析就是把上面的域名转换成这个IP地址的过程,这样你就可以域名访问了上面地址上的内容了. 端口映 ...
- android模拟器与PC的端口映射(转)
阅读目录 一.概述 二.实现步骤 回到顶部 一.概述 Android系统为实现通信将PC电脑IP设置为10.0.2.2,自身设置为127.0.0.1,而PC并没有为Android模拟器系统指定IP,所 ...
- android模拟器与PC的端口映射
一.概述 Android系统为实现通信将PC电脑IP设置为10.0.2.2,自身设置为127.0.0.1,而PC并没有为Android模拟器系统指定IP,所以PC电脑不能通过IP来直接访问Androi ...
- Android课程---Android Studio简单设置
Android Studio 简单设置 界面设置 默认的 Android Studio 为灰色界面,可以选择使用炫酷的黑色界面.Settings-->Appearance-->Theme, ...
- 【转】Android Studio简单设置
原文网址:http://ask.android-studio.org/?/article/14 Android Studio 简单设置 界面设置 默认的 Android Studio 为灰色界面,可以 ...
- 【转】如何在vmware中如何设置ip
如何在vmware中如何设置ip 1.修改网络接口选hostonly2.虚拟机里安装vmware-tool,对鼠标和图形进行更好地支持.如果你在图形界面下,首先要切换到文本模式.右键点击桌面,打开一个 ...
- 简单 TCP/IP 服务功能
本主题使用每台 Windows 计算机上提供的 Echo 和 Quote of the Day 服务.在所有 Windows 版本中都提供了简单 TCP/IP 服务功能.该功能会提供了以下服务:Cha ...
随机推荐
- windows WEB 高可用/可伸缩
windows NLB+ARR实现Web负载均衡高可用/可伸缩 基于IIS的ARR负载均衡 基于NLB负载均衡 这两篇分别分ARR 和 NLB基本配置,下面我们讲讲,如何组合使用,搭配成高可用/可 ...
- xshell --- 查看和关闭 进程
netstat -apn | grep 80 kill -l PID 关闭进程
- spring源码分析之@Conditional
根源在AnnotationConfigApplicationContext和AnnotationConfigWebApplicationContext,以AnnotationConfigApplica ...
- vue 中表单 [v-bind:true-value="a" v-bind:false-value="b"] 的用法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 用Vue.js来实现城市三级联动
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...
- 如何使用定时器settimeout、setInterval执行能传递参数的函数(转)
来自: http://www.cnblogs.com/wkylin/archive/2012/09/07/2674911.html var userName="jack";//根据 ...
- POJ 1874 畅通工程续(最短路模板题)
畅通工程续 Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submi ...
- DG查看恢复进度
查看恢复进度 (1)查看进程的活动状态 V$MANAGED_STANDBY视图专用于显示物理Standby数据库相关进程的当前状态,该视图中的列也很有特点,查看进程状态时,通常我们会关注PROCESS ...
- Trie&可持久化Trie
WARNING:以下代码未经测试,若发现错误,欢迎指出qwq~ Trie树(字典树) 一种简单的数据结构,可存储大量字符串,可在$O(len)$的时间内完成插入,删除,查找等操作. 下面是一个简单的例 ...
- BZOJ4817: [Sdoi2017]树点涂色(LCT)
Description Bob有一棵n个点的有根树,其中1号点是根节点.Bob在每个点上涂了颜色,并且每个点上的颜色不同.定义一条路 径的权值是:这条路径上的点(包括起点和终点)共有多少种不同的颜色. ...