Фоновая служба Android останавливается после блокировки экрана мобильного устройства через несколько минут - PullRequest
0 голосов
/ 17 октября 2019

Я пытался внедрить приложение для потокового радио онлайн, но через несколько минут после блокировки экрана оно остановилось, помогите мне решить эту проблему.

Мой мобильный телефон - Android 9

public class AudioService extends Service {


    private AudioServiceBinder audioServiceBinder = new AudioServiceBinder();

    public AudioService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return audioServiceBinder;
    }


}

public class AudioServiceBinder extends Binder {

    // Save local audio file uri ( local storage file. ).
    private Uri audioFileUri = null;

    // Save web audio file url.
    private String audioFileUrl = "https://www.radiantmediaplayer.com/media/bbb-360p.mp4";

    // Check if stream audio.
    private boolean streamAudio = true;

    // Media player that play audio.
    private MediaPlayer audioPlayer = null;

    // Caller activity context, used when play local audio file.
    private Context context = null;

    // This Handler object is a reference to the caller activity's Handler.
    // In the caller activity's handler, it will update the audio play progress.
    private Handler audioProgressUpdateHandler;

    // This is the message signal that inform audio progress updater to update audio progress.
    public final int UPDATE_AUDIO_PROGRESS_BAR = 1;

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public String getAudioFileUrl() {
        return audioFileUrl;
    }

    public void setAudioFileUrl(String audioFileUrl) {
        this.audioFileUrl = audioFileUrl;
    }

    public boolean isStreamAudio() {
        return streamAudio;
    }

    public void setStreamAudio(boolean streamAudio) {
        this.streamAudio = streamAudio;
    }

    public Uri getAudioFileUri() {
        return audioFileUri;
    }

    public void setAudioFileUri(Uri audioFileUri) {
        this.audioFileUri = audioFileUri;
    }

    public Handler getAudioProgressUpdateHandler() {
        return audioProgressUpdateHandler;
    }

    public void setAudioProgressUpdateHandler(Handler audioProgressUpdateHandler) {
        this.audioProgressUpdateHandler = audioProgressUpdateHandler;
    }

    // Start play audio.
    public void startAudio()
    {
        initAudioPlayer();
        if(audioPlayer!=null) {
            audioPlayer.start();
//            ProgressUtils.dismissProgress();
        }
    }



    // Stop play audio.
    public void stopAudio()
    {
        if(audioPlayer!=null) {
            audioPlayer.stop();
            destroyAudioPlayer();
        }
    }

    // Initialise audio player.
    private void initAudioPlayer()
    {
        try {
            if (audioPlayer == null) {
                audioPlayer = new MediaPlayer();

                if (!TextUtils.isEmpty(getAudioFileUrl())) {
                    if (isStreamAudio()) {
                        audioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    }
                    audioPlayer.setDataSource(getAudioFileUrl());
                } else {
                    audioPlayer.setDataSource(getContext(), getAudioFileUri());
                }

                audioPlayer.prepare();


            }
        }catch(IOException ex)
        {
            ex.printStackTrace();
        }
    }

    // Destroy audio player.
    private void destroyAudioPlayer()
    {
        if(audioPlayer!=null)
        {
            if(audioPlayer.isPlaying())
            {
                audioPlayer.stop();
            }

            audioPlayer.release();

            audioPlayer = null;
        }
    }

}

Я попытался реализовать приложение для потокового радио в Интернете, но оно остановилось, когда блокировка экрана через несколько минут помогла мне решить эту проблему.

public class MainActivity extends Activity {

    // User input mp3 file url in this text box. Or display user selected mp3 file name.
    private static String audioFileUrl = "https://www.radiantmediaplayer.com/media/bbb-360p.mp4";


    private AudioServiceBinder audioServiceBinder = null;

    private Handler audioProgressUpdateHandler = null;

    // Show played audio progress.
//    private ProgressBar backgroundAudioProgress;

    ImageView startBackgroundAudio;
    ImageView stopBackgroundAudio;


