Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何使用交互式通知为Web广播流创建Android前台服务?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

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

public class Streamingservice extends service
        implements MediaPlayer.onPreparedListener,MediaPlayer.onErrorListener {

    // .. snipped out fields

    private Au@L_220_5@manager.onAudioFocuschangelistener mOnAudioFocuschangelistener =
            new Au@L_220_5@manager.onAudioFocuschangelistener() {
                @Override
                public void onAudioFocusChange(int focusChangE) {
                    switch (focusChangE) {
                        case Au@L_220_5@manager.AUdioFOCUS_GAIN:
                            // set mCurrentAudioFocusState field
                    }

                    if (mMediaPlayer != null)
                        configureplayerState();
                }
            };

    privatE int mCurrentAudioFocusState = AUdio_NO_FOCUS_NO_DUCK;

    private final IntentFilter mAudioNoisyIntentFilter =
            new IntentFilter(Au@L_220_5@manager.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();

        Au@L_220_5@manager mAu@L_220_5@manager = (Au@L_220_5@manager)
                getSystemservice(Context.AUdio_serviCE);

        int result = mAu@L_220_5@manager.requestAudioFocus(
                mOnAudioFocuschangelistener,Au@L_220_5@manager.STREAM_MUSIC,Au@L_220_5@manager.AUdioFOCUS_GAIN
        );

        if (result != Au@L_220_5@manager.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(Au@L_220_5@manager.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: +727ms
05-06 12:41:23.955  1903  2517 D Audioservice: Stream muted,skip playBACk
05-06 12:41:23.962  1903  3205 I Activitymanager: START u0 {CR_13_11845@p=com.ojm.pinstream/.activities.PlayActivity} from uid 10191
05-06 12:41:23.979 12786 12786 W Au@L_220_5@manager: Use of stream types is deprecated for operations other than volume control
05-06 12:41:23.979 12786 12786 W Au@L_220_5@manager: See the documentation of requestAudioFocus() for what to use instead with android.media.AudioAttributes to qualify your playBACk use case
05-06 12:41:23.980  1903  3205 I MediaFocusControl: requestAudioFocus() from uid/pid 10191/12786 clientId=android.media.Au@L_220_5@manager@6badb4bcom.ojm.pinstream.services.Streamingservice$1@3626928 callingPack=com.ojm.pinstream req=1 flags=0x0 sdk=27
05-06 12:41:23.986 12786 12786 W MediaPlayer: Use of stream types is deprecated for operations other than volume control
05-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 case
05-06 12:41:23.990 12786 12786 V Mediahttpservice: Mediahttpservice(android.media.Mediahttpservice@9e12641): Cookies: null
05-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@5cb47e6
05-06 12:41:23.997 12786 12808 V Mediahttpservice: makehttpconnection(android.media.Mediahttpservice@9e12641): cookieHandler: java.net.CookieManager@5cb47e6 Cookies: null
05-06 12:41:24.005 12786 12808 D NetworkSecurityConfig: No Network Security Config specified,using platform default
05-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=45KB
05-06 12:41:24.076 12786 12791 I zygote64: After code cache collection,data=45KB
05-06 12:41:24.078 12786 12791 I zygote64: Increasing code cache capacity to 256KB
05-06 12:41:24.203  1903  1994 I Activitymanager: Displayed com.ojm.pinstream/.activities.PlayActivity: +203ms
05-06 12:41:24.227 12786 12807 D OpenGLRenderer: endAllActiveAnimators on 0x7bd8b64c00 (ListView) with handle 0x7be64b8340
05-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=1
05-06 12:41:28.322  5051  5051 D EventProcessor: Reading events starTing with id 1675
05-06 12:41:28.322  5051  5051 V Apirequest: Performing request to https://127.0.0.1:8384/rest/events?since=1675&limit=0
05-06 12:41:28.733  1903  8861 D WificondControl: Scan result ready event
05-06 12:41:29.020  1808 12827 D Genericsource: stopBufferingIfNecessary_l,mBuffering=0
05-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,@R_960_6165@State 0
05-06 12:41:29.040  1808  2811 D NuPlayerDriver: start(0xe8513800),state is 4,eos is 0
05-06 12:41:29.041  1808 12818 I Genericsource: start
05-06 12:41:29.061  1808 12834 I OMXClient: Treble IOmx obtained
05-06 12:41:29.061  1812  1902 I OMXMaster: makeComponenTinstance(OMX.google.mp3.decoder) in omx@1.0-service process
05-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 mode
05-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,@R_960_6165@State 0
05-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 mActiveDrmscheR_13_11845@e=false
05-06 12:41:29.102 12786 12786 V MediaPlayer: cleanDrmObj: mDrmObj=null mDrmSessionId=null
05-06 12:41:29.102  1808  2811 D NuPlayerDriver: reset(0xe8513800) at state 8
05-06 12:41:29.103  1903  1903 I Notificationservice: CAnnot find enqueued record for key: 0|com.ojm.pinstream|576|null|10191
05-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(),根据文档:

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

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

@H_551_9@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前台服务?所遇到的程序开发问题。

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。