import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
public static FileService fileService = null;
// 声明获取得用户与密码的组件
public EditText edit_name, edit_pass;
// 声明登陆按钮对象
public Button btn_login;
// 声明CheckBox组件对象
public CheckBox box_remember;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置显示视图
setContentView(R.layout.activity_login);
// 实例化业务对象
fileService = new FileService(this);
edit_name = (EditText) findViewById(R.id.edit_name);
edit_pass = (EditText) findViewById(R.id.edit_pass);
btn_login = (Button) findViewById(R.id.btn_login);
box_remember = (CheckBox) findViewById(R.id.file_Chickbox);
btn_login.setOnClickListener(new MyOnClickListener());
// 回显数据
Map
if (map != null) {
edit_name.setText(map.get("edit_name"));
edit_pass.setText(map.get("edit_pass"));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
// 内部类
class MyOnClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
int id = v.getId();
if (id == btn_login.getId()) {
String name = edit_name.getText().toString();
String pass = edit_pass.getText().toString();
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pass)) {
Toast.makeText(LoginActivity.this, "用户名或密码不能为空",
Toast.LENGTH_LONG).show();
return;
} else {
// 如果记住密码勾选上了
if (box_remember.isChecked()) {
// 进行保存
// 调用业务对象的业务方法
LoginActivity.this.fileService.saveToRom(name, pass,
"private.txt");
Toast.makeText(LoginActivity.this, "用户名和密码需要保存",
Toast.LENGTH_LONG).show();
} else {
// 不保存
Toast.makeText(LoginActivity.this, "用户名和密码不需要保存",
Toast.LENGTH_LONG).show();
}
}
}
}
}
}
[java]
[java]
[java]
html name="code">package com.example.lession02_file.service;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import com.example.lession02_file.util.StreamTools;
import android.content.Context;
public class FileService {
// 上下文的对象
public Context context;
public FileService(Context context) {
this.context = context;
}
/**
* 往手机内存上存储用户名与密码的操作
*
* @param name
* @param pass
* @param fileName
* @return
*/
public boolean saveToRom(String name, String pass, String fileName) {
// 上下文对象的api
try {
// 通过openFileOutput()方法获取一个文件的输出流对象
FileOutputStream fos = context.openFileOutput(fileName,
Context.MODE_PRIVATE);
// 拼接用户名与密码
String result = name + ":" + pass;
// 写入
fos.write(result.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true