Android之Notification制作多媒体控制器
? ? 上一篇講述了Notification的基礎(chǔ)用法,本篇將介紹,自定義通知欄,并利用講到的內(nèi)容,實現(xiàn)一個簡單的音樂播發(fā)器。
?1.自定義通知的實現(xiàn);
? Notification有一個contentView屬性,該屬性接受的對象是RemoteView對象,用它即可實現(xiàn)自定義布局.
? 獲取RemoteView對象的方法:
2.添加通知欄響應(yīng)事件
?
Intent buttonplayIntent = new Intent("play");PendingIntent pendplayButtonIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, buttonplayIntent, 0);mRemoteViews.setOnClickPendingIntent(R.id.play, pendplayButtonIntent);?其中關(guān)于PendingIntent
?PendingIntent用于描述Intent及其最終的行為.?
? ?? ???你可以通過getActivity(Context context, int requestCode, Intent intent, int flags)系列方法從系統(tǒng)取得一個用于啟動一個Activity的PendingIntent對象,
? ?? ? 可以通過getService(Context context, int requestCode, Intent intent, int flags)方法從系統(tǒng)取得一個用于啟動一個Service的PendingIntent對象
? ?? ???可以通過getBroadcast(Context context, int requestCode, Intent intent, int flags)方法從系統(tǒng)取得一個用于向BroadcastReceiver的Intent廣播的PendingIntent對象
? ?? ?? ?返回的PendingIntent可以遞交給別的應(yīng)用程序,然后繼續(xù)處理。這里的話你可以稍后才處理PendingIntent中描述的Intent及其最終行為。
3.完整的創(chuàng)建自定義通知方法:
?
Notification mNotification;RemoteViews mRemoteViews;NotificationManager notificationManager;public void createNotifiView() {notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);mNotification = new Notification(R.drawable.ic_launcher, "MusicDemo",System.currentTimeMillis());mNotification.flags |= Notification.FLAG_ONGOING_EVENT;Intent intent = new Intent(Intent.ACTION_MAIN);intent.setClass(getApplicationContext(), MainActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,PendingIntent.FLAG_CANCEL_CURRENT);mNotification.contentIntent = pendingIntent;if (mRemoteViews == null) {mRemoteViews = new RemoteViews(getPackageName(),R.layout.notify_view);}Intent buttoncloseIntent = new Intent("close");PendingIntent pendcloseButtonIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, buttoncloseIntent, 0);mRemoteViews.setOnClickPendingIntent(R.id.close, pendcloseButtonIntent);Intent buttonplayIntent = new Intent("play");PendingIntent pendplayButtonIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, buttonplayIntent, 0);mRemoteViews.setOnClickPendingIntent(R.id.play, pendplayButtonIntent);//Intent buttonnextIntent = new Intent("next");PendingIntent pendnextButtonIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, buttonnextIntent, 0);mRemoteViews.setOnClickPendingIntent(R.id.next, pendnextButtonIntent);Intent buttonprewtIntent = new Intent("prew");PendingIntent pendprewButtonIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, buttonprewtIntent, 0);mRemoteViews.setOnClickPendingIntent(R.id.prew, pendprewButtonIntent);mRemoteViews.setTextViewText(R.id.songName, "歌曲名");if (!MainActivity.isPlay) {mRemoteViews.setImageViewResource(R.id.play,R.drawable.statusbar_btn_play);mRemoteViews.setOnClickPendingIntent(R.id.play,pendplayButtonIntent);} else {mRemoteViews.setImageViewResource(R.id.play,R.drawable.statusbar_btn_pause);mRemoteViews.setOnClickPendingIntent(R.id.play,pendplayButtonIntent);}mNotification.contentView = mRemoteViews;notificationManager.notify(0, mNotification);}因為這里用了getBroadCast()獲取PendingIntent,所以該Intent是通過發(fā)送廣播來告知通知欄控件發(fā)生了觸發(fā)事件。
所以,需要在響應(yīng)界面過濾action,注冊響應(yīng)廣播。
先給出通知布局文件notifiy_view:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"tools:ignore="ContentDescription" ><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="64dp"android:orientation="vertical" ><ImageViewandroid:id="@+id/icon_pic"android:layout_width="60dp"android:layout_height="60dp"android:layout_centerVertical="true" /><ImageButtonandroid:id="@+id/close"android:layout_width="30dp"android:layout_height="30dp"android:layout_alignParentRight="true"android:layout_alignParentTop="true"android:layout_marginRight="10dp"android:layout_marginTop="10dp"android:background="@drawable/status_bg"android:src="@drawable/statusbar_close" /><TextViewandroid:id="@+id/songName"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:layout_marginRight="5dp"android:layout_marginTop="10dp"android:layout_toLeftOf="@+id/close"android:layout_toRightOf="@+id/icon_pic"android:ellipsize="end"android:singleLine="true"android:text="歌名"android:textSize="15dp" /><ImageButtonandroid:id="@+id/prew"android:layout_width="30dp"android:layout_height="30dp"android:layout_alignParentBottom="true"android:layout_centerInParent="true"android:background="@drawable/status_bg"android:src="@drawable/statusbar_btn_prev" /><ImageButtonandroid:id="@+id/play"android:layout_width="30dp"android:layout_height="30dp"android:layout_alignTop="@+id/prew"android:layout_marginLeft="10dp"android:layout_toRightOf="@+id/prew"android:background="@drawable/status_bg"android:src="@drawable/statusbar_btn_play" /><ImageButtonandroid:id="@+id/next"android:layout_width="30dp"android:layout_height="30dp"android:layout_alignTop="@+id/prew"android:layout_marginLeft="10dp"android:layout_toRightOf="@+id/play"android:background="@drawable/status_bg"android:src="@drawable/statusbar_btn_next" /></RelativeLayout></LinearLayout>
我將會把項目放在CSDN上,大家可以下載,獲取相應(yīng)的資源文件
在這個小項目中,我將播放的service做為的是后臺服務(wù),然后廣播也提出來了,作為一個公用的廣播,如果只是做簡單播放用,可以將廣播放在播放界面。
項目中用到的廣播:
public class MusicBroadCast extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Intent musicServiceIntent = new Intent(context, MusicService.class);if (intent.getAction().equals("play")) {musicServiceIntent.putExtra(MusicService.MusicCommandKey, ""+ MusicService.MusicPlayCommand);context.startService(musicServiceIntent);} else if (intent.getAction().equals("next")) {musicServiceIntent.putExtra(MusicService.MusicCommandKey, ""+ MusicService.MusicNextCommand);context.startService(musicServiceIntent);} else if (intent.getAction().equals("prew")) {musicServiceIntent.putExtra(MusicService.MusicCommandKey, ""+ MusicService.MusicNextCommand);context.startService(musicServiceIntent);} else if (intent.getAction().equals("close")) {musicServiceIntent.putExtra(MusicService.MusicCommandKey, "");context.startService(musicServiceIntent);} else if (intent.getAction().equals("android.media.AUDIO_BECOMING_NOISY")) {// 耳機拔出事件musicServiceIntent.putExtra(MusicService.MusicCommandKey,MusicService.MusicPauseCommand+ MusicService.MusicPauseCommand);context.startService(musicServiceIntent);}}}
我這里是在service注冊的廣播,這個應(yīng)該有點夸張了,由于項目需要全局播放,然后由通知欄也可以控制,就這樣做了。
service文件代碼:
package com.example.musicdemo;import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.IBinder; import android.support.annotation.Nullable; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import android.widget.RemoteViews;import java.io.IOException;/*** Create by gaylen on 2015/12/9 11:07*/public class MusicService extends Service {// 其他對象控制Service進(jìn)行音頻播放操作// 全部采用命令+命令參數(shù)的形式處理public static final int MusicInitCommand = 0;public static final int MusicPlayCommand = 10;public static final int MusicStopCommand = 20;public static final int MusicPauseCommand = 30;public static final int MusicSeekToCommand = 40;public static final int MusicNextCommand = 50;public static final int MusicPrevCommand = 60;public static final int MusicNotificationCommand = 70;// 所有的命令參數(shù)都String傳遞// 非String類型,采取轉(zhuǎn)型處理public static String MusicCommandKey = "CtrlCommand";public static String MusicParameterKey = "CommandParameter";private MusicBroadCast broadCast;@Overridepublic void onCreate() {super.onCreate();broadCast = new MusicBroadCast();IntentFilter filter = new IntentFilter();filter.addAction("play");filter.addAction("next");filter.addAction("prew");filter.addAction("close");// 耳機filter.addAction("android.media.AUDIO_BECOMING_NOISY");// 短信// mSystemFilter.addAction("android.provider.Telephony.SMS_RECEIVED");registerReceiver(broadCast, filter);regeisterCallLisenler();/*** 為了防止通知欄點擊時出現(xiàn)閃屏,在開啟service就將一些對象實例化了*/notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);mNotification = new Notification(R.drawable.ic_launcher, "MusicDemo",System.currentTimeMillis());mNotification.flags |= Notification.FLAG_ONGOING_EVENT;Intent intent = new Intent(Intent.ACTION_MAIN);intent.setClass(getApplicationContext(), MainActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,PendingIntent.FLAG_CANCEL_CURRENT);mNotification.contentIntent = pendingIntent;}@Nullable@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// 分析傳入的命令,根據(jù)不同命令調(diào)用不同方法String commandValue = intent.getStringExtra(MusicCommandKey);if (commandValue != null) {int command = Integer.parseInt(commandValue);switch (command) {case MusicService.MusicPlayCommand:// 得到play命令對應(yīng)的參數(shù)String Param = intent.getStringExtra(MusicParameterKey);// 執(zhí)行doPlayCommand方法doPlayCommand(Param);break;case MusicService.MusicStopCommand:stopPlayCommand();break;case MusicService.MusicSeekToCommand:// 解析命令參數(shù)執(zhí)行相關(guān)方法// 得到SeekTo的進(jìn)度(字符串形式)String strProgressSet = intent.getStringExtra(MusicService.MusicParameterKey);doSeekToCommand(strProgressSet);break;case MusicService.MusicNextCommand:doNextCommand();break;case MusicService.MusicPrevCommand:doPreCommand();break;case MusicService.MusicNotificationCommand:createNotifiView();break;}}return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {super.onDestroy();// Service 被結(jié)束,則音樂停止unregisterReceiver(broadCast);}/*** 停止播放*/private void stopPlayCommand() {Log.i("play", "stop");createNotifiView();}private void doPause() {Log.i("play", "pause");}/*** 播放* * @param param*/private void doPlayCommand(String param) {if (MainActivity.isPlay) {doPause();} else {Log.i("play", "play");}createNotifiView();}// 播放下一首命令處理private void doNextCommand() {Log.i("play", "next");}// 播放上一首命令處理private void doPreCommand() {Log.i("play", "pre");}private void doSeekToCommand(String seekToValue) {int seekTo = Integer.parseInt(seekToValue);// 設(shè)置跳轉(zhuǎn)進(jìn)度// mMediaPlayer.seekTo(seekTo);}Notification mNotification;RemoteViews mRemoteViews;NotificationManager notificationManager;public void createNotifiView() {if (mRemoteViews == null) {mRemoteViews = new RemoteViews(getPackageName(),R.layout.notify_view);}Intent buttoncloseIntent = new Intent("close");PendingIntent pendcloseButtonIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, buttoncloseIntent, 0);mRemoteViews.setOnClickPendingIntent(R.id.close, pendcloseButtonIntent);Intent buttonplayIntent = new Intent("play");PendingIntent pendplayButtonIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, buttonplayIntent, 0);mRemoteViews.setOnClickPendingIntent(R.id.play, pendplayButtonIntent);//Intent buttonnextIntent = new Intent("next");PendingIntent pendnextButtonIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, buttonnextIntent, 0);mRemoteViews.setOnClickPendingIntent(R.id.next, pendnextButtonIntent);Intent buttonprewtIntent = new Intent("prew");PendingIntent pendprewButtonIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, buttonprewtIntent, 0);mRemoteViews.setOnClickPendingIntent(R.id.prew, pendprewButtonIntent);mRemoteViews.setTextViewText(R.id.songName, "歌曲名");if (!MainActivity.isPlay) {mRemoteViews.setImageViewResource(R.id.play,R.drawable.statusbar_btn_play);mRemoteViews.setOnClickPendingIntent(R.id.play,pendplayButtonIntent);} else {mRemoteViews.setImageViewResource(R.id.play,R.drawable.statusbar_btn_pause);mRemoteViews.setOnClickPendingIntent(R.id.play,pendplayButtonIntent);}mNotification.contentView = mRemoteViews;notificationManager.notify(0, mNotification);}private AudioManager mAudioManager;public void regeisterCallLisenler() {mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);// 添加來電監(jiān)聽事件TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // 獲取系統(tǒng)服務(wù)telManager.listen(new MobliePhoneStateListener(),PhoneStateListener.LISTEN_CALL_STATE);}/*** @author wwj 電話監(jiān)聽器類*/private class MobliePhoneStateListener extends PhoneStateListener {@Overridepublic void onCallStateChanged(int state, String incomingNumber) {switch (state) {case TelephonyManager.CALL_STATE_IDLE: // 掛機狀態(tài)// doPlayCommand("");break;case TelephonyManager.CALL_STATE_OFFHOOK: // 通話狀態(tài)case TelephonyManager.CALL_STATE_RINGING: // 響鈴狀態(tài)Log.i("tag", "接收到來電-->");doPause();break;default:break;}}} }
最后就是播放主界面:
public class MainActivity extends ActionBarActivity {public static boolean isPlay = false;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);player();}public void player() {Intent musicServiceIntent = new Intent(MainActivity.this,MusicService.class);// 設(shè)置播放控制命令:playCommandmusicServiceIntent.putExtra(MusicService.MusicCommandKey, ""+ MusicService.MusicPlayCommand);MainActivity.this.startService(musicServiceIntent);} }
布局跟通知欄布局差不多,這里就不寫了。
完整項目源碼可以去:http://download.csdn.net/detail/caihuajian235/9365027下載。
?
總結(jié)
以上是生活随笔為你收集整理的Android之Notification制作多媒体控制器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MedicineCare-可行性分析
- 下一篇: android正则判断两个符号之间,An