android - 如何完成后台播放录音的任务并处理不同的 Activity ?

标签 android service background recording

我对 Android 开发有点陌生,我遇到过一个场景,希望得到专家的宝贵反馈。

在我的应用程序中,用户位于 Activity1,用户从中选择客户端并导航到 Activity2。在 Activity2 上,用户应能够播放录音文件,在播放录音时,用户可以导航到 Activity3、Activity4 或 Activity5,收听音频并进行输入。在 Activity3、Activity4 和 Activity5 上,用户将可以控制暂停或停止音频。 如果用户从 Activity2 导航回 Activity1,音频将自动停止。

我很困惑它可以通过服务或后台任务来完成。

非常感谢任何有值(value)的建议/代码示例。

最佳答案

我肯定会使用 service 。您可以绑定(bind)到服务并从中调用方法。

Intent it = new Intent(MainActivity.this, MyService.class);
bindService(it, mConnection, Context.BIND_AUTO_CREATE);

绑定(bind)到每个 Activity 中的服务,这样您就可以用它做任何您想做的事情。 不要忘记在您的 Activity 中取消绑定(bind)其“onDestroy”。

if(mBound)unbindService(mConnection);

只需停止服务即可停止播放。

stopService(new Intent(this, MyService.class));

这是我使用的serviceConnection。

private ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className,IBinder service) {
        // We've bound to LocalService, cast the IBinder and get LocalService instance
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;            
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        mBound = false;
    }
}; 

将其放入您的服务中以返回到 Activity :

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

public class LocalBinder extends Binder {
    MyService getService() {
        // Return this instance of LocalService so clients can call public methods
        return MyService.this;
    }
}

最后,这将在启动服务后调用 startService(intent); 请注意,它返回 Service.START_STICKY。这将防止您的服务被终止,除非操作系统内存很少。

public int onStartCommand(Intent intent, int flags, int startid) {      
    return Service.START_STICKY;
}

希望我的回答对您有所帮助,祝您好运。

关于android - 如何完成后台播放录音的任务并处理不同的 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21000095/

相关文章:

android - Retrofit ssl=0x717f870208 : I/O error during system call, 连接被对端重置

Android:单击 TextView 中的特定单词时显示弹出对话框

java - 为什么 View 的操作(在本例中为按钮)必须采用 View 作为参数?

windows - 如何在 WiX 安装程序中更改 Windows 服务启动类型

c# - DDD 动态服务注入(inject)

css - 正文宽度为页面而非屏幕的 100%

java - 膨胀 fragment 时发现类未找到异常

windows - 有没有办法监视 Windows 服务并在它挂起/停止时提醒人们?

c - GTK_WINDOW_TOPLEVEL Gtk Widget 的背景颜色

html - 在 CSS 中设置图像周围的背景