将音频记录为Android服务并使用计时器停止。录制长度不同,服务似乎无法停止。

3

我最近(几天前)开始学习JAVA,所以我相信我在犯一些基本错误。我创建了一个活动,通过按钮启动记录音频的服务。我加入了一个计时器来停止录音,并通过stopself()退出服务,希望这是正确关闭的方式。

但是,当我运行应用程序时,它会为录制期间(我将其设置为90分钟)生成多个音频文件,并且它们被无理地裁剪掉(其中一些是30分钟,一些是20分钟等),有时服务似乎也无法停止。

我的服务类:

@SuppressLint("SimpleDateFormat")
 public class myservice extends Service {
     private MediaRecorder myRecorder;
       private String outputFile = null;
        public IBinder onBind(Intent arg0) {
            return null;
        }
        @Override
        public void onCreate() {
           // super.onCreate();  (not sure about this one)

            SimpleDateFormat s = new SimpleDateFormat("ddMMyyyy_hhmmss");
            String format = s.format(new Date());

            outputFile = Environment.getExternalStorageDirectory().
                  getAbsolutePath() +  "/" + format + ".3gpp";

            myRecorder = new MediaRecorder();
            myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
            myRecorder.setOutputFile(outputFile);

               try {
                  myRecorder.prepare();
                  myRecorder.start();
               } catch (IllegalStateException e) {
                  // start:it is called before prepare()
                  // prepare: it is called after start() or before setOutputFormat() 
                  e.printStackTrace();
               } catch (IOException e) {
                   // prepare() fails
                   e.printStackTrace();
                }

            Timer myTimer;

            myTimer = new Timer();
            myTimer.schedule(new TimerTask() {          
                @Override
                public void run() {

        try {
                          myRecorder.stop();
                          myRecorder.reset();
                          myRecorder.release();
                          myRecorder = null;

                          stopSelf();
                          //onDestroy();  I added this one to test it out. not sure.

                       } catch (IllegalStateException e) {
                            //  it is called before start()
                            e.printStackTrace();
                       } catch (RuntimeException e) {
                            // no valid audio/video data has been received
                            e.printStackTrace();
                       }
                    }

            }, 60000 * 90); //90 minutes timer to stop the recording after 90 minutes

            }

        public int onStartCommand(Intent intent, int flags, int startId) {
            //onCreate();  
           // return 1;
            return START_STICKY; //not sure about this one
        }

        public void onStart(Intent intent, int startId) {
            // TO DO
        }
        public IBinder onUnBind(Intent arg0) {
            // TO DO Auto-generated method
            return null;
        }

        public void onStop() {

        }
        public void onPause() {

        }
//what about this one ?
       // @Override
       // public void onDestroy() {
//  myRecorder.stop();
//  myRecorder.reset();
//  myRecorder.release();
      //}

    }

我的主要活动:

public class MainActivity extends Activity {

       private Button startBtn;


   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);


      startBtn = (Button)findViewById(R.id.start);
      startBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent svc=new Intent(getBaseContext(), myservice.class);
            startService(svc);


            finish(); //because I want to close the UI after service started
        }
      });

   }

}

在使用安卓服务之前,我使用线程编写了这个应用。它能工作,但计时器只能工作很短的时间,10分钟或更少。录音在某些时刻停止(通常为30分钟或更短),而且这个长度是不固定的(尽管计时器被设置为90分钟)。我仍然不知道原因,但我认为安卓操作系统会由于资源不足而关闭线程。非常感谢您提供帮助。
1个回答

4

既然我已经解决了这个问题,我将发布我的解决方案,以便其他人遇到类似的问题时可以参考。显然,在Android操作系统中,服务(在大约30分钟没有交互的情况下)也可能被关闭。我需要的是一个前台服务。以下是官方文档中的示例:

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接