服务永远不会真正开始

问题描述 投票:0回答:1

我正在使用一个录音应用程序,并且我们有一个RecordingFragment试图启动一个录音服务。可悲的是它从未真正运行过。我尝试将一些日志放到Create和其他方法上,但未调用它们。

我也是android的新手,我认为startService()就像启动一个新线程。所以它至少应该创建它而不考虑其他错误,对吗?

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

    <uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

    <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=".Activities.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name="Services.RecordingService"
            android:enabled="true"></service>
    </application>

</manifest>
package com.example.voicerecorder.Fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.voicerecorder.R;
import com.example.voicerecorder.Services.RecordingService;
import com.melnykov.fab.FloatingActionButton;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RecordFragment extends Fragment {

    @BindView(R.id.chronometer) Chronometer chronometer;
    @BindView(R.id.recording_status_txt) TextView recordingStatusTxt;
    @BindView(R.id.btnRecord) FloatingActionButton recordBtn;
    @BindView(R.id.btnPause) Button btnPause;

    private boolean mStartRecording = true;
    private boolean mPauseRecording = true; //TODO
    long timeWhenPaused = 0;

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

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View recordView = inflater.inflate(R.layout.fragment_record,container, false);
        ButterKnife.bind(this,recordView);
        return recordView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        btnPause.setVisibility(View.GONE);
        recordBtn.setColorPressed(getResources().getColor(R.color.colorPrimary));
    }

    @OnClick(R.id.btnRecord)
    public void recordAudio() {
        onRecord(mStartRecording);
        mStartRecording = !mStartRecording; //TODO
    }

    private void onRecord(boolean start) {
        Intent intent = new Intent(getActivity(), RecordingService.class);

        if (start) {
            recordBtn.setImageResource(R.drawable.ic_media_stop);
            Toast.makeText(getContext(), "Recording started", Toast.LENGTH_LONG).show();

            File folder = new File(Environment.getExternalStorageDirectory()+ "MySoundRec"); //TODO

            if(!folder.exists()) {
                folder.mkdir();
            }

            chronometer.setBase(SystemClock.elapsedRealtime());
            chronometer.start();

            getActivity().startService(intent);
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

            recordingStatusTxt.setText("Recording...");
        }

        else {
            recordBtn.setImageResource(R.drawable.ic_mic_white);
            Toast.makeText(getContext(), "Recording finished ", Toast.LENGTH_LONG).show();
            chronometer.stop();
            chronometer.setBase(SystemClock.elapsedRealtime());
            timeWhenPaused = 0;
            recordingStatusTxt.setText("Tap the button to start recording");

            getActivity().stopService(intent);
        }
    }
}
package com.example.voicerecorder.Services;

import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.example.voicerecorder.Database.DBHelper;
import com.example.voicerecorder.Models.RecordingItem;

import java.io.File;
import java.io.IOException;

public class RecordingService extends Service {

    MediaRecorder mediaRecorder;
    long mStartingTimeMillis = 0;
    long mElapsedMillis = 0;

    File file;

    String fileName;

    DBHelper dbhelper;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("maaan","teeeeeest");
        dbhelper = new DBHelper((getApplicationContext()));
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startRecording();
        return START_STICKY;
    }

    private void startRecording() {
        Long tsLong = System.currentTimeMillis()/1000;
        String ts = tsLong.toString();

        fileName = "audio_"+ts;

        file = new File(Environment.getExternalStorageDirectory() + "/MySoundRec"+fileName+".mp3");

        mediaRecorder = new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mediaRecorder.setOutputFile(file.getAbsolutePath());
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        mediaRecorder.setAudioChannels(1);

        try {
            mediaRecorder.prepare();
            mediaRecorder.start();

            mStartingTimeMillis = System.currentTimeMillis();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopRecording() {
        mediaRecorder.stop();
        mElapsedMillis = System.currentTimeMillis() - mStartingTimeMillis;
        mediaRecorder.release();
        Toast.makeText(getApplicationContext(), "Recording saved"+file.getAbsolutePath(), Toast.LENGTH_LONG).show();

        RecordingItem recordingItem = new RecordingItem(fileName, file.getAbsolutePath(),mElapsedMillis,System.currentTimeMillis());

        dbhelper.addRecording(recordingItem);
    }

    @Override
    public void onDestroy() {
        if (mediaRecorder!=null) {
            stopRecording();
        }
        super.onDestroy();
    }
}
android service
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.