国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Android Studio初學者實例:音樂播放器與Service學習

這篇具有很好參考價值的文章主要介紹了Android Studio初學者實例:音樂播放器與Service學習。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

本次一個案例實現(xiàn)的一個簡單的音樂播放器

用到的知識點最主要的幾點是:Service、handler(實現(xiàn)音樂播放的進度條更新與圖片旋轉)以及用于播放音頻的MediaPlayer

看一下案例效果:

音樂播放器service方式實現(xiàn),Android初學者,Android學習與探索,學習,android音樂播放器service方式實現(xiàn),Android初學者,Android學習與探索,學習,android

?由于Service是Android的四大組件之一,Activity、Service等等一個重要知識點就是生命周期的問題,以下圖片借鑒于W3Cschool

圖示中分別描述了通過startService與通過bindService來啟動Service的生命周期,

可以看到無論是通過哪個方法,都必然的調用生命周期中的onCreate與onDesroy方法,這里簡單的解釋一下使用startService與bindService來啟動Service的主要區(qū)別:startService與它的調用者無必然的聯(lián)系,就是說當調用者結束了自己的生命周期, 但是只要不調用stopService,那么Service還是會繼續(xù)運行bindService來說就是在一條船上

而在本案例中使用的bindService

音樂播放器service方式實現(xiàn),Android初學者,Android學習與探索,學習,android

?

首先看一下

主界面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/beij"
    android:gravity="center"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/iv_music"
        android:layout_width="240dp"
        android:layout_height="240dp"
        android:layout_gravity="center_horizontal"
        android:layout_margin="15dp"
        android:src="@drawable/musics" />

    <SeekBar
        android:id="@+id/sb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:thumb="@drawable/iconbiao"
        android:layout_marginTop="74dp" />
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="8dp"
        android:paddingRight="8dp">
        <TextView
            android:id="@+id/tv_progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="00:00" />
        <TextView
            android:id="@+id/tv_total"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text="00:00" />
    </RelativeLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btn_play"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_margin="8dp"
            android:layout_weight="1"
            android:background="@drawable/btn_bg_selector"
            android:text="播放音樂" />
        <Button
            android:id="@+id/btn_pause"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_margin="8dp"
            android:layout_weight="1"
            android:background="@drawable/btn_bg_selector"
            android:text="暫停播放" />
        <Button
            android:id="@+id/btn_continue_play"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_margin="8dp"
            android:layout_weight="1"
            android:background="@drawable/btn_bg_selector"
            android:text="繼續(xù)播放" />
        <Button
            android:id="@+id/btn_exit"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_margin="8dp"
            android:layout_weight="1"
            android:background="@drawable/btn_bg_selector"
            android:text="退出" />
    </LinearLayout>
</LinearLayout>

其次是Activity代碼

