歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android:一步一步實現音樂播放器

Android:一步一步實現音樂播放器

日期:2017/3/1 10:28:27   编辑:Linux編程
已經做過一個Android版音樂播放器,模仿音樂播放器項目(見http://www.linuxidc.com/Linux/2012-02/53967.htm),這個播放器基本功能已經實現,但是最大的問題是播放代碼放在了activity中處理的,當推出音樂播放界面的時候,音樂是需要繼續播放,當帶過來電話時音樂需要暫停,打完電話繼續播放,所以以前的版本還是有很大問題的,今天決定一步一步實現一個功能齊全的播放器,把播放控制代碼放在service中。

首先來實現這樣一個簡單的界面:

新建一個android項目,如圖所示:

把項目中用到的圖片拷貝到drawable目錄下,編寫main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <TabHost xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id="@android:id/tabhost"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent" >
  6. <LinearLayout
  7. android:layout_width="fill_parent"
  8. android:layout_height="fill_parent"
  9. android:orientation="vertical"
  10. android:padding="5dp" >
  11. <TabWidget
  12. android:id="@android:id/tabs"
  13. android:layout_width="fill_parent"
  14. android:layout_height="wrap_content" />
  15. <FrameLayout
  16. android:id="@android:id/tabcontent"
  17. android:layout_width="fill_parent"
  18. android:layout_height="fill_parent"
  19. android:padding="5dp" />
  20. </LinearLayout>
  21. </TabHost>
編寫MainActivity類
  1. public class MainActivity extends TabActivity {
  2. /** Called when the activity is first created. */
  3. @Override
  4. public void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. requestWindowFeature(Window.FEATURE_NO_TITLE);
  7. this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  8. WindowManager.LayoutParams.FLAG_FULLSCREEN);
  9. setContentView(R.layout.main);
  10. Resources res = getResources();
  11. TabHost tabHost = getTabHost();
  12. TabHost.TabSpec spec;
  13. Intent intent;
  14. intent = new Intent().setClass(this, ListActivity.class);
  15. spec = tabHost.newTabSpec("音樂").setIndicator("音樂",
  16. res.getDrawable(R.drawable.item))
  17. .setContent(intent);
  18. tabHost.addTab(spec);
  19. intent = new Intent().setClass(this, ArtistsActivity.class);
  20. spec = tabHost.newTabSpec("藝術家").setIndicator("藝術家",
  21. res.getDrawable(R.drawable.artist))
  22. .setContent(intent);
  23. tabHost.addTab(spec);
  24. intent = new Intent().setClass(this, AlbumsActivity.class);
  25. spec = tabHost.newTabSpec("專輯").setIndicator("專輯",
  26. res.getDrawable(R.drawable.album))
  27. .setContent(intent);
  28. tabHost.addTab(spec);
  29. intent = new Intent().setClass(this, SongsActivity.class);
  30. spec = tabHost.newTabSpec("最近播放").setIndicator("最近播放",
  31. res.getDrawable(R.drawable.album))
  32. .setContent(intent);
  33. tabHost.addTab(spec);
  34. tabHost.setCurrentTab(0);
  35. }
  36. }
注意這裡要繼承的是TabActivity,關於TabHost的用法不做過多介紹,官網有。最後分別建立其他用到的activity和使用的xml布局文件,不要忘記在manifest中注冊,

這樣上面的主界面就完成了。

Copyright © Linux教程網 All Rights Reserved