首页 > 解决方案 > 从手机后台任务中删除应用程序后,音频不在后台播放

问题描述

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

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

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

音频适配器.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;
    }

}




音频服务.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)”

提前致谢。

标签: android-recyclerviewmedia-playerintentservicebackground-service

解决方案


推荐阅读