import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
    private static SeekBar sb;
    private static TextView tv_progress, tv_total;
    private ObjectAnimator animator;
    private MusicService.MusicControl musicControl;
    MyServiceConn conn;
    Intent intent;
    private boolean isUnbind = false;//記錄服務是否被解綁
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }
    private void init() {
        tv_progress = (TextView) findViewById(R.id.tv_progress);
        tv_total = (TextView) findViewById(R.id.tv_total);
        sb = (SeekBar) findViewById(R.id.sb);
        findViewById(R.id.btn_play).setOnClickListener(this);
        findViewById(R.id.btn_pause).setOnClickListener(this);
        findViewById(R.id.btn_continue_play).setOnClickListener(this);
        findViewById(R.id.btn_exit).setOnClickListener(this);
        intent = new Intent(this, MusicService.class);//創(chuàng)建意圖對象
        conn = new MyServiceConn();//創(chuàng)建服務連接對象
        bindService(intent, conn, BIND_AUTO_CREATE);  //綁定服務
        Log.i("MusicService","使用了bindService進行綁定服務");
        //為滑動條添加事件監(jiān)聽
        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean
                    fromUser) {                          //滑動條進度改變時,會調用此方法
                if (progress == seekBar.getMax()) { //當滑動條滑到末端時,結束動畫
                    animator.pause();                   //停止播放動畫
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {//滑動條開始滑動時調用
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) { //滑動條停止滑動時調用
                //根據(jù)拖動的進度改變音樂播放進度
                int progress = seekBar.getProgress();//獲取seekBar的進度
                musicControl.seekTo(progress);         //改變播放進度
            }
        });
        ImageView iv_music = (ImageView) findViewById(R.id.iv_music);
        animator = ObjectAnimator.ofFloat(iv_music, "rotation", 0f, 360.0f);
        animator.setDuration(10000);  //動畫旋轉一周的時間為10秒
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(-1);  //-1表示設置動畫無限循環(huán)
    }
    public static Handler handler = new Handler() {//創(chuàng)建消息處理器對象
        //在主線程中處理從子線程發(fā)送過來的消息
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData(); //獲取從子線程發(fā)送過來的音樂播放進度
            int duration = bundle.getInt("duration");                  //歌曲的總時長
            int currentPostition = bundle.getInt("currentPosition");//歌曲當前進度
            sb.setMax(duration);                //設置SeekBar的最大值為歌曲總時長
            sb.setProgress(currentPostition);//設置SeekBar當前的進度位置
            //歌曲的總時長
            int minute = duration / 1000 / 60;
            int second = duration / 1000 % 60;
            String strMinute = null;
            String strSecond = null;
            if (minute < 10) {              //如果歌曲的時間中的分鐘小于10
                strMinute = "0" + minute; //在分鐘的前面加一個0
            } else {
                strMinute = minute + "";
            }
            if (second < 10) {             //如果歌曲的時間中的秒鐘小于10
                strSecond = "0" + second;//在秒鐘前面加一個0
            } else {
                strSecond = second + "";
            }
            tv_total.setText(strMinute + ":" + strSecond);
            //歌曲當前播放時長
            minute = currentPostition / 1000 / 60;
            second = currentPostition / 1000 % 60;
            if (minute < 10) {             //如果歌曲的時間中的分鐘小于10
                strMinute = "0" + minute;//在分鐘的前面加一個0
            } else {
                strMinute = minute + "";
            }
            if (second < 10) {               //如果歌曲的時間中的秒鐘小于10
                strSecond = "0" + second;  //在秒鐘前面加一個0
            } else {
                strSecond = second + "";
            }
            tv_progress.setText(strMinute + ":" + strSecond);
        }
    };
    class MyServiceConn implements ServiceConnection { //用于實現(xiàn)連接服務
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicControl = (MusicService.MusicControl) service;
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }
    private void unbind(boolean isUnbind){
        if(!isUnbind){                  //判斷服務是否被解綁
            musicControl.pausePlay();//暫停播放音樂
            unbindService(conn);      //解綁服務
            Log.i("MusicService","使用了unbindService進行解綁");
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_play:                //播放按鈕點擊事件
                musicControl.play();           //播放音樂
                animator.start();               //播放動畫
                break;
            case R.id.btn_pause:               //暫停按鈕點擊事件
                musicControl.pausePlay();     //暫停播放音樂
                animator.pause();              //暫停播放動畫
                break;
            case R.id.btn_continue_play:     //繼續(xù)播放按鈕點擊事件
                musicControl.continuePlay(); //繼續(xù)播放音樂
                animator.start();              //播放動畫
                break;
            case R.id.btn_exit:                //退出按鈕點擊事件
                unbind(isUnbind);               //解綁服務綁定
                Log.i("MusicService","使用了unbind進行解綁");
                isUnbind = true;                //完成解綁服務
                finish();                         //關閉音樂播放界面
                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbind(isUnbind); //解綁服務
        Log.i("MusicService","使用了unbind進行解綁");
    }
}

?然后就是最重要的Service組件

音樂播放器service方式實現(xiàn),Android初學者,Android學習與探索,學習,android

?以及代碼文章來源地址http://www.zghlxwxcb.cn/news/detail-771402.html

