前段时间疲于应付考试和各种作业,并没有很多时间来学习android。这几天考试已经结束,又可以学习android了,最好的学习方法就是自己动手编写应用项目,在实践中学习。因此我的学习之路以后都是做小应用来引导。
废话不多说,下面讲讲我的第一个应用Nju-WLAN,每次在学校里用手机登陆校园无线,都要用手机打开浏览器,再登录,感觉很不方便。所以我写了一个android客户端,来方便我的登录。
一、保存用户名密码
这里我盗版了QQ的界面,^_^,
第一个问题就是保存用户名密码。我采用的是java的属性文件来保存,写了一个文件类用来保存用户名密码。
package com.mayday.njuwifi; /** * Created by mayday on 2015/1/14. */ import java.io.FileOutputStream; import android.content.Context; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.io.File; import java.io.FileInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.io.IOException; public class FileService { private Context context; public FileService(Context context){ this.context = context; } /** * 把用户名和密码保存到手机ROM * @param username 要保存的用户名 * @param password 输入要保存的密码 * @param filename 保存到哪个文件 * @return */ public void saveUserInfoToRom(String username,String password,String filename) throws Exception{ Properties pro = new Properties(); pro.setProperty("username", username); pro.setProperty("password", password); File file = new File(context.getFilesDir(),filename); FileOutputStream fos = new FileOutputStream(file); pro.store(fos,filename); fos.flush(); fos.close(); } public Properties getUserInfo(String filename) throws Exception{ try{ File file = new File(context.getFilesDir(),filename); FileInputStream fis = new FileInputStream(file); Properties pro = new Properties(); pro.load(fis); fis.close(); return pro; }catch (Exception e) { e.printStackTrace(); return null; } } public void removeUserInfo(String filename){ try { File file = new File(context.getFilesDir(), filename); file.delete(); } catch (Exception e) { e.printStackTrace(); } } }
在主函数中,如果检查到记住密码被选中,就调用
private FileService fileService;
fileService = new FileService(this);
fileService.saveUserInfoToRom(username, password, "userInfo.properties"); //保存用户名密码到userInfo.properties文件中
如果以前保存,现在不保存
fileService.removeUserInfo("userInfo.properties"); //删除userInfo.properties文件
在下次登录时,就检查是否用这个文件,如果有直接从该文件中得到用户名和密码信息。
try { Properties pro = fileService.getUserInfo("userInfo.properties"); if (!TextUtils.isEmpty(pro.getProperty("username")) && !TextUtils.isEmpty(pro.getProperty("password"))){ nameEdit.setText(pro.getProperty("username")); pwdEdit.setText(pro.getProperty("password")); } }catch(Exception e) { e.printStackTrace(); }
二、Http的post请求
由于要模拟登录,需要采用基于http的post请求
我建了一个类用来处理登录,和退出登录。
package com.mayday.njuwifi; /** * Created by mayday on 2015/1/9. */ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.os.Build; import android.os.StrictMode; public class NJUService { private String username;//用户名 private String password;//密码 private String login_url="http://p.nju.edu.cn/portal/portal_io.do";//登录页面url @TargetApi(Build.VERSION_CODES.GINGERBREAD) @SuppressLint("NewApi") public String login() throws Exception{ System.out.println("login"); StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); String postData = "action=login&username="+username+"&password="+password; URL url = new URL(login_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(20000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); OutputStreamWriter out= new OutputStreamWriter(conn.getOutputStream()); out.write(postData); out.flush(); out.close(); InputStream ins = conn.getInputStream(); String charset = "UTF-8"; InputStreamReader inr = new InputStreamReader(ins, charset); BufferedReader br = new BufferedReader(inr); String line = ""; StringBuffer sb = new StringBuffer(); while((line = br.readLine())!=null) { sb.append(line); } inr.close(); ins.close(); conn.disconnect(); return sb.toString(); } public NJUService(){} public NJUService(String username, String password){ this.username=username; this.password=password; } @TargetApi(Build.VERSION_CODES.GINGERBREAD) @SuppressLint("NewApi") public String logout() throws Exception{ System.out.println("logout"); StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); String postData = "action=logout"; URL url = new URL(login_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); OutputStreamWriter out= new OutputStreamWriter(conn.getOutputStream()); out.write(postData); out.flush(); out.close(); InputStream ins = conn.getInputStream(); String charset = "UTF-8"; InputStreamReader inr = new InputStreamReader(ins, charset); BufferedReader br = new BufferedReader(inr); String line = ""; StringBuffer sb = new StringBuffer(); while((line = br.readLine())!=null) { sb.append(line); } inr.close(); ins.close(); conn.disconnect(); return sb.toString(); } }
提交用户名密码到http://p.nju.edu.cn/portal/portal_io.do并得到返回信息。
三、判断当前wifi和gprs功能开启或关闭
我想让这个应用可以自动关闭gprs移动流量,并打开无线连入NJU-wlan
建了一个类用来管理无线
package com.mayday.njuwifi; /** * Created by mayday on 2015/1/15. */ import android.net.wifi.WifiManager; import android.net.wifi.WifiConfiguration; public class WifiAdmin { private WifiManager wifiManager; public WifiAdmin(WifiManager wifiManager){ this.wifiManager = wifiManager; } public void connect(String ssid) { Thread thread = new Thread(new ConnectRunnable(ssid)); thread.start(); } private WifiConfiguration createWifiInfo(String SSID) { WifiConfiguration config = new WifiConfiguration(); config.allowedAuthAlgorithms.clear(); config.allowedGroupCiphers.clear(); config.allowedKeyManagement.clear(); config.allowedPairwiseCiphers.clear(); config.allowedProtocols.clear(); config.SSID = """ + SSID + """; config.wepKeys[0] = ""; config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); config.wepTxKeyIndex = 0; return config; } public void disConnect(String ssid){ WifiConfiguration wifiConfig = createWifiInfo(ssid); int netID = wifiManager.addNetwork(wifiConfig); wifiManager.disableNetwork(netID); wifiManager.disconnect(); } class ConnectRunnable implements Runnable { private String ssid; public ConnectRunnable(String ssid) { this.ssid = ssid; } @Override public void run() { WifiConfiguration wifiConfig = createWifiInfo(ssid); int netID = wifiManager.addNetwork(wifiConfig); wifiManager.enableNetwork(netID, true); } } }
通过public void connect(String ssid),在主函数中调用
private WifiManager wifiManager; private WifiAdmin wifiAdmin; wifiManager = (WifiManager)this.getSystemService(this.WIFI_SERVICE); wifiAdmin = new WifiAdmin(wifiManager); if (!wifiManager.isWifiEnabled()) { Toast.makeText(this, "您尚未打开wlan,正在打开wlan", Toast.LENGTH_SHORT).show(); wifiManager.setWifiEnabled(true); while (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) { try { // 为了避免程序一直while循环,让它睡个100毫秒检测…… Thread.sleep(100); } catch (InterruptedException ie) { ie.printStackTrace(); } } Toast.makeText(this, "成功开启wlan功能", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(this, "已开启wlan功能", Toast.LENGTH_SHORT).show(); } wifiAdmin.connect("NJU-WLAN");
GPRS流量
private ConnectivityManager mCM; mCM = (ConnectivityManager)this.getSystemService(this.CONNECTIVITY_SERVICE); boolean isOpen = gprsIsOpenMethod("getMobileDataEnabled"); //为true gprs打开 ,false gprs关闭 if (isOpen){ Toast.makeText(this, "正在关闭GPRS移动流量", Toast.LENGTH_SHORT).show(); setGprsEnable("setMobileDataEnabled", false); }else{ Toast.makeText(this, "当前GPRS移动流量已关闭", Toast.LENGTH_SHORT).show(); } //检测GPRS是否打开 private boolean gprsIsOpenMethod(String methodName) { Class cmClass = mCM.getClass(); Class[] argClasses = null; Object[] argObject = null; Boolean isOpen = false; try { Method method = cmClass.getMethod(methodName, argClasses); isOpen = (Boolean) method.invoke(mCM, argObject); } catch (Exception e) { e.printStackTrace(); } return isOpen; } //开启/关闭GPRS private void setGprsEnable(String methodName, boolean isEnable) { Class cmClass = mCM.getClass(); Class[] argClasses = new Class[1]; argClasses[0] = boolean.class; try { Method method = cmClass.getMethod(methodName, argClasses); method.invoke(mCM, isEnable); } catch (Exception e) { e.printStackTrace(); } }
判断当前gprs流量开启的话,就关闭gprs移动流量。
四、Intent跳转和传值
只需要在后面加上你要跳转的avtivity.class,startActivity(it),就可实现跳转
Intent it = new Intent(this,loginSuccess.class);
it.putExtra("reply",reply);
startActivity(it);
it.putExtra("reply",reply);前面的是你传值的参数名字,后面是你传的真实值
在loginSuccess中,
Intent intent = getIntent();
String reply = intent.getStringExtra("reply");
就可得到传递的值。
第一个程序大概功能就是这样,里面很多东西都是从网上别的博客找到的。这虽然是一个很小的应用但涵盖了很多android知识。有必要把一些东西再系统详细的学习下。
稍后我将会把我的整个程序放到github上。