当前位置: 编程技术>移动开发
本页文章导读:
▪播发网络流文件 播放网络流文件
public class AudioPlayer implements OnErrorListener, OnBufferingUpdateListener, MediaPlayer.OnCompletionListener { private static final String TAG = "AudioPlayer"; private MediaPlayer mPlayer; private String current; private .........
▪ 容易通讯录 简单通讯录
public class Main extends Activity implements OnItemClickListener {
GridView buttomMenuGrid;// 底部菜单布局
String[] buttomMenu_name = { "增加", "删除", "退出" };// 底部菜单项的名字
int[] buttomMenu_images = { R..........
▪ Layout格局 Layout布局
内容:LinearLayout水平布局(可水平或者垂直布局)<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent" android:layout_height=".........
[1]播发网络流文件
来源: 互联网 发布时间: 2014-02-18
播放网络流文件
public class AudioPlayer implements OnErrorListener, OnBufferingUpdateListener,
MediaPlayer.OnCompletionListener {
private static final String TAG = "AudioPlayer";
private MediaPlayer mPlayer;
private String current;
private static final int MIN_BUFF = 100 * 1024;
private int totalKbRead = 0;
private Handler handler = new Handler();
private File DLTempFile;
private File BUFFTempFile;
private final String TEMP_DOWNLOAD_FILE_NAME = "tempMediaData";
private final String TEMP_BUFF_FILE_NAME = "tempBufferData";
private final String FILE_POSTFIX = ".dat";
private final int PER_READ = 1024;
private boolean pause;
private boolean stop;
private final int UNKNOWN_LENGTH = -1;
private Handler mHandler = null;
public void setHandler(Handler handler) {
mHandler = handler;
}
public void play(final String path) {
downloadOver = false;
totalKbRead = 0;
try {
Log.v(TAG, "playing: " + path);
if (path.equals(current) && mPlayer != null) {
mPlayer.start();
return;
}
current = path;
mPlayer = null;
new PlayThread(current).start();
} catch (Exception e) {
}
}
private void setListener() {
if (mPlayer != null) {
mPlayer.setOnErrorListener(this);
mPlayer.setOnBufferingUpdateListener(this);
mPlayer.setOnCompletionListener(this);
}
}
/**
* 下载数据,分段下载
* todo:联网方式和分段
* @param mediaUrl
* @param start
* @param end
*/
private void playFromNet(String mediaUrl, int start, int end) {
URLConnection cn = null;
FileOutputStream out = null;
InputStream is = null;
try {
cn = new URL(/blog_article/mediaUrl/index.html).openConnection();
cn.connect();
is = cn.getInputStream();
int mediaLength = cn.getContentLength();
if (is == null) {
return;
}
deleteTempFile(true);
DLTempFile = File.createTempFile(TEMP_DOWNLOAD_FILE_NAME,FILE_POSTFIX);
out = new FileOutputStream(DLTempFile);
byte buf[] = new byte[PER_READ];
int readLength = 0;
while (readLength != -1 && !stop) {
if (pause) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
readLength = is.read(buf);
if (readLength > 0) {
try {
out.write(buf, 0, readLength);
totalKbRead += readLength;
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
dealWithBufferData();
}
if (totalKbRead == mediaLength) {
downloadOver = true;
dealWithLastData();
// 删除临时文件
if (DLTempFile != null && DLTempFile.exists()) {
DLTempFile.delete();
}
}
} catch (MalformedURLException e) {
Log.e(TAG, e.toString());
} catch (IOException e) {
Log.e(TAG, e.toString());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private boolean downloadOver = false;
private boolean wasPlayed = false;
private void dealWithBufferData() {
if (mPlayer == null || !wasPlayed) {
if (totalKbRead >= MIN_BUFF) {
try {
startMediaPlayer();
} catch (Exception e) {
}
}
} else if (mPlayer.getDuration() - mPlayer.getCurrentPosition() <= 1000) {
deleteTempFile(true);
transferBufferToMediaPlayer();
}
}
private void startMediaPlayer() {
try {
deleteTempFile(true);
BUFFTempFile = File.createTempFile(TEMP_BUFF_FILE_NAME,FILE_POSTFIX);
FileSystemUtil.copyFile(DLTempFile, BUFFTempFile);
mPlayer = new MediaPlayer();
setListener();
mPlayer.setDataSource(BUFFTempFile.getAbsolutePath());
mPlayer.prepare();
mPlayer.start();
wasPlayed = true;
} catch (IOException e) {
}
}
private void transferBufferToMediaPlayer() {
try {
boolean wasPlaying = mPlayer.isPlaying();
int curPosition = mPlayer.getCurrentPosition();
mPlayer.pause();
BUFFTempFile = File.createTempFile(TEMP_BUFF_FILE_NAME,FILE_POSTFIX);
FileSystemUtil.copyFile(DLTempFile, BUFFTempFile);
mPlayer = new MediaPlayer();
mPlayer.setDataSource(BUFFTempFile.getAbsolutePath());
mPlayer.prepare();
mPlayer.seekTo(curPosition);
boolean atEndOfFile = mPlayer.getDuration()- mPlayer.getCurrentPosition() <= 1000;
if (wasPlaying || atEndOfFile) {
mPlayer.start();
}
} catch (Exception e) {
}
}
private void dealWithLastData() {
Runnable updater = new Runnable() {
public void run() {
transferBufferToMediaPlayer();
}
};
handler.post(updater);
}
public void onCompletion(MediaPlayer mp) {
if (mHandler != null) {
mHandler.sendEmptyMessage(Preferences.MEDIA_ENDED);
}
}
public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
if (mHandler != null) {
mHandler.sendEmptyMessage(Preferences.MEDIA_ERROR);
}
return true;
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate called --->
percent:" + percent);
if (mHandler != null) {
mHandler.sendEmptyMessage(Preferences.EMDIA_BUFF_CHANGE);
}
}
private class PlayThread extends Thread {
private String url;
PlayThread(String url) {
this.url = url;
}
public void run() {
if (!URLUtil.isNetworkUrl(/blog_article/url/index.html)) {
mPlayer = new MediaPlayer();
setListener();
try {
// if (url.startsWith("content://")) {
// mPlayer.setDataSource(MediaPlayService.this, Uri
// .parse(url));
// } else {
mPlayer.setDataSource(url);
// }
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
setVolume(0f);
mPlayer.prepare();
mPlayer.start();
} catch (IllegalArgumentException e) {
Log.e(TAG, e.toString());
} catch (IllegalStateException e) {
Log.e(TAG, e.toString());
} catch (IOException e) {
Log.e(TAG, e.toString());
}
} else {
playFromNet(url, 0, UNKNOWN_LENGTH);
}
}
}
}
public class AudioPlayer implements OnErrorListener, OnBufferingUpdateListener,
MediaPlayer.OnCompletionListener {
private static final String TAG = "AudioPlayer";
private MediaPlayer mPlayer;
private String current;
private static final int MIN_BUFF = 100 * 1024;
private int totalKbRead = 0;
private Handler handler = new Handler();
private File DLTempFile;
private File BUFFTempFile;
private final String TEMP_DOWNLOAD_FILE_NAME = "tempMediaData";
private final String TEMP_BUFF_FILE_NAME = "tempBufferData";
private final String FILE_POSTFIX = ".dat";
private final int PER_READ = 1024;
private boolean pause;
private boolean stop;
private final int UNKNOWN_LENGTH = -1;
private Handler mHandler = null;
public void setHandler(Handler handler) {
mHandler = handler;
}
public void play(final String path) {
downloadOver = false;
totalKbRead = 0;
try {
Log.v(TAG, "playing: " + path);
if (path.equals(current) && mPlayer != null) {
mPlayer.start();
return;
}
current = path;
mPlayer = null;
new PlayThread(current).start();
} catch (Exception e) {
}
}
private void setListener() {
if (mPlayer != null) {
mPlayer.setOnErrorListener(this);
mPlayer.setOnBufferingUpdateListener(this);
mPlayer.setOnCompletionListener(this);
}
}
/**
* 下载数据,分段下载
* todo:联网方式和分段
* @param mediaUrl
* @param start
* @param end
*/
private void playFromNet(String mediaUrl, int start, int end) {
URLConnection cn = null;
FileOutputStream out = null;
InputStream is = null;
try {
cn = new URL(/blog_article/mediaUrl/index.html).openConnection();
cn.connect();
is = cn.getInputStream();
int mediaLength = cn.getContentLength();
if (is == null) {
return;
}
deleteTempFile(true);
DLTempFile = File.createTempFile(TEMP_DOWNLOAD_FILE_NAME,FILE_POSTFIX);
out = new FileOutputStream(DLTempFile);
byte buf[] = new byte[PER_READ];
int readLength = 0;
while (readLength != -1 && !stop) {
if (pause) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
readLength = is.read(buf);
if (readLength > 0) {
try {
out.write(buf, 0, readLength);
totalKbRead += readLength;
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
dealWithBufferData();
}
if (totalKbRead == mediaLength) {
downloadOver = true;
dealWithLastData();
// 删除临时文件
if (DLTempFile != null && DLTempFile.exists()) {
DLTempFile.delete();
}
}
} catch (MalformedURLException e) {
Log.e(TAG, e.toString());
} catch (IOException e) {
Log.e(TAG, e.toString());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private boolean downloadOver = false;
private boolean wasPlayed = false;
private void dealWithBufferData() {
if (mPlayer == null || !wasPlayed) {
if (totalKbRead >= MIN_BUFF) {
try {
startMediaPlayer();
} catch (Exception e) {
}
}
} else if (mPlayer.getDuration() - mPlayer.getCurrentPosition() <= 1000) {
deleteTempFile(true);
transferBufferToMediaPlayer();
}
}
private void startMediaPlayer() {
try {
deleteTempFile(true);
BUFFTempFile = File.createTempFile(TEMP_BUFF_FILE_NAME,FILE_POSTFIX);
FileSystemUtil.copyFile(DLTempFile, BUFFTempFile);
mPlayer = new MediaPlayer();
setListener();
mPlayer.setDataSource(BUFFTempFile.getAbsolutePath());
mPlayer.prepare();
mPlayer.start();
wasPlayed = true;
} catch (IOException e) {
}
}
private void transferBufferToMediaPlayer() {
try {
boolean wasPlaying = mPlayer.isPlaying();
int curPosition = mPlayer.getCurrentPosition();
mPlayer.pause();
BUFFTempFile = File.createTempFile(TEMP_BUFF_FILE_NAME,FILE_POSTFIX);
FileSystemUtil.copyFile(DLTempFile, BUFFTempFile);
mPlayer = new MediaPlayer();
mPlayer.setDataSource(BUFFTempFile.getAbsolutePath());
mPlayer.prepare();
mPlayer.seekTo(curPosition);
boolean atEndOfFile = mPlayer.getDuration()- mPlayer.getCurrentPosition() <= 1000;
if (wasPlaying || atEndOfFile) {
mPlayer.start();
}
} catch (Exception e) {
}
}
private void dealWithLastData() {
Runnable updater = new Runnable() {
public void run() {
transferBufferToMediaPlayer();
}
};
handler.post(updater);
}
public void onCompletion(MediaPlayer mp) {
if (mHandler != null) {
mHandler.sendEmptyMessage(Preferences.MEDIA_ENDED);
}
}
public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
if (mHandler != null) {
mHandler.sendEmptyMessage(Preferences.MEDIA_ERROR);
}
return true;
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate called --->
percent:" + percent);
if (mHandler != null) {
mHandler.sendEmptyMessage(Preferences.EMDIA_BUFF_CHANGE);
}
}
private class PlayThread extends Thread {
private String url;
PlayThread(String url) {
this.url = url;
}
public void run() {
if (!URLUtil.isNetworkUrl(/blog_article/url/index.html)) {
mPlayer = new MediaPlayer();
setListener();
try {
// if (url.startsWith("content://")) {
// mPlayer.setDataSource(MediaPlayService.this, Uri
// .parse(url));
// } else {
mPlayer.setDataSource(url);
// }
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
setVolume(0f);
mPlayer.prepare();
mPlayer.start();
} catch (IllegalArgumentException e) {
Log.e(TAG, e.toString());
} catch (IllegalStateException e) {
Log.e(TAG, e.toString());
} catch (IOException e) {
Log.e(TAG, e.toString());
}
} else {
playFromNet(url, 0, UNKNOWN_LENGTH);
}
}
}
}
[2] 容易通讯录
来源: 互联网 发布时间: 2014-02-18
简单通讯录
public class Main extends Activity implements OnItemClickListener { GridView buttomMenuGrid;// 底部菜单布局 String[] buttomMenu_name = { "增加", "删除", "退出" };// 底部菜单项的名字 int[] buttomMenu_images = { R.drawable.menu_add, R.drawable.menu_delete, R.drawable.menu_exit };// 底部菜单项的图片 ArrayList listdate; ListView listView;// 显示所有数据的ListView SimpleAdapter adapter; ArrayList<Integer> deleteId;// 删除项的ID public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); // 单击listview中的某一项的事件 listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { HashMap item = (HashMap) arg0.getItemAtPosition(arg2); Integer _id = Integer.parseInt(String.valueOf(item.get("_id"))); Intent intent = new Intent(Main.this, Detail.class); Contact contact = new Contact(); contact._id = Integer.parseInt(String.valueOf(item.get("_id"))); contact.name = String.valueOf(item.get("name")); contact.phone = String.valueOf(item.get("phone")); /* 注意:必须对实体contact进行序列化,即实体类实现Serializable接口,否则无法传递contact到下一个页面 */ intent.putExtra("contact", contact); System.out.println("arg2:" + arg2); startActivityForResult(intent, arg2); } }); /** * 长按listview的监听事件 */ listView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub if (deleteId == null) { deleteId = new ArrayList<Integer>(); } HashMap item = (HashMap) arg0.getItemAtPosition(arg2); Integer _id = Integer.parseInt(String.valueOf(item.get("_id"))); RelativeLayout relativeLayout = (RelativeLayout) arg1; ImageView markedView = (ImageView) relativeLayout.getChildAt(2);// // 获取第二个imageView if (markedView.getVisibility() == View.VISIBLE) {// 如果已标记就删除 markedView.setVisibility(View.GONE); deleteId.remove(_id); } else {// 如果未标记,就标记上,并添加到deleteID中 markedView.setVisibility(View.VISIBLE); deleteId.add(_id); } return true; } }); } private void init() { DBHelper dbHelper = new DBHelper(this); dbHelper.openDB();// 打开数据库 listView = (ListView) findViewById(R.id.contact_list); adapter = getAdapter(); listView.setAdapter(adapter); listView.setCacheColorHint(Color.TRANSPARENT);// 设置listView的背景透明 loadBottomMenu(); buttomMenuGrid.setVisibility(View.VISIBLE); } /** * 获取底部菜单的适配器 * * @param buttomMenu_name * @param buttomMenu_images * @return */ public SimpleAdapter getButtomMenuAdapter(String[] buttomMenu_name, int[] buttomMenu_images) { ArrayList<HashMap<String, Object>> dataArrayList = new ArrayList<HashMap<String, Object>>(); for (int i = 0; i < buttomMenu_images.length; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("images", buttomMenu_images[i]); map.put("name", buttomMenu_name[i]); dataArrayList.add(map); } SimpleAdapter simpleAdapter = new SimpleAdapter(this, dataArrayList, R.layout.buttom_menu, new String[] { "images", "name" }, new int[] { R.id.buttom_menu_image, R.id.buttom_menu_text }); return simpleAdapter; } // 重写了onActivityResult方法:处理页面返回后的数据 相当于重新刷新ListView中的数据 protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == 3) {// resultCode == 3代表添加一个用户返回 adapter = getAdapter();// 重新获取适配器 } listView.setAdapter(adapter);// 重新设置ListView的适配器 } // 获取适配器 public SimpleAdapter getAdapter() { DBHelper dbHelper = new DBHelper(this); listdate = dbHelper.getAll(); adapter = new SimpleAdapter(this, listdate, R.layout.list_item, new String[] { "name", "phone" }, new int[] { R.id.name_item, R.id.phone_item }); return adapter; } // 装载底部菜单 private void loadBottomMenu() { if (buttomMenuGrid == null) { buttomMenuGrid = (GridView) findViewById(R.id.buttom_menu); buttomMenuGrid.setNumColumns(3); buttomMenuGrid.setGravity(Gravity.CENTER); buttomMenuGrid.setVerticalSpacing(10); buttomMenuGrid.setHorizontalSpacing(10); buttomMenuGrid.setAdapter(getButtomMenuAdapter(buttomMenu_name, buttomMenu_images));// 设置底部菜单的Adapter buttomMenuGrid.setOnItemClickListener(this); } } // 菜单单击事件 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { switch (arg2) { case 0:// 添加 if (deleteId == null || deleteId.size() == 0) { Intent intent = new Intent(Main.this, Add.class); startActivityForResult(intent, 3); } else { // 如果deleteId不空,清空,防止数据的残留 deleteId.clear(); } break; case 1:// 删除 if (deleteId == null || deleteId.size() == 0) { Toast.makeText(Main.this, "未标记任何记录\n长按一条记录即可标记", Toast.LENGTH_LONG).show(); } else { new AlertDialog.Builder(Main.this).setTitle("确定要删除吗?") .setPositiveButton("确定", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { DBHelper dbHelper = new DBHelper(Main.this); dbHelper.deleteMarked(deleteId); adapter = getAdapter(); listView.setAdapter(adapter); deleteId.clear(); } }).setNegativeButton("取消", null).create().show(); } break; case 2:// 退出 finish(); break; default: break; } } }
[3] Layout格局
来源: 互联网 发布时间: 2014-02-18
Layout布局
内容:
LinearLayout水平布局(可水平或者垂直布局)
内容:
LinearLayout水平布局(可水平或者垂直布局)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" >TableLayout表格布局(布置表格布局)
<TableLayout android:id="@+id/tableLayout1" android:layout_height="wrap_content" android:layout_width="fill_parent">RelativeLayout相对布局
最新技术文章: