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();
}
}

您可以将服务设置为前台服务,这将在通知栏中显示一个图标,以便用户可以查看您的服务正在运行。

否则,您无法保持服务运行。

顺便说一下,你应该知道一个永恒的服务是一个Android反模式,系统应该能够在内存不足时杀死你的应用程序,并且应用程序有一段时间没有使用它了。

如果您正在做一些合法需要"永远"生活的事情,您应该使用前台服务。

阅读此内容以获取更多信息:

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

有点晚了,但有人可能会发现它很有帮助。

为了防止服务被杀死,您需要获取唤醒锁。

[Service]
internal class NotificationService : Service
{
readonly PowerManager.WakeLock _wakeLock;
public NotificationService()
{
PowerManager powerManager = Android.App.Application.Context.GetSystemService(Context.PowerService) as PowerManager;
_wakeLock = powerManager.NewWakeLock(WakeLockFlags.Partial, "ServiceWakeLock");
}
public override void OnCreate()
{
base.OnCreate();
_wakeLock?.Acquire();
}
public override void OnDestroy()
{
_wakeLock?.Release();
base.OnDestroy();
}
}

相关内容

  • 没有找到相关文章

最新更新