当应用在后台时无法启动服务

发布于 2025-02-10 23:48:14 字数 6334 浏览 1 评论 0原文

当收到推送通知时,我想开始播放MP3 URL的服务,但是由于Android限制性策略在背景或IDLE服务中未启动时,这是我的代码,因此请使用通知。 我还在使用数据有效负载其工作罚款应用程序位于前景中,但是当应用程序转向后台时,问题就会出现。

我的firebasemessaging class 盯着服务

 val resultIntent = Intent(applicationContext, MusicService::class.java)
                        resultIntent.putExtra("title", title)
                        resultIntent.putExtra("body", body)
                        resultIntent.putExtra("action_type", action_type)
                        resultIntent.putExtra("deep_link_type", deep_link_type)
                        resultIntent.putExtra("deep_link_id", deep_link_id)
                        resultIntent.putExtra("masjid_Id", masjid_Id)
                        resultIntent.putExtra("url", url)
                        Log.i("***TAG", "From Background")
                        resultIntent.setAction("com.example.mymasjid");
//                        resultIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
                        startService(resultIntent) 


**My Music Service Class** 


class MusicService : Service(), MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener,
    MediaPlayer.OnErrorListener {

    var objService: MusicService? = null
    var title: String = ""
    var body: String = ""
//    private val mBinder: IBinder = LocalBinder()

    override fun onCreate() {
        super.onCreate()
//        if (title.isNotEmpty() && body.isNotEmpty())
            adhanNotification(title, body)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
//        val url = intent!!.getStringExtra("url")
         title = intent!!.getStringExtra("title").toString()
         body = intent!!.getStringExtra("body").toString()
//        if (title!!.isNotEmpty() && body!!.isNotEmpty())
            Log.i("***TAG","From Background Service")
            adhanNotification(title, body)
        val url = "https://cdn.islamic.network/quran/audio/64/ar.alafasy/9.mp3"
        if (mediaPlayer != null) {
            mediaPlayer!!.stop()
            mediaPlayer!!.release()
            mediaPlayer = null
        }
        mediaPlayer = MediaPlayer()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mediaPlayer!!.setAudioAttributes(
                AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .setLegacyStreamType(AudioManager.STREAM_MUSIC)
                    .build()
            );
        } else {
            mediaPlayer!!.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
        try {
            mediaPlayer!!.setDataSource(url)
            mediaPlayer!!.prepare()
            mediaPlayer!!.start()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        mediaPlayer!!.setLooping(false)
        mediaPlayer!!.setOnPreparedListener(this);
        mediaPlayer!!.setOnCompletionListener(this);
        return START_STICKY
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onPrepared(p0: MediaPlayer?) {
        mediaPlayer!!.start()
        Log.i("***play", "play")
    }

    override fun onCompletion(p0: MediaPlayer?) {
        mediaPlayer!!.stop()
        Log.i("***play", "complete")
        stopSelf()
        /* mediaPlayer!!.release()

         mediaPlayer=null*/
    }

    override fun onError(p0: MediaPlayer?, p1: Int, p2: Int): Boolean {
        Log.i("***play", "error")
        return false
    }

    override fun onDestroy() {
        isServiceRunning = false
        objService = null
        super.onDestroy()
    }

    private fun adhanNotification(title: String, body: String) {
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val mBuilder = NotificationCompat.Builder(applicationContext, "notify_001")
        val collapsedView = RemoteViews(
            packageName,
            R.layout.notification
        )
        val expandView = RemoteViews(packageName, R.layout.notification_expand)

        val onCancelIntent = Intent(this, CancelNotification::class.java)
        val onDismissPendingIntent =
            PendingIntent.getService(this.applicationContext, 0, onCancelIntent, 0)

        val time = Utility.getTime("LLL dd, KK:mm aaa")
        collapsedView.setTextViewText(R.id.tvNotifyTime, time)
        collapsedView.setTextViewText(R.id.title, title)
        collapsedView.setTextViewText(R.id.body, body)
        expandView.setTextViewText(R.id.tvNotifyTime, time)
        expandView.setTextViewText(R.id.title, title)
        expandView.setTextViewText(R.id.body, body)
//        val switchIntent = Intent(this, BackgroundService.switchButtonListener::class.java)

        mBuilder.setSmallIcon(R.drawable.ic_notification)
        mBuilder.setDeleteIntent(onDismissPendingIntent)
        //mBuilder.setAutoCancel(true)
        mBuilder.setOngoing(false)
        /*    if (sound=="default")
                mBuilder.setSound(uri)
            else if (sound=="silent")
                mBuilder.setSilent(true)*/
        mBuilder.priority = Notification.PRIORITY_HIGH
//        mBuilder.setOnlyAlertOnce(false)
        mBuilder.build().flags = Notification.FLAG_NO_CLEAR or Notification.PRIORITY_HIGH
        //mBuilder.setCustomContentView(contentView)
        mBuilder.setCustomContentView(collapsedView)
        mBuilder.setCustomBigContentView(expandView)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "channel_id"
            val channel =
                NotificationChannel(channelId, "channel name", NotificationManager.IMPORTANCE_HIGH)
            channel.enableVibration(true)
            channel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
            notificationManager.createNotificationChannel(channel)
            mBuilder.setChannelId(channelId)
        }
        val random = (0 until 100).random()
        val notification = mBuilder.build()
        notificationManager.notify(random, notification)
    }

    companion object {
        var isServiceRunning = false
        var mediaPlayer: MediaPlayer? = null
    }
}

I want to start service to play mp3 url when push notification is received but when app in background or idle service doesn't start due to android restriction policy here is my code so doing with notification.
I am also using data payload its working fine app is in foreground but the problem is coming when app goes to background.

My FirebaseMessaging Class where staring the service

 val resultIntent = Intent(applicationContext, MusicService::class.java)
                        resultIntent.putExtra("title", title)
                        resultIntent.putExtra("body", body)
                        resultIntent.putExtra("action_type", action_type)
                        resultIntent.putExtra("deep_link_type", deep_link_type)
                        resultIntent.putExtra("deep_link_id", deep_link_id)
                        resultIntent.putExtra("masjid_Id", masjid_Id)
                        resultIntent.putExtra("url", url)
                        Log.i("***TAG", "From Background")
                        resultIntent.setAction("com.example.mymasjid");
//                        resultIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
                        startService(resultIntent) 


**My Music Service Class** 


class MusicService : Service(), MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener,
    MediaPlayer.OnErrorListener {

    var objService: MusicService? = null
    var title: String = ""
    var body: String = ""
//    private val mBinder: IBinder = LocalBinder()

    override fun onCreate() {
        super.onCreate()
//        if (title.isNotEmpty() && body.isNotEmpty())
            adhanNotification(title, body)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
//        val url = intent!!.getStringExtra("url")
         title = intent!!.getStringExtra("title").toString()
         body = intent!!.getStringExtra("body").toString()
//        if (title!!.isNotEmpty() && body!!.isNotEmpty())
            Log.i("***TAG","From Background Service")
            adhanNotification(title, body)
        val url = "https://cdn.islamic.network/quran/audio/64/ar.alafasy/9.mp3"
        if (mediaPlayer != null) {
            mediaPlayer!!.stop()
            mediaPlayer!!.release()
            mediaPlayer = null
        }
        mediaPlayer = MediaPlayer()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mediaPlayer!!.setAudioAttributes(
                AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .setLegacyStreamType(AudioManager.STREAM_MUSIC)
                    .build()
            );
        } else {
            mediaPlayer!!.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
        try {
            mediaPlayer!!.setDataSource(url)
            mediaPlayer!!.prepare()
            mediaPlayer!!.start()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        mediaPlayer!!.setLooping(false)
        mediaPlayer!!.setOnPreparedListener(this);
        mediaPlayer!!.setOnCompletionListener(this);
        return START_STICKY
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onPrepared(p0: MediaPlayer?) {
        mediaPlayer!!.start()
        Log.i("***play", "play")
    }

    override fun onCompletion(p0: MediaPlayer?) {
        mediaPlayer!!.stop()
        Log.i("***play", "complete")
        stopSelf()
        /* mediaPlayer!!.release()

         mediaPlayer=null*/
    }

    override fun onError(p0: MediaPlayer?, p1: Int, p2: Int): Boolean {
        Log.i("***play", "error")
        return false
    }

    override fun onDestroy() {
        isServiceRunning = false
        objService = null
        super.onDestroy()
    }

    private fun adhanNotification(title: String, body: String) {
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val mBuilder = NotificationCompat.Builder(applicationContext, "notify_001")
        val collapsedView = RemoteViews(
            packageName,
            R.layout.notification
        )
        val expandView = RemoteViews(packageName, R.layout.notification_expand)

        val onCancelIntent = Intent(this, CancelNotification::class.java)
        val onDismissPendingIntent =
            PendingIntent.getService(this.applicationContext, 0, onCancelIntent, 0)

        val time = Utility.getTime("LLL dd, KK:mm aaa")
        collapsedView.setTextViewText(R.id.tvNotifyTime, time)
        collapsedView.setTextViewText(R.id.title, title)
        collapsedView.setTextViewText(R.id.body, body)
        expandView.setTextViewText(R.id.tvNotifyTime, time)
        expandView.setTextViewText(R.id.title, title)
        expandView.setTextViewText(R.id.body, body)
//        val switchIntent = Intent(this, BackgroundService.switchButtonListener::class.java)

        mBuilder.setSmallIcon(R.drawable.ic_notification)
        mBuilder.setDeleteIntent(onDismissPendingIntent)
        //mBuilder.setAutoCancel(true)
        mBuilder.setOngoing(false)
        /*    if (sound=="default")
                mBuilder.setSound(uri)
            else if (sound=="silent")
                mBuilder.setSilent(true)*/
        mBuilder.priority = Notification.PRIORITY_HIGH
//        mBuilder.setOnlyAlertOnce(false)
        mBuilder.build().flags = Notification.FLAG_NO_CLEAR or Notification.PRIORITY_HIGH
        //mBuilder.setCustomContentView(contentView)
        mBuilder.setCustomContentView(collapsedView)
        mBuilder.setCustomBigContentView(expandView)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "channel_id"
            val channel =
                NotificationChannel(channelId, "channel name", NotificationManager.IMPORTANCE_HIGH)
            channel.enableVibration(true)
            channel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
            notificationManager.createNotificationChannel(channel)
            mBuilder.setChannelId(channelId)
        }
        val random = (0 until 100).random()
        val notification = mBuilder.build()
        notificationManager.notify(random, notification)
    }

    companion object {
        var isServiceRunning = false
        var mediaPlayer: MediaPlayer? = null
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文