本人第一个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/端口功能的更多相关文章

  1. windows 10 防火墙设置规则:允许特定ip端口

    本例中以如何设置ip为10.242.62.239的电脑通过3306端口访问我的电脑 为例 1, 打开防火墙高级设置,如图所示,操作如下 入站规则->新建规则->自定义->下一步 2, ...

  2. [administrator][netctl] 给未插线未UP端口设置IP

    以下内容均为使用netctl配置工具前提下: 需求: Tstation管理口做日常使用.没有千兆交换.所以加一个一块千兆的卡.这块卡是为了做数据传输专用的. 目前主要就是每周给T7备份使用.但是由于是 ...

  3. (转)建站知识:域名/ 空间/ IP/ 端口之间的关系

    先说域名解析吧,比如说你的域名是 www.sunnymould.com,这个域名对应着一个IP地址,域名解析就是把上面的域名转换成这个IP地址的过程,这样你就可以域名访问了上面地址上的内容了. 端口映 ...

  4. android模拟器与PC的端口映射(转)

    阅读目录 一.概述 二.实现步骤 回到顶部 一.概述 Android系统为实现通信将PC电脑IP设置为10.0.2.2,自身设置为127.0.0.1,而PC并没有为Android模拟器系统指定IP,所 ...

  5. android模拟器与PC的端口映射

    一.概述 Android系统为实现通信将PC电脑IP设置为10.0.2.2,自身设置为127.0.0.1,而PC并没有为Android模拟器系统指定IP,所以PC电脑不能通过IP来直接访问Androi ...

  6. Android课程---Android Studio简单设置

    Android Studio 简单设置 界面设置 默认的 Android Studio 为灰色界面,可以选择使用炫酷的黑色界面.Settings-->Appearance-->Theme, ...

  7. 【转】Android Studio简单设置

    原文网址:http://ask.android-studio.org/?/article/14 Android Studio 简单设置 界面设置 默认的 Android Studio 为灰色界面,可以 ...

  8. 【转】如何在vmware中如何设置ip

    如何在vmware中如何设置ip 1.修改网络接口选hostonly2.虚拟机里安装vmware-tool,对鼠标和图形进行更好地支持.如果你在图形界面下,首先要切换到文本模式.右键点击桌面,打开一个 ...

  9. 简单 TCP/IP 服务功能

    本主题使用每台 Windows 计算机上提供的 Echo 和 Quote of the Day 服务.在所有 Windows 版本中都提供了简单 TCP/IP 服务功能.该功能会提供了以下服务:Cha ...

随机推荐

  1. Resize图片

    在网站上传图片的时候,提示图片太大了. 有5种方式来调整图片大小 http://www.wikihow.com/Resize-a-JPEG picresize.com 这个网站比较靠谱:使用Windo ...

  2. POJ 3042 区间DP(费用提前计算相关的DP)

    题意: 思路: f[i][j][1]表示从i到j的区间全都吃完了 现在在j点 变质期最小是多少 f[i][j][0]表示从i到j的区间全都吃完了 现在在i点 变质期最小是多少 f[i][j][0]=m ...

  3. BZOJ4652: [Noi2016]循环之美(莫比乌斯反演,杜教筛)

    Description 牛牛是一个热爱算法设计的高中生.在他设计的算法中,常常会使用带小数的数进行计算.牛牛认为,如果在 k  进制下,一个数的小数部分是纯循环的,那么它就是美的.现在,牛牛想知道:对 ...

  4. echo---打印变量或输出字符串

    cho命令用于在shell中打印shell变量的值,或者直接输出指定的字符串.linux的echo命令,在shell编程中极为常用, 在终端下打印变量value的时候也是常常用到的,因此有必要了解下e ...

  5. Python-Flask项目开发--为什么需要搭建虚拟环境?

    在使用python开发过程中,需要使用到某些工具包/框架等,需要联网下载.   例如,联网安装Flask框架flask-0.10.1版本:pip install flask==0.10.1   此时, ...

  6. 【习题 8-6 UVA - 1611】 Crane

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 想把数字i从位置j移动到位置i 可以这样. 假设mov(x,y)表示将(x..x+len/2-1)和(x+len/2..y)交换. ...

  7. [Android] 图像各种处理系列文章合集

        这是我近期在做Android随手拍一个项目的各种网上关于图片处理的资料,曾经学过数字图像处理都是用C++写的,以下的资料个人觉得是很优秀的各种集合,还有一方面它是在线笔记,希望对大家有所帮助吧 ...

  8. android 自己定义View之SubmitView

    转载请注明出处:王亟亟的大牛之路 近期看了一大堆的自己定义View多数都能够充当耗时操作的交互界面.再接再厉再传一个SubmitView.一个和可用于模仿提交等待与用户交互用的一个自己定义View 效 ...

  9. Nginx系列(一)--nginx是什么?

    一.介绍 Nginx是一个高性能的HTTP和反向代理server,也是一个IMAP/POP3/SMTP代理server. Nginx是一款轻量级的Webserver/反向代理server以及电子邮件代 ...

  10. 分享一段php获取随意时间的前一天代码

    <?php /** * 获取给定日期的前一天 * @param string $date * @return string $yesterday */ function getYesterday ...