从手机后台任务中删除应用程序后,音频不在后台播放

如何解决从手机后台任务中删除应用程序后,音频不在后台播放

从 RecyclerView 项目下载任何文件后,我使用后台服务通过 Intent 播放音频

退出应用后,音频在后台运行,但如果我从手机后台删除应用,应用就会崩溃。

请帮我一个忙并检查我的代码

AudioAdaptor.java


public class AudioAdapter extends RecyclerView.Adapter<AudioAdapter.AudioViewHolder> {

    Context context;
    List<Model> modelList;

    File mediaFile;
    String fileName;
    private static boolean isPlaying;

    public AudioAdapter(@NonNull Context context,List<Model> modelList) {
        this.context = context;
        this.modelList = modelList;
    }

    @NonNull
    @Override
    public AudioViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.audio_item,parent,false );
        return new AudioViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AudioViewHolder holder,int position) {

        holder.audio_title.setText(modelList.get(position).getAudio_title());
        holder.download.setBackgroundResource(ic_download_start);

        uri = Uri.parse(String.valueOf(modelList.get(position).getAudioFileName()));
        mediaFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),String.valueOf(uri));

        if (mediaFile.exists()){
            holder.download.setBackgroundResource(ic_bin);
        }

    }

    @Override
    public int getItemCount() {
        return modelList.size();
    }

public class AudioViewHolder extends RecyclerView.ViewHolder{

        TextView audio_title;
        Button play,stop,download;

        public AudioViewHolder(View itemView) {
            super(itemView);
            audio_title = (TextView) itemView.findViewById(R.id.tv_Audio_Title);
            play = (Button) itemView.findViewById(R.id.play);
            stop = (Button) itemView.findViewById(R.id.stop);
            download = (Button) itemView.findViewById(R.id.download);

            play.setonClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    int position = getAbsoluteAdapterPosition();
                    Model audioModel = modelList.get(position);
                    fileName = audioModel.getFileName();
                    Uri audioUri = Uri.parse(String.valueOf(fileName));
                    mediaFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),String.valueOf(audioUri));

                    if(mediaFile.exists()){
                        if (isPlaying){
                            Intent intent = new Intent(context,AudioService.class);
                            context.stopService(intent);
                            isPlaying = false;
                            stopStart();
                        }else{
                            Intent intent = new Intent(context,AudioService.class);
                            intent.putExtra("fileName",fileName);
                            context.startService(intent);
                            isPlaying = true;
                        }
                    }else {
                        Toast.makeText(context,"Audio file not found,plz download",Toast.LENGTH_LONG).show();
                    }

                }
            });

            stop.setonClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(context,AudioService.class);
                    context.stopService(intent);
                    isPlaying = false;

                }
            });
    }

    private void stopStart() {
        Intent intent = new Intent(context,AudioService.class);
        intent.putExtra("fileName",fileName);
        context.startService(intent);
        isPlaying = true;
    }

}




AudioService.java


public class AudioService extends Service {
    MediaPlayer mediaPlayer;
    String playAudio;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(@NonNull Intent intent,int flags,int startId) {
        
        playAudio = intent.getStringExtra("fileName");
        Uri audioUri = Uri.parse(String.valueOf(playAudio));
        File mediaFile = new File(this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),String.valueOf(audioUri));
        mediaPlayer = new MediaPlayer();

        try {
                mediaPlayer.setDataSource(String.valueOf(mediaFile));
                mediaPlayer.prepare();
                mediaPlayer.start();

        } catch (IOException e) {
            e.printstacktrace();
        }

        return super.onStartCommand(intent,flags,startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mediaPlayer.stop();
        mediaPlayer.release();
    }

    @Override
    public IBinder onBind(@NonNull Intent intent) {
        // Todo: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}



AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.audioplayer">

    
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <service
            android:name=".AudioService"
            android:enabled="true"
            android:exported="false" />
    </application>

</manifest>


从手机后台删除应用程序后的崩溃报告。

java.lang.NullPointerException 尝试在空对象引用上调用虚拟方法 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)'

提前致谢。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?