1. 程式人生 > >4.android學習日誌

4.android學習日誌

這是一個音樂播放器到了server handler 廣播等;

package com.jorkyin.mymusic;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import
android.view.View; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.util.Timer; import java.util.TimerTask; /** * Created by YinJian on 2016/3/24. */ public class MusicPlayActivty extends Activity implements View
.OnClickListener {
private boolean mPlayTab = true; private ImageView mMusicNextImageView, mMusicPlayImageView, mMusicPrevImageView; private TextView mMusicNameTextView, mMusicTotalHoursTextView, mMusicTimeingTextView; private SeekBar mMusictimeingSeekBar; public static final String CTL_ACTION = "com.jorkyin.mymusic.CTL_ACTION"
; public static final String UPFATE_ACTION = "com.jorkyin.mymusic.UPFATE_ACTION"; private int status = 0x11; ActivityReceiver activityReceiver; String[] titleStrs = new String[]{"可惜沒有如果", "誣賴", "隱形的翅膀"}; private Intent mIntent; private static boolean isExit = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_music_play); initActivity(); //建立ActivityReceiver activityReceiver = new ActivityReceiver(); //指定IntentFilter監聽的Activity IntentFilter filter = new IntentFilter(); filter.addAction(UPFATE_ACTION); //註冊BroadcastReceiver registerReceiver(activityReceiver, filter); mIntent = new Intent(MusicPlayActivty.this, MusicService.class); //啟動後臺Service startService(mIntent); } private void initActivity() { mMusicNameTextView = (TextView) findViewById(R.id.music_name_id_tv); mMusicTimeingTextView = (TextView) findViewById(R.id.music_timeing_tv); mMusicTotalHoursTextView = (TextView) findViewById(R.id.music_total_hours_tv); mMusictimeingSeekBar = (SeekBar) findViewById(R.id.music_timeing_sb); mMusicPrevImageView = (ImageView) findViewById(R.id.music_prev_id_iv); mMusicPlayImageView = (ImageView) findViewById(R.id.music_play_id_iv); mMusicNextImageView = (ImageView) findViewById(R.id.music_next_id_iv); mMusicPrevImageView.setOnClickListener(this); mMusicPlayImageView.setOnClickListener(this); mMusicNextImageView.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = new Intent(CTL_ACTION); switch (v.getId()) { case R.id.music_prev_id_iv: intent.putExtra("control", 3); break; case R.id.music_play_id_iv: if (mPlayTab) { intent.putExtra("control", 1); } else { intent.putExtra("control", 2); } break; case R.id.music_next_id_iv: intent.putExtra("control", 4); break; } sendBroadcast(intent); } public class ActivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int update = intent.getIntExtra("update", -1); int current = intent.getIntExtra("current", -1); int seekbar = intent.getIntExtra("seekbar", -1); int duration = intent.getIntExtra("duration", -1); if (current >= 0) { mMusicNameTextView.setText(titleStrs[current]); } switch (update) { case 0x11: mMusicPlayImageView.setImageResource(R.mipmap.control_play); status = 0x11; break; case 0x12: mMusicPlayImageView.setImageResource(R.mipmap.control_pause); status = 0x12; break; case 0x13: mMusicPlayImageView.setImageResource(R.mipmap.control_play); status = 0x13; break; } if (duration >=0){ mMusicTotalHoursTextView.setText(formatDuring(duration)); } if (seekbar>=0){ mMusictimeingSeekBar.setProgress(seekbar*mMusictimeingSeekBar.getMax()/duration); mMusicTimeingTextView.setText(formatDuring(seekbar)); } } } private void exit() { if (!isExit) { isExit = true; Toast.makeText(this, "在按一次退出程式", Toast.LENGTH_SHORT).show(); new Timer().schedule(new TimerTask() { @Override public void run() { isExit = false; } }, 2000); } else { stopService(mIntent); finish(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { exit(); } return false; } private String formatDuring(long mss){ String time=""; long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60); if (minutes<10){ time=time+ "0"+minutes+":"; }else{ time=time+minutes+":"; } long seconds = (mss % (1000 * 60)) / 1000; if (seconds<10){ time=time+ "0"+seconds; }else{ time=time+seconds; } return time; } }
package com.jorkyin.mymusic;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;