    // This service connection object is the bridge between activity and background service.
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
              iBander object.
            audioServiceBinder = (AudioServiceBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        // Bind background audio service when activity is created.


        bindAudioService();

        // Click this button to start play audio in a background service.
        startBackgroundAudio = findViewById(R.id.start_audio_in_background);
        stopBackgroundAudio = findViewById(R.id.stop_audio_in_background);
        startBackgroundAudio.post(() -> {


            startBackgroundAudio.setOnClickListener(view -> {

                new PrograssAsyncTask(this).execute();


                startBackgroundAudio.setVisibility(View.GONE);
                stopBackgroundAudio.setVisibility(View.VISIBLE);
//                ProgressUtils.showProgress(MainActivity.this);
                // Set web audio file url
                audioServiceBinder.setAudioFileUrl(audioFileUrl);

                // Web audio is a stream audio.
                audioServiceBinder.setStreamAudio(true);

                // Set application context.
                audioServiceBinder.setContext(getApplicationContext());

                // Initialize audio progress bar updater Handler object.
//            createAudioProgressbarUpdater();
                audioServiceBinder.setAudioProgressUpdateHandler(audioProgressUpdateHandler);

                // Start audio in background service.
                audioServiceBinder.startAudio();

            });
        });


        stopBackgroundAudio.post(() -> {
            stopBackgroundAudio.setOnClickListener(view -> {
                startBackgroundAudio.setVisibility(View.VISIBLE);
                stopBackgroundAudio.setVisibility(View.GONE);
                audioServiceBinder.stopAudio();
                abc.stopAudio();
            });
        });

//        ProgressUtils.showProgress(MainActivity.this);


        Handler handler = new Handler();
        handler.post(() -> {
            autoPlay();
        });



    }

    AudioServiceBinder abc;

    private void autoPlay() {
        Intent intent = new Intent("com.android.ServiceStopped");
        sendBroadcast(intent);
        abc = new AudioServiceBinder();
        abc.setContext(getApplicationContext());
        abc.setAudioProgressUpdateHandler(audioProgressUpdateHandler);
        abc.startAudio();
    }

    // Bind background service with caller activity. Then this activity can use
    // background service's AudioServiceBinder instance to invoke related methods.
    private void bindAudioService() {
        if (audioServiceBinder == null) {
            Intent intent = new Intent(MainActivity.this, AudioService.class);
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            @SuppressLint("InvalidWakeLockTag")
            PowerManager.WakeLock screenWakeLock = pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK  | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                    "ScreenLock tag from AlarmListener");
            screenWakeLock.acquire();
            // Below code will invoke serviceConnection's onServiceConnected method.
            bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
            screenWakeLock.release();

        }
    }

    // Unbound background audio service with caller activity.
    private void unBoundAudioService() {
        if (audioServiceBinder != null) {
            unbindService(serviceConnection);
        }
    }

    @Override
    protected void onDestroy() {
        // Unbound background audio service when activity is destroyed.
        unBoundAudioService();
        super.onDestroy();
    }

    private class PrograssAsyncTask extends AsyncTask<Void, Void, Void> {
        private ProgressDialog dialog;

        public PrograssAsyncTask(MainActivity activity) {
            dialog = new ProgressDialog(activity);
        }

        @Override
        protected void onPreExecute() {
            dialog.setMessage("Please wait......");
            dialog.show();
        }

        @Override
        protected Void doInBackground(Void... args) {
            // do background work here
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // do UI work here
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
//        autoPlay();
    }
}

1 Ответ

0 голосов
/ 17 октября 2019

Вы можете сделать свой сервис приоритетным, который будет отображать значок в панели уведомлений, чтобы пользователь мог видеть, что ваш сервис запущен.

В противном случае вы не сможете поддерживать работоспособность своего сервиса.

Кстати, вы должны знать, что вечный сервис является антипаттерном Android, и система должна иметь возможностьубить ваше приложение, когда памяти мало, и приложения давно его не использовали.

Если вы делаете что-то, что на законных основаниях необходимо для того, чтобы жить «вечно», вам следует делать это с помощью службы переднего плана.

Прочтите это для получения дополнительной информации:

http://developer.android.com/guide/components/services.html#Foreground

...