Android:Day03_完美登录案例(使用流和文件来保存登录信息)

                                        Day03_完美登录案例

目录

                                        Day03_完美登录案例

一、项目目录结构

二、类和文档(按项目目录结构排序)

1、类:LoginSace

2、类:MainActivity 

3、AndroidManifest.xml

4、activity_main.xml


一、项目目录结构

二、类和文档(按项目目录结构排序)

1、类:LoginSace

package com.example.loginperfect;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

import android.content.Context;
import android.os.Environment;
import android.provider.MediaStore.Video;
import android.view.View;
import android.widget.Toast;

public class LoginSace {

	//1.保存用户信息到手机T卡
	public static boolean saveinfobycontext(String username, String pwd){
		
		//1.将信息合并为一整条字符串信息
		String infostr=username+"##"+pwd;
		
		File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/tcardinfo.txt");
		//2.得到一个输出流
		try {
			
			FileOutputStream fos=new FileOutputStream(file);
			fos.write(infostr.getBytes());
			fos.close();
			
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	
	//1.读取用户信息到手机T卡
	public static String readinfofromTcard(){
		
		File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/tcardinfo.txt");
		//2.得到一个输出流
		try {
			FileInputStream fis=new FileInputStream(file);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
			String readLine = bufferedReader.readLine();
			return readLine;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	
	//2.保存用户信息到手机内部路径
	public static boolean saveinfobycontext(Context context, String username, String pwd){
		
		//1.将信息合并为一整条字符串信息
		String infostr=username+"##"+pwd;
		FileOutputStream fos;
		//File file = new File(context.getFilesDir().getAbsolutePath()+"/innerinfo.txt");
		//2.得到一个输出流
		try {
		//	fos=new FileOutputStream(file);
			fos=context.openFileOutput("innerinfo.txt", Context.MODE_PRIVATE);
			fos.write(infostr.getBytes());
			fos.close();
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	
	//2.保存用户信息到手机内部路径
	public static String readinfobycontext(Context context){
		
		//File file = new File(context.getFilesDir().getAbsolutePath()+"/innerinfo.txt");
		//2.得到一个输出流
		try {
		//	fos=new FileOutputStream(file);
			FileInputStream fis=context.openFileInput("innerinfo.txt");
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
			String readLine = bufferedReader.readLine();
			return readLine;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
}

2、类:MainActivity 

package com.example.loginperfect;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private EditText et_username;
	private EditText et_pwd;
	private CheckBox cb_issave;
	private Button bt_login;
	private String strtcard;
	private TextView tv_freespace_ex;
	private TextView tv_totalspace_ex;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		et_username = (EditText)findViewById(R.id.et_username);
		et_pwd = (EditText)findViewById(R.id.et_pwd);
		cb_issave = (CheckBox)findViewById(R.id.cb_issave);
		bt_login = (Button)findViewById(R.id.bt_login);
		
		
		tv_freespace_ex = (TextView)findViewById(R.id.tv_freespace_ex);
		tv_totalspace_ex = (TextView)findViewById(R.id.tv_totalspace_ex);
		
		File externalStorageDirectory = Environment.getExternalStorageDirectory();
		
		//给控件赋值,显示sd卡的剩余空间大小和总空间大小
		tv_freespace_ex.setText(Formatter.formatFileSize(this, externalStorageDirectory.getFreeSpace()));
		tv_totalspace_ex.setText(Formatter.formatFileSize(this, externalStorageDirectory.getTotalSpace()));
				
		
		//打开界面即读取信息
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			strtcard = LoginSace.readinfofromTcard();
		}else {
			strtcard = LoginSace.readinfobycontext(MainActivity.this);
		}
		
		
		//读取其它应用的私有文件
		
		
		//判断字符串是否为空
		if(strtcard != null) {
			String[] name_pwd = strtcard.split("##");
			et_username.setText(name_pwd[0]);
			et_pwd.setText(name_pwd[1]);
		}
		
		
		//2.设置登录监听事件
		bt_login.setOnClickListener(new OnClickListener() {

			private boolean retsave;

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				//1.获取username和pwd
				String username=et_username.getText().toString().trim();
				String pwd=et_pwd.getText().toString().trim();
				
				//2.判断username和pwd是否为空
				if(TextUtils.isEmpty(username)||TextUtils.isEmpty(pwd)) {
					Toast.makeText(MainActivity.this, "username or pwd is null!", Toast.LENGTH_SHORT).show();
				}else {
					if(cb_issave.isChecked()) {
						/*保存登录信息*/
						//判断手机T卡是否挂载
						if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
							//1.保存在手机T卡存储
							retsave=LoginSace.saveinfobycontext(username,pwd);
						}else {
							//2.保存在手机内部存储
							retsave=LoginSace.saveinfobycontext(MainActivity.this, username, pwd);
						}
					}	
					if(retsave) {
						Toast.makeText(MainActivity.this, "save successfully!", Toast.LENGTH_SHORT).show();
					}else {
						Toast.makeText(MainActivity.this, "save fail!", Toast.LENGTH_SHORT).show();;
					}
				}
			}
			
		});
	}
	
	
	//另一种按钮点击事件,方法名字与android:onClick="btreadotherappfile"一致
	public void btreadotherappfile(View v) {
		
		File file = new File("data/data/com.example.login/files/info.txt");

		try {
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
			String readLine = bufferedReader.readLine();
			Toast.makeText(this,readLine, Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(this,"读取失败!", Toast.LENGTH_SHORT).show();
		}
	}

}

3、AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.loginperfect"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="17" />
	
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

4、activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.loginperfect.MainActivity" 
    android:orientation="vertical"
    >

	<EditText 
	    android:id="@+id/et_username"
	    android:layout_width="match_parent"
	    android:layout_height="30dp"
	    android:hint="请输入用户名"
	    android:background="#FF0000"
	    />
    
	<EditText 
	    android:id="@+id/et_pwd"
	    android:layout_width="match_parent"	
	    android:layout_height="30dp"
	    android:hint="请输入密码"
	    android:inputType="textPassword"
	    android:background="#00FF00"
	    />
    
    
	<LinearLayout 
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:orientation="horizontal"
	    >
    	<CheckBox 
    	    android:id="@+id/cb_issave"
    	    android:layout_width="0dp"
    	    android:layout_height="wrap_content"
    	    android:layout_weight="1"
    	    android:text="是否保存登录信息"
    	   
    	    />
    
    	<Button 
    	    android:id="@+id/bt_login"
    	    android:layout_width="wrap_content"
    	    android:layout_height="wrap_content"
    	    android:text="登录"
    	    />
	</LinearLayout>
		
	<LinearLayout 
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:orientation="horizontal"
	    >
    <TextView 
		    android:id="@+id/tv_freespace"
		    android:layout_width="wrap_content"
		    
		    android:layout_height="wrap_content"
		    android:text="剩余空间大小:"
		    />
		<TextView 
		    android:id="@+id/tv_freespace_ex"
		    android:layout_width="0dp"
		    android:layout_weight="1"
		    android:layout_height="wrap_content"
		    android:hint="剩余空间大小"
		    />
	</LinearLayout>
		<LinearLayout 
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:orientation="horizontal"
	    >
    <TextView 
		    android:id="@+id/tv_totalspace"
		    android:layout_width="wrap_content"
		    
		    android:layout_height="wrap_content"
		    android:text="总空间大小:"
		    />
		<TextView 
		    android:id="@+id/tv_totalspace_ex"
		    android:layout_width="0dp"
		    android:layout_weight="1"
		    android:layout_height="wrap_content"
		    android:hint="总空间大小"
		    />
	</LinearLayout>
	
	<LinearLayout 
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:orientation="horizontal"
	    >
	    <Button 
	        android:id="@+id/bt_read"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:background="#ff00ff"
	        android:text="读取其它私有文件"
	        android:onClick="btreadotherappfile"
	        />
	    
	    
	</LinearLayout>
</LinearLayout>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值