实例介绍
【实例简介】
【实例截图】
【核心代码】
package com.hext.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.loveplusplus.update.UpdateChecker;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
/**
* 文件管理器
*
* @author HEXT(贺小钿)
*
*/
public class MainActivity extends FragmentActivity {
protected static final String APP_UPDATE_SERVER_URL = "http://update.hexiaotian.cn/file.json"; // "http://192.168.205.33:8080/Hello/api/update";
TextView currentPathTextView;// 显示当前路径的文本视图
ListView fileListView;// 显示文件列表的视图
GridView bottomMenuGridView;// 底部菜单视图
File currentDirectory;// 当前文件目录
File cutFile;// 将要剪切的文件
File copyFile;// 将要复制的文件
File[] files;// 当前文件列表
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 调用检查更新的方法,弹框提示
// UpdateChecker.checkForDialog(MainActivity.this,APP_UPDATE_SERVER_URL);
// 调用检查更新的方法,通知栏提示
UpdateChecker.checkForNotification(MainActivity.this,
APP_UPDATE_SERVER_URL);
// 获取视图
currentPathTextView = (TextView) findViewById(R.id.textView1);
fileListView = (ListView) findViewById(R.id.listView1);
bottomMenuGridView = (GridView) findViewById(R.id.gridView1);
// 初始化底部菜单
initBottomMenu();
// 初始化文件列表
initFileList(Environment.getExternalStorageDirectory());
// 给文件列表视图绑定点击事件
fileListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// 如果是点击到下标0
if (arg2 == 0) {
// 返回上层目录
initFileList(currentDirectory.getParentFile());
} else {
// 获取点击的文件
File f = files[arg2 - 1];
// 如果是文件夹
if (f.isDirectory()) {
// 重新初始化文件列表视图
initFileList(f);
} else {// 否则的话 打开文件
// 调用系统方法获取后缀
String extension = MimeTypeMap
.getFileExtensionFromUrl(f.getName());
// 获取MIME类型
String mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(extension);
mimeType = mimeType == null ? "*/*" : mimeType;
// 创建Intent
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
// 设置文件路径和MIME类型 让系统自己决定用什么打开
intent.setDataAndType(Uri.fromFile(f), mimeType);
startActivity(intent);
}
}
}
});
// 设置文件列表视图的长按事件
fileListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
// 获取点击的文件
final File f = files[arg2 - 1];
// 本程序只对文件进行复制等操作,请自行扩展
if (f.isFile()) {
// 如果能读取
if (f.canRead()) {
Builder builder = new Builder(MainActivity.this);
builder.setTitle("请选择操作");
String[] items;
// 如果能写入(修改/删除)
if (f.canWrite()) {
items = new String[] { "复制", "剪切", "删除" };
} else {
items = new String[] { "复制" };
}
// 绑定选项和点击事件
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
switch (arg1) {
case 0:
// 复制
copyFile = f;
cutFile = null;
break;
case 1:
// 剪切
cutFile = f;
copyFile = null;
break;
case 2:
// 删除
f.delete();
initFileList(currentDirectory);// 重新初始化文件列表
break;
}
}
});
builder.show();
} else {
alert("此文件/文件夹不能进行任何操作555~");
}
} else {
alert("暂时只支持对文件进行操作~");
}
return true;
}
});
}
/**
* 初始化文件列表
*
* @param f
* 要打开的目录(文件夹)
*/
void initFileList(File f) {
// 如果f为null则默认为跟目录
if (f == null) {
f = new File("/");
}
// 如果是文件夹
if (f.isDirectory()) {
// 如果能读取
if (f.canRead()) {
// 保存当前路径
currentDirectory = f;
// 显示当前路径到界面
currentPathTextView.setText(" " f.getPath());
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map;
// 在文件列表视图添加返回上层
map = new HashMap<String, Object>();
map.put("text", "返回上层目录");
map.put("img", R.drawable.back);
list.add(map);
// 在文件列表视图添加子文件或目录
files = f.listFiles();
// 排序
Arrays.sort(files);
for (File file : files) {
map = new HashMap<String, Object>();
map.put("text", file.getName());
// 根据是目录或文件来决定列表中的图标 (可根据后缀名来丰富更多图标)
if (file.isDirectory()) {
map.put("img", R.drawable.folder);
} else if (file.isFile()) {
map.put("img", R.drawable.others);
} else {
map.put("img", R.drawable.unknown);
}
list.add(map);
}
// 创建适配器
SimpleAdapter sa = new SimpleAdapter(MainActivity.this, list,
R.layout.list, new String[] { "img", "text" },
new int[] { R.id.imageView1, R.id.textView1 });
// 绑定适配器
fileListView.setAdapter(sa);
} else {
// 不能读取文件夹的提示
alert("没有权限555~");
}
}
}
/**
* 初始化底部菜单
*/
void initBottomMenu() {
String[] mMenuToolStringList = { "手机", "SD卡", "创建", "粘贴", "退出" };
int[] mMenuToolImageList = { R.drawable.menu_phone,
R.drawable.menu_sdcard, R.drawable.menu_create,
R.drawable.menu_palse, R.drawable.menu_exit };
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
// 设置文字和图标
for (int i = 0; i < mMenuToolStringList.length; i ) {
Map<String, Object> line = new HashMap<String, Object>();
line.put("text", mMenuToolStringList[i]);
line.put("img", mMenuToolImageList[i]);
data.add(line);
}
// 设置整个底部菜单的背景
this.bottomMenuGridView
.setBackgroundResource(R.drawable.menu_background);
// 绑定适配器
bottomMenuGridView.setAdapter(new SimpleAdapter(MainActivity.this,
data, R.layout.bottom_menu, new String[] { "text", "img" },
new int[] { R.id.gv_text, R.id.gv_img }));
// 绑定点击事件
bottomMenuGridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
switch (arg2) {
case 0:// 点击了 手机
// 初始化列表为跟目录
initFileList(null);
break;
case 1:// 点击了SD卡
// 初始化为SD卡目录
initFileList(Environment.getExternalStorageDirectory());
break;
case 2:// 点击了创建
// 如果此文件能创建
if (currentDirectory.canWrite()) {
// 创建一个弹窗供用户操作
// 获得新建弹窗的布局
View v = LayoutInflater.from(MainActivity.this)
.inflate(R.layout.createfile, null);
// 获取上面的文本框和单选按钮
final EditText et = (EditText) v.findViewById(R.id.et);
final RadioGroup rg = (RadioGroup) v
.findViewById(R.id.rg);
Builder builder = new Builder(MainActivity.this);
builder.setTitle("新建");
builder.setView(v);
// builder.setCancelable(false);//点击对话框外面 不消失
// 绑定按钮和点击事件
builder.setPositiveButton("取消", null);
builder.setNegativeButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// 获取用户选择的按钮和文本
int checkedRadioButtonId = rg
.getCheckedRadioButtonId();
String newFileName = et.getText().toString()
.trim();
if (newFileName.equals("")) {
alert("你怎么不输入文件/文件夹的名字呢~");
} else {
// 根据当前目录和输入的名称 创建新文件
File newFile = new File(currentDirectory,
newFileName);
switch (checkedRadioButtonId) {
case R.id.r0:// 选择了创文件
try {
if (newFile.createNewFile()) {
alert("创建文件成功hhh~");
initFileList(currentDirectory);
} else {
alert("文件已存在555~");
}
} catch (IOException e) {
alert("创建文件失败555~");
}
break;
case R.id.r1:// 选择了创文件夹
if (newFile.mkdirs()) {
alert("创建文件夹成功hhh~");
initFileList(currentDirectory);
} else {
alert("创建文件夹失败555~");
}
break;
}
}
}
});
builder.show();
} else {
alert("没有权限创建555~");
}
break;
case 3:// 点击了粘贴
// 目标文件(位置)
File targetFile = null;
if (!currentDirectory.canWrite()) {
alert("此文件夹不可粘贴~");
} else if (copyFile != null) {// 复制
// 去重复处理
targetFile = distinctOfFile(copyFile);
nioBufferCopy(copyFile, targetFile);
} else if (cutFile != null) {// 粘贴
targetFile = distinctOfFile(cutFile);
nioBufferCopy(cutFile, targetFile);
cutFile.delete();
} else {
alert("然而并没有什么东西可以用来粘贴~");
}
break;
case 4:// 退出
exitAlert();
break;
}
}
});
}
/**
* 去重复 当粘贴的目标文件存在时进行改名处理
*
* @param source
* 源文件
* @return 处理后的 目标文件
*/
File distinctOfFile(File source) {
File targetFile = new File(currentDirectory, source.getName());
int i = 0;
while (targetFile.exists())// 如果目标文件已经存在的话(同名)
{
i ;
targetFile = new File(currentDirectory, "(" i ")"
source.getName());
}
return targetFile;
}
// 创建全局文件流和管道 方便在线程中使用
FileChannel in;
FileChannel out;
FileInputStream inStream;
FileOutputStream outStream;
ByteBuffer buffer;
/**
* 复制文件
*
* @param source
* 源文件
* @param target
* 目标文件
*/
void nioBufferCopy(File source, File target) {
try {
// 初始化
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
// 缓冲区为4K
buffer = ByteBuffer.allocate(4096);
// 实例化一个进度条对话框
final ProgressDialog progressDialog = new ProgressDialog(
MainActivity.this);
// 设置标题
progressDialog.setTitle("粘贴中...");
// 设置进度条的风格
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// 设置点返回或按区域外不取消进度条
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
// 创建线程
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
// 设置进度条的最大值
progressDialog.setMax((int) in.size());
// 循环读取写入
while (in.read(buffer) != -1) {
buffer.flip();
out.write(buffer);
buffer.clear();
// 设置进度
progressDialog.setProgress((int) out.size());
}
// 取消进度条
progressDialog.cancel();
alert("粘贴完成");
// 在UI线程中初始化文件列表 (不能在非UI线程操作界面)
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
initFileList(currentDirectory);
}
});
} catch (IOException e) {
alert("粘贴出错");
e.printStackTrace();
} finally {
// 关闭流和管道
try {
inStream.close();
in.close();
outStream.close();
out.close();
} catch (IOException e) {
alert("关闭流出错");
e.printStackTrace();
}
}
}
});
t.start();
} catch (FileNotFoundException e1) {
alert("粘贴源不见鸟~");
e1.printStackTrace();
}
}
/**
* 创建菜单
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* 菜单项被选中事件
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_aboutMenu:// 关于
Builder bAbout = new Builder(MainActivity.this);
bAbout.setTitle("关于");
StringBuffer sb = new StringBuffer();
try {
PackageInfo pi = getPackageManager().getPackageInfo(
getPackageName(), 0);
sb.append("名称:");
sb.append(pi.applicationInfo.loadLabel(getPackageManager()));
sb.append("\n");
sb.append("版本:");
sb.append(pi.versionName);
sb.append("\n");
} catch (NameNotFoundException e) {
e.printStackTrace();
}
sb.append("作者:HEXT(贺小钿)");
bAbout.setMessage(sb);
bAbout.setNeutralButton("确定", null);
bAbout.show();
break;
case R.id.Menu_update:// 检查更新
// 调用检查更新的方法,弹框提示
UpdateChecker.checkForDialog(MainActivity.this,
APP_UPDATE_SERVER_URL);
break;
default:
super.onOptionsItemSelected(item);
break;
}
return true;
}
/**
* 封装Toast弹窗 方便使用
*
* @param message
* 需要弹窗的内容
*/
void alert(Object message) {
message = message == null ? "null" : message;
final String text = message.toString();
// 因为弹窗提示可能会在非UI线程中用到,所以使用runOnUiThread,如果当前是UI线程就直接弹窗,如果不是就加入到消息列队(列队循环很快,也会立刻弹窗)
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT)
.show();
}
});
}
/**
* 退出弹窗提示
*/
void exitAlert() {
Builder bexit = new Builder(MainActivity.this);
bexit.setTitle("提示");
bexit.setMessage("确定退出吗?");
bexit.setPositiveButton("取消", null);
bexit.setNegativeButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// 结束MainActivity
MainActivity.this.finish();
}
});
bexit.show();
}
// 重写按键事件
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// 如果按下了返回键
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == KeyEvent.ACTION_DOWN) {
File f = currentDirectory.getParentFile();
// 如果不是根目录就返回上层,如果是就提示退出
if (f != null) {
initFileList(f);
} else {
exitAlert();
}
}
return true;
}
}
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论