2010-11-28 160 views
4

我正在製作一個音樂播放器小部件(主屏幕小部件).. 它只需要播放1首歌曲(最好使用MediaPlayer類)。但我不知道如何實現它。我對Android開發並不熟悉,就這麼提及。Android音樂播放器小部件

我有類到目前爲止擴展AppWidgetProvider,我想這不是一個好主意,讓這個類處理音樂播放一部分,而是一個Service。如果是這樣,怎麼樣?此外,我有3個按鈕:播放,暫停和停止,並且我可以區分在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);   
    } 
} 

回答

3

增加了<service android:name=".MusicService" android:enabled="true" /> 到清單!

0

在你AppWidgetProvideronUpdate(...)方法,使用這樣的啓動服務(本例中,服務於一個按鈕單擊事件相關聯):

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

+0

感謝您的答案,但它仍然無法正常工作。我可能在這裏錯失了一些很明顯的東西。 – whirlwin 2010-11-28 22:22:35

+0

你怎麼知道問題不在服務中?讓服務在啓動時記錄一些內容,這樣至少可以知道它們是否被調用。 – aromero 2010-11-29 00:13:51