代码之家  ›  专栏  ›  技术社区  ›  whirlwin

Android音乐播放器小工具

  •  7
  • whirlwin  · 技术社区  · 15 年前

    我正在开发一个音乐播放器小部件(主屏幕小部件)。 它只需要播放一首歌(最好是在MediaPlayer类中)。但我不知道如何实现它。我对Android开发有点缺乏经验,正如前面提到的。

    到目前为止我所上的课已经扩展了 AppWidgetProvider 我想让这门课来处理音乐演奏部分不是个好主意,而是 Service . 如果是,怎么办?

    此外,我有三个按钮:播放、暂停和停止,我可以区分哪个按钮被按下 onReceive(...) .

    事先谢谢!


    这是班级。

    public class MusicManager extends AppWidgetProvider {
    
        private final String ACTION_WIDGET_PLAY = "PlaySong";
        private final String ACTION_WIDGET_PAUSE = "PauseSong";
        private final String ACTION_WIDGET_STOP = "StopSong";   
        private final int INTENT_FLAGS = 0;
        private final int REQUEST_CODE = 0;
    
        @Override
        public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                int[] appWidgetIds) {
    
            RemoteViews controlButtons = new RemoteViews(context.getPackageName(),
                    R.layout.main);
    
            Intent playIntent = new Intent(context, MusicService.class);
    
            Intent pauseIntent = new Intent(context, MusicService.class);
    
            Intent stopIntent = new Intent(context, MusicService.class);
    
    
            PendingIntent playPendingIntent = PendingIntent.getService(
                    context, REQUEST_CODE, playIntent, INTENT_FLAGS);
            PendingIntent pausePendingIntent = PendingIntent.getService(
                    context, REQUEST_CODE, pauseIntent, INTENT_FLAGS);
            PendingIntent stopPendingIntent = PendingIntent.getService(
                    context, REQUEST_CODE, stopIntent, INTENT_FLAGS);
    
            controlButtons.setOnClickPendingIntent(
                    R.id.btnPlay, playPendingIntent);
            controlButtons.setOnClickPendingIntent(
                    R.id.btnPause, pausePendingIntent);
            controlButtons.setOnClickPendingIntent(
                    R.id.btnStop, stopPendingIntent);
    
            appWidgetManager.updateAppWidget(appWidgetIds, controlButtons);         
        }
    }
    
    2 回复  |  直到 13 年前
        1
  •  4
  •   whirlwin    15 年前

    补充 <service android:name=".MusicService" android:enabled="true" /> 到舱单上!

        2
  •  0
  •   aromero    15 年前

    在 onUpdate(...) 你的方法 AppWidgetProvider ,使用类似的方法启动服务(此示例将服务与按钮单击事件关联):

    Intent intent = new Intent(context, MusicService.class);
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
    
    // Get the layout for the App Widget and attach an on-click listener to the button
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider_layout);
    views.setOnClickPendingIntent(R.id.button, pendingIntent);
    

    更多信息,请看 here