如何使用交互式通知为Web广播流创建Android前台服务?

如何使用交互式通知为Web广播流创建Android前台服务?,第1张

概述我正在尝试构建一个非常简单的无线电流应用程序,它存储一个网络无线电URL列表,可以选择流式传输音频;使用服务允许播放继续当应用程序不通过通知控制时.我需要的控件非常简单:播放/暂停和停止,这应该会终止服务并在清除通知或在应用程序中按下停止按钮时引发.我为大量代码道歉,但这就是我所处的位置:public class StreamingService exten

我正在尝试构建一个非常简单的无线电流应用程序,它存储一个网络无线电URL列表,可以选择流式传输音频;使用服务允许播放继续当应用程序不通过通知控制时.

我需要的控件非常简单:播放/暂停和停止,这应该会终止服务并在清除通知或在应用程序中按下停止按钮时引发.

我为大量代码道歉,但这就是我所处的位置:

public class StreamingService extends Service        implements MediaPlayer.OnPreparedListener,MediaPlayer.OnErrorListener {    // .. snipped out fIElds    private AudioManager.OnAudioFocuschangelistener mOnAudioFocuschangelistener =            new AudioManager.OnAudioFocuschangelistener() {                @OverrIDe                public voID onAudioFocusChange(int focusChange) {                    switch (focusChange) {                        case AudioManager.AUdioFOCUS_GAIN:                            // set mCurrentAudioFocusstate fIEld                    }                    if (mMediaPlayer != null)                        configurePlayerState();                }            };    private int mCurrentAudioFocusstate = AUdio_NO_FOCUS_NO_DUCK;    private final IntentFilter mAudioNoisyIntentFilter =            new IntentFilter(AudioManager.ACTION_AUdio_BECOMING_NOISY);    private broadcastReceiver mNoisyReceiver = new broadcastReceiver() {        @OverrIDe        public voID onReceive(Context context,Intent intent) {            // Pause when headphones unplugged            mMediaPlayer.pause();        }    };    private boolean mAudioNoisyReceiverRegistered = false;    @OverrIDe    public voID onCreate() {        super.onCreate();        AudioManager mAudioManager = (AudioManager)                getSystemService(Context.AUdio_SERVICE);        int result = mAudioManager.requestAudioFocus(                mOnAudioFocuschangelistener,AudioManager.STREAM_MUSIC,AudioManager.AUdioFOCUS_GAIN        );        if (result != AudioManager.AUdioFOCUS_REQUEST_GRANTED) {            stopSelf();        } else {            mCurrentAudioFocusstate = AUdio_FOCUSED;        }    }    @OverrIDe    public int onStartCommand(Intent intent,int flags,int startID) {        mMediaPlayer = new MediaPlayer();        mMediaPlayer.setonPreparedListener(this);        mMediaPlayer.setonErrorListener(this);        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);        mMediaPlayer.setWakeMode(getApplicationContext(),PowerManager.PARTIAL_WAKE_LOCK);        WifiManager.WifiLock wifiLock =                ((WifiManager) Objects.requireNonNull(                        getApplicationContext().getSystemService(Context.WIFI_SERVICE)))                        .createWifiLock(WifiManager.WIFI_MODE_FulL,"wifi_lock");        wifiLock.acquire();        try {            mMediaPlayer.setDataSource(intent.getStringExtra(STREAM_URI));        } catch (IOException e) {            e.printstacktrace();        }        mMediaPlayer.prepareAsync();        onStartIntent = intent;        return Service.START_STICKY;    }    @OverrIDe    public voID onDestroy() {        mMediaPlayer.release();    }    @Nullable    @OverrIDe    public IBinder onBind(Intent intent) {        return null;    }    @OverrIDe    public boolean onError(MediaPlayer mediaPlayer,int i,int i1) {        mMediaPlayer.reset();        return true;    }    @OverrIDe    public voID onPrepared(MediaPlayer mediaPlayer) {        handleIntent(onStartIntent);    }    private voID handleIntent(Intent intent) {        String action = intent.getAction();        String command = intent.getStringExtra(CMD_name);        if (ACTION_CMD.equals(action)) {            switch (command) {                case CMD_PLAY:                    registeraudioNoisyReceiver();                    mMediaPlayer.start();                    startForeground(NOTIFICATION_ID,buildNotification());                case CMD_PAUSE:                    unregisteraudioNoisyReceiver();                    mMediaPlayer.pause();                    startForeground(NOTIFICATION_ID,buildNotification());                case CMD_Stop:                    unregisteraudioNoisyReceiver();                    mMediaPlayer.stop();                    stopSelf();            }        }    }    private Notification buildNotification() {        createNotificationChannel();        NotificationCompat.Builder builder =                new NotificationCompat.Builder(getApplicationContext(),NOTIFICATION_CHANNEL);        builder                .setContentTitle(onStartIntent.getStringExtra(STREAM_Title))                .setContentIntent(PendingIntent.getActivity(                        this,new Intent(getApplicationContext(),MainActivity.class),0))                .setVisibility(NotificationCompat.VISIBIliTY_PUBliC)                .setDeleteIntent(getActionIntent(CMD_Stop));        builder                .setSmallicon(androID.R.drawable.ic_media_play)                .setcolor(ContextCompat.getcolor(this,R.color.colorPrimaryDark));        builder                .addAction(new NotificationCompat.Action(                        androID.R.drawable.ic_media_pause,getString(R.string.pause),getActionIntent(CMD_PAUSE)));        builder                .setStyle(new androID.support.v4.media.app.NotificationCompat.MediaStyle()                        .setShowActionsInCompactVIEw(0)                        .setShowCancelbutton(true)                        .setCancelbuttonIntent(                                getActionIntent(CMD_Stop)));        return builder.build();    }    private PendingIntent getActionIntent(String action) {        Intent s = new Intent(getApplicationContext(),StreamingService.class);        s.putExtra(                STREAM_Title,onStartIntent.getStringExtra(STREAM_Title)        );        s.putExtra(                STREAM_URI,onStartIntent.getStringExtra(STREAM_URI)        );        s.setAction(ACTION_CMD);        s.putExtra(                CMD_name,action        );        s.setPackage(getApplicationContext().getPackagename());        return PendingIntent.getService(                getApplicationContext(),s,0);    }    // snipped methods to register and unregister noisy receiver    private voID configurePlayerState() {        switch(mCurrentAudioFocusstate) {            case AUdio_NO_FOCUS_CAN_DUCK:                registeraudioNoisyReceiver();                mMediaPlayer.setVolume(VolUME_DUCK,VolUME_DUCK);            case AUdio_NO_FOCUS_LOST:                unregisteraudioNoisyReceiver();                mMediaPlayer.stop();            case AUdio_NO_FOCUS_NO_DUCK:                unregisteraudioNoisyReceiver();                mMediaPlayer.pause();            case AUdio_FOCUSED:                registeraudioNoisyReceiver();                mMediaPlayer.setVolume(VolUME_norMAL,VolUME_norMAL);        }    }    private voID createNotificationChannel() {        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {            CharSequence name = getString(R.string.channel_name);            String description = getString(R.string.channel_description);            int importance = notificationmanager.importANCE_DEFAulT;            NotificationChannel channel =                    new NotificationChannel(NOTIFICATION_CHANNEL,name,importance);            channel.setDescription(description);            notificationmanager notificationmanager = getSystemService(notificationmanager.class);            assert notificationmanager != null;            notificationmanager.createNotificationChannel(channel);        }    }}

这是通过使用Google的媒体播放,AndroID文档和UAMP等示例应用以及其他在线示例的讲座来整理的.

它目前的代码:启动,似乎设置音频,但似乎暂停,停止和销毁,也破坏通知.在应用程序中没有任何通知,也没有音频播放.这是一个logcat:

05-06 12:41:21.407  1903  1994 I ActivityManager: displayed com.ojm.pinstream/.activitIEs.MainActivity: +727ms05-06 12:41:23.955  1903  2517 D AudioService: Stream muted,skip playback05-06 12:41:23.962  1903  3205 I ActivityManager: START u0 {cmp=com.ojm.pinstream/.activitIEs.PlayActivity} from uID 1019105-06 12:41:23.979 12786 12786 W AudioManager: Use of stream types is deprecated for operations other than volume control05-06 12:41:23.979 12786 12786 W AudioManager: See the documentation of requestAudioFocus() for what to use instead with androID.media.AudioAttributes to qualify your playback use case05-06 12:41:23.980  1903  3205 I MediaFocusControl: requestAudioFocus() from uID/pID 10191/12786 clIEntID=androID.media.AudioManager@6badb4bcom.ojm.pinstream.services.StreamingService@3626928 callingPack=com.ojm.pinstream req=1 flags=0x0 sdk=2705-06 12:41:23.986 12786 12786 W MediaPlayer: Use of stream types is deprecated for operations other than volume control05-06 12:41:23.986 12786 12786 W MediaPlayer: See the documentation of setAudioStreamType() for what to use instead with androID.media.AudioAttributes to qualify your playback use case05-06 12:41:23.990 12786 12786 V MediahttpService: MediahttpService(androID.media.MediahttpService@9e12641): cookies: null05-06 12:41:23.992  1808 25066 D NuPlayerDriver: NuPlayerDriver(0xe8513800) created,clIEntPID(12786)05-06 12:41:23.996 12786 12808 V MediahttpService: makehttpconnection: cookieManager created: java.net.cookieManager@5cb47e605-06 12:41:23.997 12786 12808 V MediahttpService: makehttpconnection(androID.media.MediahttpService@9e12641): cookieHandler: java.net.cookieManager@5cb47e6 cookies: null05-06 12:41:24.005 12786 12808 D NetworkSecurityConfig: No Network Security Config specifIEd,using platform default05-06 12:41:24.053  1903  4685 E NotificationService: Suppressing notification from package by user request.05-06 12:41:24.056  1903  1966 E NotificationService: Suppressing notification from package by user request.05-06 12:41:24.076 12786 12791 I zygote64: Do partial code cache collection,code=60KB,data=45KB05-06 12:41:24.076 12786 12791 I zygote64: After code cache collection,data=45KB05-06 12:41:24.078 12786 12791 I zygote64: Increasing code cache capacity to 256KB05-06 12:41:24.203  1903  1994 I ActivityManager: displayed com.ojm.pinstream/.activitIEs.PlayActivity: +203ms05-06 12:41:24.227 12786 12807 D Openglrenderer: endAllActiveAnimators on 0x7bd8b64c00 (ListVIEw) with handle 0x7be64b834005-06 12:41:27.025  1903  8861 E NotificationService: Suppressing notification from package by user request.05-06 12:41:27.031  1903  1966 E NotificationService: Suppressing notification from package by user request.05-06 12:41:28.257  5051  5051 V APIRequest: Performing request to https://127.0.0.1:8384/rest/events?since=0&limit=105-06 12:41:28.322  5051  5051 D EventProcessor: Reading events starting with ID 167505-06 12:41:28.322  5051  5051 V APIRequest: Performing request to https://127.0.0.1:8384/rest/events?since=1675&limit=005-06 12:41:28.733  1903  8861 D WificondControl: Scan result ready event05-06 12:41:29.020  1808 12827 D GenericSource: stopBufferingIfNecessary_l,mBuffering=005-06 12:41:29.020  1808 12818 D NuPlayerDriver: notifyListener_l(0xe8513800),(1,-1),loop setting(0,0)05-06 12:41:29.039  1903  3205 V MediaRouterService: restoreBluetoothA2dp(false)05-06 12:41:29.039  1711  6225 D AudioPolicyManagerCustom: setForceUse() usage 1,config 10,mPhonestate 005-06 12:41:29.040  1808  2811 D NuPlayerDriver: start(0xe8513800),state is 4,eos is 005-06 12:41:29.041  1808 12818 I GenericSource: start05-06 12:41:29.061  1808 12834 I OMXClIEnt: Treble IOmx obtained05-06 12:41:29.061  1812  1902 I OMXMaster: makeComponentInstance(OMX.Google.mp3.decoder) in omx@1.0-service process05-06 12:41:29.067  1812  1902 E OMXNodeInstance: setConfig(0xf362a720:Google.mp3.decoder,ConfigPriority(0x6f800002)) ERROR: Undefined(0x80001001)05-06 12:41:29.068  1808 12834 I ACodec  : codec does not support config priority (err -2147483648)05-06 12:41:29.068  1812  6179 E OMXNodeInstance: getConfig(0xf362a720:Google.mp3.decoder,ConfigAndroIDvendorExtension(0x6f100004)) ERROR: Undefined(0x80001001)05-06 12:41:29.069  1808 12834 I MediaCodec: MediaCodec will operate in async mode05-06 12:41:29.081  1808  2811 D NuPlayerDriver: pause(0xe8513800)05-06 12:41:29.081  1808  2811 D NuPlayerDriver: notifyListener_l(0xe8513800),(7,0)05-06 12:41:29.082  1903  1966 E NotificationService: Suppressing notification from package by user request.05-06 12:41:29.082  1903  8861 V MediaRouterService: restoreBluetoothA2dp(false)05-06 12:41:29.084  1711  6225 D AudioPolicyManagerCustom: setForceUse() usage 1,mPhonestate 005-06 12:41:29.097  1808  2811 D NuPlayerDriver: stop(0xe8513800)05-06 12:41:29.097  1808  2811 D NuPlayerDriver: notifyListener_l(0xe8513800),(8,0)05-06 12:41:29.101 12786 12786 V MediaPlayer: resetDrmState:  mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false05-06 12:41:29.102 12786 12786 V MediaPlayer: cleanDrmObj: mDrmObj=null mDrmSessionID=null05-06 12:41:29.102  1808  2811 D NuPlayerDriver: reset(0xe8513800) at state 805-06 12:41:29.103  1903  1903 I NotificationService: Cannot find enqueued record for key: 0|com.ojm.pinstream|576|null|1019105-06 12:41:29.108  1808 12826 I NuCachedSource2: caching reached eos.05-06 12:41:29.108  1903  1966 E NotificationService: Suppressing notification from package by user request.05-06 12:41:29.117  1903  3205 E NotificationService: Suppressing notification from package by user request.05-06 12:41:29.117  1808 12818 D NuPlayerDriver: notifyresetComplete(0xe8513800)05-06 12:41:29.121  1903  1966 E NotificationService: Suppressing notification from package by user request.05-06 12:41:29.123  2663  2663 W Statusbar: removeNotification for unkNown key: 0|com.ojm.pinstream|576|null|10191

我对AndroID开发并不熟悉.如果有人可以提供任何帮助,那将非常感激.最佳答案以下是代码中调用的方法链:

>音频开始
>调用startForeground(NOTIFICATION_ID,buildNotification())方法
> buildNotification()方法通过方法getActionIntent(CMD_PAUSE)添加CMD_PAUSE *** 作
> getActionIntent()方法调用方法PendingIntent.getService(getApplicationContext(),0)

问题是你通过一个方法来获取你的PendingIntent并立即启动服务 – PendingIntent.getService(),根据文档:

RetrIEve a PendingIntent that will start a service,like calling
{@link Context#startService Context.startService()}. The start
arguments given to the service will come from the extras of the Intent.

当您的音频开始播放时,它会创建通知,获取CMD_PAUSE *** 作的待处理意图,此待处理意图启动服务,调用handleIntent()方法,并通过待处理的意图设置 *** 作,然后暂停您的音频. .

根据个人经验,您应该使用以下方法进行调查:

MediabuttonReceiver.buildMediabuttonPendingIntent(context,PlaybackStateCompat.ACTION_PLAY)

有关更多详细信息,请参见MediaButtonReceiver documentation.

当媒体服务发生媒体事件(例如按暂停按钮)时,会调用onStartCommand(),因此您应该实现一个简单的回调来处理意图:

overrIDe fun onStartCommand(intent: Intent?,flags: Int,startID: Int): Int {    MediabuttonReceiver.handleIntent(mSession,intent)    return super.onStartCommand(intent,flags,startID)}

您需要找到一种向服务传递新URI的不同方式,例如使用Mediabrowser – 或更简单的方法,绑定到服务并调用方法来刷新活动中的URI.您不应该从触发onStartCommand()的活动中调用startService(). 总结

以上是内存溢出为你收集整理的如何使用交互式通知为Web广播流创建Android前台服务?全部内容,希望文章能够帮你解决如何使用交互式通知为Web广播流创建Android前台服务?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1139590.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存