編輯:關於Android編程
一、數據存儲選項:Data Storage ——Storage Options【重點】
button_main_savedata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prefs = getSharedPreferences("myaccount", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("age", 38);
editor.putString("username", "wangxiangjun");
editor.putString("pwd", "123456");
editor.putString("username", "xiangjun");
editor.putString("age", "I'm 40 years old!");
editor.commit();
}
});
button_main_readdata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prefs = getSharedPreferences("myaccount", Context.MODE_PRIVATE);
String name = prefs.getString("username", "wxj");
String pwd = prefs.getString("pwd", "000");
int age = prefs.getInt("age", 20);
System.out.println("====>" + name + ":" + pwd + ":" + age);
}
});
(四)、保存之後的SharedPreferences數據文件:
SharedPreferences數據總是以xml格式保存在:/data/data/包名/shared_prefs目錄下;
例如:
手機中常有這樣的設置頁面,如果做這樣的頁面呢?是不是需要寫一個復雜的布局文件,再寫一堆事件監聽來完成呢?
2、PreferenceActivity的簡單用法:
1)、步驟:
3)、核心代碼:
//在SettingActivity中。不再需要setContentView(R.layout.activity_main)方法來加載布局了。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
addPreferencesFromResource(R.xml.setting);
//備注:This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.這個方法在11版本以上就已經不推薦使用了。
}
(六)、借助SharedPreferences實現黑名單管理:
1、示例代碼:
publicclass MainActivity extends Activity {
private ListView listView_main_blockList;
private EditText editText_main_number;
private TextView textView_main_emptyinfo;
private SharedPreferences prefs = null;
private Editor editor = null;
private ArrayAdapter adapter = null;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText_main_number = (EditText) findViewById(R.id.editText_main_number);
listView_main_blockList = (ListView) findViewById(R.id.listView_main_blocklist);
textView_main_emptyinfo = (TextView) findViewById(R.id.text_main_emptyinfo);
prefs = getSharedPreferences("blocklist", Context.MODE_PRIVATE);
editor = prefs.edit();
List list = getBlocklist();
adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
// 注意setEmptyView()的用法。當適配器為空的時候,設置ListView中的展示內容。
listView_main_blockList.setEmptyView(textView_main_emptyinfo);
listView_main_blockList.setAdapter(adapter);
}
publicvoid clickButton(View view) {
switch (view.getId()) {
case R.id.button_main_add:
String mpnumber = editText_main_number.getText().toString();
editor.putString(mpnumber, mpnumber);
editor.commit();
fillListView();
break;
case R.id.button_main_clear:
editor.clear();
editor.commit();
fillListView();
break;
default:
break;
}
}
/*
* 獲取SharedPreferences中的全部數據,放到List集合中。形成適配器的數據源
*/
private List getBlocklist() {
List list = new ArrayList();
try {
Map map = prefs.getAll();
// 增強for循環,實現對Map集合的遍歷
for (Map.Entry entry : map.entrySet()) {
list.add(entry.getKey());
}
return list;
} catch (Exception e) {
returnnull;
}
}
/*
* 填充ListView控件,實現刷新顯示數據的效果
*/
privatevoid fillListView() {
adapter.clear();
adapter.addAll(getBlocklist());
}
@Override
publicboolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
returntrue;
}
}
三、內部存儲:
(一)、Context類提供的基本文件和目錄處理方法
1、getCacheDir()
獲取內部存儲緩存目錄 /data/data/包名/cache。備注:應及時清理該目錄,並節約使用空間
2、getFilesDir()
獲取內部存儲文件目錄 /data/data/包名/files
跟SharedPreferences目錄的區別:/data/data/包名/shared_prefs
3、String[] fileList()
獲取內部存儲/data/data/包名/files 目錄下的文件列表
4、openFileInput(String name)
打開內部存儲的files目錄下的文件
5、openFileOutput(String name , int mode)
打開內存存儲空間上文件進行寫入,如果不存在則創建該文件
四、External Storage之SDCard操作:
(一)、引入:Android中提供了特有的兩個方法來進行IO操作(openFileInput()和openFileOutput() ),但是畢竟手機內置存儲空間很有限,為了更好地存儲應用程序的大文件數據,需要讀寫SD卡上的文件。SD卡大大擴充了手機的存儲能力。
(二)、讀寫SD卡的步驟:
1、先判斷手機是否有sd卡;
調用Environment的getExternalStorageState()方法判斷手機是否插上sdcard。
2、獲取sdcard的路徑;
調用Environment的getExternalStorageDirectory()方法來獲取外部存儲器的目錄。
3、此外還可以獲取SDCard可用磁盤空間的大小(借助StatFs類來實現);
4、清單文件中設置讀寫sdcard的權限;
package com.steven.sdcardhelper;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
public class SDCardHelper {
// 判斷SD卡是否被掛載
public static boolean isSDCardMounted() {
// return Environment.getExternalStorageState().equals("mounted");
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
// 獲取SD卡的根目錄
public static String getSDCardBaseDir() {
if (isSDCardMounted()) {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
return null;
}
// 獲取SD卡的完整空間大小,返回MB
public static long getSDCardSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardBaseDir());
int count = fs.getBlockCount();
int size = fs.getBlockSize();
return count * size / 1024 / 1024;
}
return 0;
}
// 獲取SD卡的剩余空間大小
public static long getSDCardFreeSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardBaseDir());
int count = fs.getFreeBlocks();
int size = fs.getBlockSize();
return count * size / 1024 / 1024;
}
return 0;
}
// 獲取SD卡的可用空間大小
public static long getSDCardAvailableSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardBaseDir());
int count = fs.getAvailableBlocks();
int size = fs.getBlockSize();
return count * size / 1024 / 1024;
}
return 0;
}
// 往SD卡的公有目錄下保存文件
public static boolean saveFileToSDCardPublicDir(byte[] data, String type,
String fileName) {
BufferedOutputStream bos = null;
if (isSDCardMounted()) {
File file = Environment.getExternalStoragePublicDirectory(type);
try {
bos = new BufferedOutputStream(new FileOutputStream(new File(
file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
// 往SD卡的自定義目錄下保存文件
public static boolean saveFileToSDCardCustomDir(byte[] data, String dir,
String fileName) {
BufferedOutputStream bos = null;
if (isSDCardMounted()) {
File file = new File(getSDCardBaseDir() + File.separator + dir);
if (!file.exists()) {
file.mkdirs();// 遞歸創建自定義目錄
}
try {
bos = new BufferedOutputStream(new FileOutputStream(new File(
file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
// 往SD卡的私有Files目錄下保存文件
public static boolean saveFileToSDCardPrivateFilesDir(byte[] data,
String type, String fileName, Context context) {
BufferedOutputStream bos = null;
if (isSDCardMounted()) {
File file = context.getExternalFilesDir(type);
try {
bos = new BufferedOutputStream(new FileOutputStream(new File(
file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
// 往SD卡的私有Cache目錄下保存文件
public static boolean saveFileToSDCardPrivateCacheDir(byte[] data,
String fileName, Context context) {
BufferedOutputStream bos = null;
if (isSDCardMounted()) {
File file = context.getExternalCacheDir();
try {
bos = new BufferedOutputStream(new FileOutputStream(new File(
file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
// 從SD卡獲取文件
public static byte[] loadFileFromSDCard(String fileDir) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
bis = new BufferedInputStream(
new FileInputStream(new File(fileDir)));
byte[] buffer = new byte[8 * 1024];
int c = 0;
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
baos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
// 獲取SD卡公有目錄的路徑
public static String getSDCardPublicDir(String type) {
return Environment.getExternalStoragePublicDirectory(type).toString();
}
// 獲取SD卡私有Cache目錄的路徑
public static String getSDCardPrivateCacheDir(Context context) {
return context.getExternalCacheDir().getAbsolutePath();
}
// 獲取SD卡私有Files目錄的路徑
public static String getSDCardPrivateFilesDir(Context context, String type) {
return context.getExternalFilesDir(type).getAbsolutePath();
}
}
(四)、案例:
1、功能:點擊按鈕,實現從網絡上訪問圖片,將圖片保存進SDCard中。點擊另外一按鈕,可以獲取到剛才保存進SDCard中的圖片,將其加載的頁面中的ImageView控件中。2、示例代碼:、示例代碼:
publicclass MainActivity extends Activity {
private ImageView imageView_main_img;
private String urlString = "http://t2.baidu.com/it/u=2,1891512358&fm=19&gp=0.jpg";
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView_main_img = (ImageView) findViewById(R.id.imageView_main_img);
}
publicvoid clickButton(View view) {
switch (view.getId()) {
case R.id.button_main_save:
new MyTask(this).execute(urlString);
break;
case R.id.button_main_show:
String filepath = SDCardHelper.getSDCardPath() + File.separator
+ "mydir" + File.separator + "firstimg.jpg";
byte[] data = SDCardHelper.loadFileFromSDCard(filepath);
if (data != null) {
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView_main_img.setImageBitmap(bm);
} else {
Toast.makeText(this, "沒有該圖片!", Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
class MyTask extends AsyncTask {
private Context context;
private ProgressDialog pDialog;
public MyTask(Context context) {
this.context = context;
pDialog = new ProgressDialog(context);
pDialog.setIcon(R.drawable.ic_launcher);
pDialog.setMessage("圖片加載中...");
}
@Override
protectedvoid onPreExecute() {
super.onPreExecute();
pDialog.show();
}
@Override
protectedbyte[] doInBackground(String... params) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
URL url = new URL(params[0]);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
httpConn.setDoInput(true);
httpConn.connect();
if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
byte[] buffer = newbyte[1024 * 8];
int c = 0;
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
return baos.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
}
returnnull;
}
@Override
protectedvoid onPostExecute(byte[] result) {
super.onPostExecute(result);
if (result == null) {
Toast.makeText(context, "圖片加載失敗!", Toast.LENGTH_LONG).show();
} else {
// 將字節數組轉成Bitmap,然後將bitmap加載的imageview控件中
// Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0,
// result.length);
// imageView_main_img.setImageBitmap(bitmap);
if (SDCardHelper.saveFileToSDCard(result, "mydir",
"firstimg.jpg")) {
Toast.makeText(context, "圖片保存OK!", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(context, "圖片保存失敗!", Toast.LENGTH_LONG)
.show();
}
}
pDialog.dismiss();
}
}
@Override
publicboolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
returntrue;
}
}
(五)、案例:SDCard文件浏覽器
1、效果如圖:
2、原理:利用File對象的listFile()方法獲得File[]數組。將數組產生的信息填充在listview中。
核心代碼中的重要方法:
publicclass MainActivity extends Activity {
private TextView textView_main_currentpath;
private ListView listView_main_fileList;
private File currentFile = null;
private File[] arrCurrentFiles = null;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView_main_currentpath = (TextView) findViewById(R.id.text_main_currentpath);
listView_main_fileList = (ListView) findViewById(R.id.listView_main_filelist);
if (SDCardHelper.isSDCardMounted()) {
currentFile = new File(SDCardHelper.getSDCardPath());
fillListView(currentFile);
} else {
Toast.makeText(MainActivity.this, "SDCARD不存在!", Toast.LENGTH_LONG)
.show();
}
listView_main_fileList
.setOnItemClickListener(new OnItemClickListener() {
@Override
publicvoid onItemClick(AdapterView parent, View view,
int position, long id) {
if (arrCurrentFiles[position].isDirectory()) {
File[] arrSubFiles = arrCurrentFiles[position]
.listFiles();
if (arrSubFiles.length == 0) {
Toast.makeText(MainActivity.this, "您點擊的是空目錄!",
2000).show();
} else {
fillListView(arrCurrentFiles[position]);
}
} else {
Toast.makeText(MainActivity.this, "您點擊的不是目錄!",
Toast.LENGTH_LONG).show();
}
}
});
}
publicvoid clickButton(View view) {
switch (view.getId()) {
case R.id.imageView_main_back:
if (!currentFile.getAbsolutePath().equals(
SDCardHelper.getSDCardPath())) {
fillListView(currentFile.getParentFile());
}
break;
default:
break;
}
}
publicvoid fillListView(File file) {
currentFile = file;
arrCurrentFiles = currentFile.listFiles();
List
(六)、案例:SDCard圖片浏覽器
詳解Android中ListView實現圖文並列並且自定義分割線(完善仿微信APP)
昨天的(今天凌晨)的博文《Android中Fragment和ViewPager那點事兒》中,我們通過使用Fragment和ViewPager模仿實現了微信的布局框架。今天
android ViewPager實現 跑馬燈切換圖片+多種切換動畫
最近在弄個項目,要求有跑馬燈效果的圖片展示。網上搜了一堆,都沒有完美實現的算了還是自己寫吧! 實現原理利用 ViewPager 控件,這個控件本身就支持滑動翻頁很好很強大
android 音樂播放器總結
學習從模仿開始一個星期完成的音樂播放器基本功能,具有下一首,上一首,暫停和隨機、順序和單曲等播放,以及保存上一次播放的狀態,缺少了歌詞顯示功能。使用了andbase框架的
(Android 基礎(十三)) shape
介紹 簡單來說,shape就是用來在xml文件中定義形狀,代碼解析之後就可以當做Drawable一樣使用官方說明關於shape定義的drawable文件位置:res/dr