/**
 * Created by YinJian on 2016/3/24.
 */
public class MusicService extends Service {
    private static final String TAG = MusicService.class.getSimpleName();
    private SetviceReceiver setviceReceiver;
    private MediaPlayer mMediaPlayer;// 媒體播放器物件
    private int current = 0;//記錄當前正在播放的音樂
    private int status = 0x11;//0x11:沒有播放  0x12:正在播放 0x13:暫停
    String[] musics = new String[]{"kxmyrg.mp3", "wl.mp3", "yxdcp.mp3"};
    Handler mHandler=new Handler();
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate");
        super.onCreate();
        //建立BroadcastReceiver物件
        setviceReceiver = new SetviceReceiver();
        //建立IntentFilter物件
        IntentFilter filter = new IntentFilter();
        filter.addAction(MusicPlayActivty.CTL_ACTION);
        registerReceiver(setviceReceiver, filter);

        //在這裡我們需要例項化MediaPlayer物件
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                current++;
                if (current >= 3) {
                    current = 0;
                }
                  prepareAndPlay(musics[current]);
            }
        });
        //傳送廣播通知Activity更改文字框
        Intent sendIntent = new Intent(MusicPlayActivty.UPFATE_ACTION);
        sendIntent.putExtra("current", current);
        //傳送廣播,蔣被Activity元件中的BroadcastReceiver接收到
        sendBroadcast(sendIntent);

    }

    public class SetviceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int control = intent.getIntExtra("control", -1);
            switch (control) {
                case 1:
                    if (status == 0x11) {
                        prepareAndPlay(musics[current]);
                        status = 0x12;
                    } else if (status == 0x12) {
                        mMediaPlayer.pause();
                        status = 0x13;
                    } else if (status == 0x13) {
                        mMediaPlayer.start();
                        status = 0x12;
                    }
                    break;
                case 2:
                    if (status == 0x12 || status == 0x13) {
                        mMediaPlayer.stop();
                        status = 0x11;
                    }
                    break;
                case 3:
                    current--;
                        if (current<0){
                            current=2;
                        }
                    prepareAndPlay(musics[current]);
                    status = 0x12;
                    break;
                case 4:
                    current++;
                    if (current>2){
                        current=0;
                    }
                    prepareAndPlay(musics[current]);
                    status = 0x12;
                    break;
            }
            //傳送廣播通知Activity更改文字框
            Intent sendIntent = new Intent(MusicPlayActivty.UPFATE_ACTION);
            sendIntent.putExtra("update", status);
            sendIntent.putExtra("current", current);
            //傳送廣播,蔣被Activity元件中的BroadcastReceiver接收到
            sendBroadcast(sendIntent);
        }
    }

    @Override
    public boolean stopService(Intent name) {
        mMediaPlayer.stop();
        return super.stopService(name);
    }

    private void prepareAndPlay(String music) {
        try {
            AssetFileDescriptor afd = getAssets().openFd(music);
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            //準備聲音
            mMediaPlayer.prepare();
            //播放
            mMediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //傳送廣播通知Activity更改文字框
        Intent sendIntent = new Intent(MusicPlayActivty.UPFATE_ACTION);

        sendIntent.putExtra("duration",mMediaPlayer.getDuration()/(60*1000));
        //傳送廣播,蔣被Activity元件中的BroadcastReceiver接收到
        sendBroadcast(sendIntent);

        mHandler.postDelayed(runnable, 2000);//每兩秒執行一次runnable.
    }

    Runnable runnable=new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            //傳送廣播通知Activity更改文字框
            Intent sendIntent = new Intent(MusicPlayActivty.UPFATE_ACTION);
            sendIntent.putExtra("seekbar", mMediaPlayer.getCurrentPosition());

            sendIntent.putExtra("duration",mMediaPlayer.getDuration());
            //傳送廣播,蔣被Activity元件中的BroadcastReceiver接收到
            sendBroadcast(sendIntent);
            mHandler.postDelayed(this, 500);
        }
    };
}