【问题标题】:Playing/Controlling songs from Android AppWidget从 Android AppWidget 播放/控制歌曲
【发布时间】:2019-02-02 06:36:22
【问题描述】:

我创建了服务类来播放/暂停 Activity 中的歌曲。但是我无法从 AppWidget 运行该服务,也无法像我在 Activity 中处理的那样处理点击事件。非常感谢有价值的 cmets/answers。谢谢。

服务类

public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
    MediaPlayer.OnCompletionListener {

//media player
private MediaPlayer player;
//song list
private ArrayList<Song> songs;
//current position
private int songPosn;
//binder
private final IBinder musicBind = new MusicBinder();

@Nullable
@Override
public IBinder onBind(Intent intent) {
    Log.e("***", "MusicService - onBind");
    return musicBind;
}

@Override
public boolean onUnbind(Intent intent) {
    Log.e("***", "MusicService - onUnbind");
    player.stop();
    player.release();
    return false;
}

@Override
public void onDestroy() {
    Log.e("***", "MusicService - onDestroy");
    super.onDestroy();
}

@Override
public void onCreate() {
    super.onCreate();
    Log.e("***", "MusicService - onCreate");
    //initialize position
    songPosn = 0;
    //create player
    player = new MediaPlayer();
    //initialize
    initMusicPlayer();
}

public void initMusicPlayer() {
    //set player properties
    player.setWakeMode(getApplicationContext(),
            PowerManager.PARTIAL_WAKE_LOCK);
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    //set listeners
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
}

@Override
public void onCompletion(MediaPlayer mp) {

}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    return false;
}

@Override
public void onPrepared(MediaPlayer mp) {
    //start playback
    mp.start();
}

public void setList(ArrayList<Song> theSongs) {
    songs = theSongs;
}

public class MusicBinder extends Binder {
    public MusicService getService() {
        return MusicService.this;
    }
}

public void playSong() {
    //play a song
    player.reset();

    //get song
    Song playSong = songs.get(songPosn);
    //get id
    long currSong = playSong.getID();
    //set uri
    Uri trackUri = ContentUris.withAppendedId(
            android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            currSong);
    //set the data source
    try {
        player.setDataSource(getApplicationContext(), trackUri);
    } catch (Exception e) {
        Log.e("MUSIC SERVICE", "Error setting data source", e);
    }

    player.prepareAsync();
}

public void stopSong() {
    player.stop();
    player.reset();
}

public void pauseSong() {
    player.pause();
}

public void resumeSong() {
    player.start();
}

public void setSong(int songIndex) {
    songPosn = songIndex;
}
}

AppWidget 类

 public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // There may be multiple widgets active, so update all of them
    for (int appWidgetId : appWidgetIds) {
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);

   //            //views.setTextViewText(R.id.appwidget_text, String.valueOf(appWidgetId));

        // Create an Intent to launch ExampleActivity
  //            Intent intent = new Intent(context, MainActivity.class);
  //            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        Intent intent = new Intent(context, MusicService.class);
        PendingIntent pendingIntent = PendingIntent.getForegroundService(context, 0, intent, 0);

        // Get the layout for the App Widget and attach an on-click listener
        // to the button
        views.setOnClickPendingIntent(R.id.appwidget_text, pendingIntent);

        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

【问题讨论】:

  • 告诉我错误和logcat
  • @bugfreerammohan 以上服务类正在活动中工作。我也想从 Widget 做同样的播放暂停。服务正在从 Widget 运行,但如何在服务中播放暂停停止音乐,同时单击 AppWidget 中的按钮。我需要一些想法或建议来处理。

标签: android service android-appwidget android-music-player


【解决方案1】:

您的服务已绑定,所以问题是您无法从 AppWidgetProvider 绑定到服务(因为它是一个 BroadcastReceiver )。您已经在按钮单击时设置了待处理的意图,只需将此意图设为唯一并确定当前在 onStartCommand() 服务调用中执行的操作。

在准备远程视图时:

Intent intent = new Intent(context, MusicService.class);
intent.setAction("TEXT_CLICK");
PendingIntent pendingIntent = PendingIntent.getForegroundService(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.appwidget_text, pendingIntent);

所以现在在 onStartCommand 中检查这个动作是这样的:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent == null || intent.getAction() == null) {
        return super.onStartCommand(null, flags, startId);
    }

    if (intent.getAction().equals("TEXT_CLICK")) {
       //make whatever you want (play/stop song, next/previous etc)
    }

    return super.onStartCommand(intent, flags, startId);
}

【讨论】:

  • 很好,工作正常。还有如何在 AppWidget 中单击按钮时更新文本(播放到暂停)
  • 你可以用类似的方式在另一边做同样的事情,因为你的应用小部件提供者是一个广播接收器,你可以覆盖 onReceive 并更新远程视图
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多