当应用在后台运行时,我正在使用服务来播放广播。我的应用包含4个广播频道。所以我使用了一个viewpager。当我慢慢滑动时,我的应用程序响应正常。但是,当我快速滑动时,我的应用程序没有响应&我正在进行ANR对话。根据文档,服务作为单独的线程运行。所以它不应该阻止我的应用程序。但为了更安全,我在异步任务中添加了服务。但仍然是同样的问题。我在Nexus 5设备上测试过它。但是当我在模拟器(Nexus 5-Lollipop)上运行应用程序时。它完美地运作。那可能是什么问题?是否有人面临类似的问题。 这就是我开始服务的方式:
private void playRadio() {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
if (getUserVisibleHint()) {
if (PreferencesManager.getInstance(getActivity()).isLiveRadioPlaying())
stopRadio();
Log.d("Visible", "");
Intent intent = new Intent(getActivity(), LiveRadioService.class);
intent.setAction(ACTION_START);
intent.putExtra(RADIO_URL, mRadioUrl);
intent.putExtra(RADIO_TITLE, mSectionTitle);
intent.putExtra(LIVE_RADIO_SECTION_POSITION, mSectionPos);
getActivity().startService(intent);
}
return null;
}
}.execute();
}
Preparing the media player inside asynctask:
private void playRadio() {
new AsyncTask<Void,Void,Void>(){
@Override
protected Void doInBackground(Void... voids) {
try {
cancelNotification();
mMediaPlayer.stop();
mMediaPlayer.reset();
mMediaPlayer.setDataSource(mUrl);
mMediaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
答案 0 :(得分:0)
根据文档,服务作为单独的线程运行。
不正确
因为Service始终在Application的同一进程中运行,但IntentService使用工作线程来处理收到的Intents。
我正在接受ANR对话
可能服务在主线程上执行一些与网络相关的工作或Api调用。
要防止ANR对话框启动单独的线程或使用AsyncTask,IntentService
在服务中执行密集或阻止操作