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 ...
随机推荐
- 比MD5 和HMAC还要安全的加密 - MD5 加时间戳
//1.给一个字符串进行MD5加密 NSString *passKey = @"myapp"; passKey = [passKey md5String]; //2.对第一步中得到 ...
- Unity中uGUI的控件事件穿透逻辑
1.正常来说Image和Text是会拦截点击事件的,假设加入EventTrigger的话,就能够响应相应的交互事件. 2.假设Image和Text是一个Button的子控件.那么尽管其会显示在Butt ...
- 洛谷P3383 【模板】线性筛素数(Miller_Rabin)
题目描述 如题,给定一个范围N,你需要处理M个某数字是否为质数的询问(每个数字均在范围1-N内) 输入输出格式 输入格式: 第一行包含两个正整数N.M,分别表示查询的范围和查询的个数. 接下来M行每行 ...
- Sql Server 基础语法
来自:http://www.cnblogs.com/AaronYang/archive/2012/04/24/2468093.html Sql Server 基础语法 -- 查看数据表 select ...
- AC自己主动机模板
AC自己主动机模板-- /* * AC自己主动机模板 * 用法: * 1.init() : 初始化函数 * 2.insert(str) : 插入字符串函数 * 3.build() : 构建ac自己主动 ...
- ios学习之block初探
1. block概念 block是ios4.0+和Mac osX 10.6以后引进的对C语言的拓展,用来实现匿名函数的特性.所谓匿名函数,也称闭包函数.即同意创建一个暂时的没有指定名称的函数. 最经经 ...
- QTemporaryDir及QTemporaryFile建立临时目录及文件夹(创建一个随机名称的目录或文件,两者均能保证不会覆盖已有文件)
版权声明:若无来源注明,Techie亮博客文章均为原创. 转载请以链接形式标明本文标题和地址:本文标题:QTemporaryDir及QTemporaryFile建立临时目录及文件夹 本文地址: ...
- android中图片倒影、圆角效果重绘
本文用来记录一些Android 操作图片的方法,方便查看. 1.将Drawable转化为Bitmap public static Bitmap drawableToBitmap(Drawable dr ...
- transfer learning(matlab 实现)
一句话总结 transfer learning 的核心即是对一个已训练模型微调,使其适应新的应用,如下图示: 为 matlab 接口所训练完成的经典深度神经网络下载地址:Index of /matco ...
- InstallShield详细制作说明(三)
八.许可协议 打开[Installation Designer]->[Behavior and Logic]->[Support Files/Billboards]面板 这里[Langua ...