所以我一直在尝试构建音乐播放器应用,尽管访问了stackoverflow上的所有页面,但我仍然停留在一个问题上。该代码在大多数情况下都可以正常运行,但是当我按下后退按钮以关闭应用程序时,动作按钮将停止工作,即使在按下主屏幕按钮时它们也可以正常工作。我认为即使我不希望关闭应用程序,广播接收器也会被注销。这是代码:
public BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getExtras().getString("actionname");
Helper.makeToast(context, action);
switch (action) {
case CreateNotification.ACTION_PREVIUOS:
//play previous
case CreateNotification.ACTION_PLAY:
if (isPlaying) {
//pause
} else {
// play
}
break;
case CreateNotification.ACTION_NEXT:
//play next
}
}
};
这是主要活动的onresume方法
@Override
protected void onResume() {
super.onResume();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
registerReceiver(broadcastReceiver, new IntentFilter("TRACKS_TRACKS"));
startService(new Intent(getBaseContext(), OnClearFromRecentService.class));
}
}
这是服务
public class OnClearFromRecentService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY_COMPATIBILITY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
stopSelf();
}
}
清单中:
<receiver .services.OnClearFromRecentService" />
所以我的问题是:关闭应用程序后,广播接收器会自动注销吗?如果是这样,我该如何防止呢?关闭应用程序后如何使广播接收器正常工作?
当您关闭应用程序时,此类接收器会自动注销。这是正确的。但是,您必须在onStop()中从接收器中注销。因为如果不这样做,您将在LogCat中收到LeakIntentMemory错误消息,但您的应用程序不会崩溃。您可以从logcat检查它。我认为,如果您想在应用关闭时收到一些信息,则必须在AndroidManifest中用动作名称声明接收者。
<receiver android:name=".YourReceiver" >
<intent-filter>
<action android:name="first.custom.action"> </action>
</intent-filter>
</receiver>