public class MusicService extends Service {
    private MediaPlayer player;
    private Timer timer;
    public MusicService() {}

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("MusicService","我是onUnbind方法");
        return super.onUnbind(intent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i("MusicService","我是onBind方法");
        return new MusicControl();
    }
    @Override
    public void onCreate() {
        Log.i("MusicService","我是onCreate方法");
        super.onCreate();
        player = new MediaPlayer();//創(chuàng)建音樂播放器對象
    }
    public void addTimer() {        //添加計時器用于設置音樂播放器中的播放進度條
        if (timer == null) {
            timer = new Timer();     //創(chuàng)建計時器對象
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    if (player == null) return;
                    int duration = player.getDuration();                //獲取歌曲總時長
                    int currentPosition = player.getCurrentPosition();//獲取播放進度
                    Message msg = MainActivity.handler.obtainMessage();//創(chuàng)建消息對象
                    //將音樂的總時長和播放進度封裝至消息對象中
                    Bundle bundle = new Bundle();
                    bundle.putInt("duration", duration);
                    bundle.putInt("currentPosition", currentPosition);
                    msg.setData(bundle);
                    //將消息發(fā)送到主線程的消息隊列
                    MainActivity.handler.sendMessage(msg);
                }
            };
            //開始計時任務后的5毫秒,第一次執(zhí)行task任務,以后每500毫秒執(zhí)行一次
            timer.schedule(task, 5, 500);
        }
    }
    class MusicControl extends Binder {
        public void play() {
            try {
                player.reset();//重置音樂播放器
                //加載多媒體文件
                player = MediaPlayer.create(getApplicationContext(), R.raw.music);
                player.start();//播放音樂
                addTimer();     //添加計時器
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public void pausePlay() {
            player.pause();//暫停播放音樂
        }
        public void continuePlay() {
            player.start();//繼續(xù)播放音樂
        }
        public void seekTo(int progress) {
            player.seekTo(progress);//設置音樂的播放位置
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("MusicService","我是onDestroy方法");
        if (player == null) return;
        if (player.isPlaying()) player.stop();//停止播放音樂
        player.release();//釋放占用的資源
        player = null;//將player置為空
    }
}

到了這里,關于Android Studio初學者實例:音樂播放器與Service學習的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內(nèi)容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • Android Studio初學者實例:SQLite實驗:綠豆通訊錄

    Android Studio初學者實例:SQLite實驗:綠豆通訊錄

    本次實驗是使用SQLite對一個通訊錄表進行簡單增刪改查 以下是實驗效果: ?首先是繼承SQLiteOpenHelper的數(shù)據(jù)庫自定義類 對于此類必須繼承于SQLiteOpenHelper ,當new創(chuàng)造該類的實例的時候會執(zhí)行創(chuàng)建數(shù)據(jù)庫以及表的操作,例如本代碼中數(shù)據(jù)庫名為itcast,數(shù)據(jù)庫表名為informatoin。db

    2024年02月08日
    瀏覽(29)
  • Android Studio初學者實例:ContentProvider讀取手機通訊錄

    Android Studio初學者實例:ContentProvider讀取手機通訊錄

    該實驗是通過ContentProvider讀取手機通訊錄 知識點包含了RecyclerView控件、UriMatcher、ContentResolver 先看效果,顯示手機通訊錄 ?首先是界面的布局代碼 activity_main59.xml 其次是RecyclerView的item布局代碼,其中使用了CardView是為了方便快捷的弄個圓角儲來 main59_item.xml 一個聯(lián)系人的實體

    2024年02月03日
    瀏覽(28)
  • Android Studio初學者實例:Fragment學習--仿美團外賣界面

    Android Studio初學者實例:Fragment學習--仿美團外賣界面

    本次課程為Fragment為主題,課程的示例仿美團外賣界面,不同于底部導航欄的Fragment案例,此界面分為左側切換與頂部切換。本文先是發(fā)布代碼與效果,后續(xù)講解將會在后續(xù)補充。先看看效果: 首先是布局文件代碼:Activity布局:activity_main.xml: 首先父布局用的LinearLayout布局,

    2024年02月03日
    瀏覽(65)
  • git初學者使用教程(包含Android studio中git使用)

    git初學者使用教程(包含Android studio中git使用)

    參考博客 git地址 如: 點擊創(chuàng)建后會出這個頁面 我推薦使用這個部分命令行來設置倉庫 在想要創(chuàng)建git倉庫的文件夾右鍵打開Git Bash Here(前提是安裝了git) 輸入命令(每次輸入一句) 3. 右鍵打開Git設置 在Git中就會出現(xiàn)用戶信息(我電腦的Git用戶是別人的,我沒有修改) 先看

    2024年02月06日
    瀏覽(31)
  • OpenCV實例解析(OpenCV初學者)

    OpenCV實例解析(OpenCV初學者)

    一、計算機視覺 1.定義:給計算機安裝上眼睛(照相機)和大腦(算法),讓其能感知周圍的環(huán)境。它是對生物視覺的一種模擬,通常的做法是通過對采集的圖像或視頻進行處理來獲得相應場景的三維信息。 2.應用: 計算機科學和工程、信號處理、物理學、應用數(shù)學和統(tǒng)計學

    2024年02月08日
    瀏覽(19)
  • R語言爬蟲實例 初學者自用

    R語言爬蟲實例 初學者自用

    本文記錄了使用rvest RSelenium 包進行爬蟲與網(wǎng)頁渲染的相關知識點及本人的編程操作過程。涉及到基本爬取操作、爬取缺失部分如何處理、操作網(wǎng)頁過濾等步驟。 本人非計算機專業(yè),如有措辭不慎敬請?zhí)岢觥?這學期為了湊學分,選了一門R語言的課,才發(fā)現(xiàn)R語言遠比我們想象

    2024年02月02日
    瀏覽(32)
  • 在 Android 中使用 C/C++:初學者綜合指南

    在 Android 中使用 C/C++:初學者綜合指南

    Java 作為一種編程語言,具有許多良好的功能,使其成為應用程序開發(fā)的首選語言。它獨立于平臺(因為虛擬機執(zhí)行)、JIT 編譯、多線程支持以及為程序員提供的富有表現(xiàn)力的簡單語法。由于其與平臺無關的特性,Java 包可以跨 CPU 架構移植,這使得庫開發(fā)變得更加容易,從而

    2024年03月13日
    瀏覽(30)
  • Mac安裝配置Visual Studio Code(vscode)以及Java環(huán)境詳細教程(初學者必看)

    Mac安裝配置Visual Studio Code(vscode)以及Java環(huán)境詳細教程(初學者必看)

    原本博主今天想繼續(xù)給大家出Java接下來的教程,但是就在昨天我在配置vscode的時候遇到了一些問題,Windows系統(tǒng)的小伙伴配置起來肯定很方便,但是在Mac的小伙伴卻顯得十分無奈,所以我想給大家出一篇Mac的Visual Studio Code配置以及Java環(huán)境搭建教程! 博客主頁:Jovy.的博客_CSDN博客-領

    2024年02月01日
    瀏覽(30)
  • 初學者不會寫接口怎么辦?微軟Visual Studio 2022無腦式API接口創(chuàng)建——Swagger一鍵導入APIKit快速測試

    初學者不會寫接口怎么辦?微軟Visual Studio 2022無腦式API接口創(chuàng)建——Swagger一鍵導入APIKit快速測試

    目錄 VsualStudio2022各版本說明 社區(qū)版本具體說明 VisualStudio2022下載選項 VisualStudio2022啟動樣式 VisualStudio2022圖標樣式 VisualStudio2022初始內(nèi)存消耗 創(chuàng)建項目ASP.NET Core項目 具體項目創(chuàng)建 編輯項目名稱與項目位置 創(chuàng)建配置 創(chuàng)建API控制器 修改路由配置 配置跨域 準備創(chuàng)建接口 創(chuàng)建【

    2024年02月05日
    瀏覽(18)
  • Android Studio 實現(xiàn)音樂播放器

    Android Studio 實現(xiàn)音樂播放器

    ?? 文章末尾有獲取完整項目源碼方式 ?? ????????Android初學者開發(fā)第一個完整的實例項目應該就屬《音樂播放器》了,項目包含SQLlit數(shù)據(jù)庫的使用、listview、Fragment、等。話不多說先上成品: Android Studio 音樂播放器 圖片效果展示: 1.啟動頁效果 2.登錄頁效果 3.注冊頁效果

    2024年02月06日
    瀏覽(24)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包