如何在android中停止命令行进程

时间:2016-01-15 11:06:48

标签: android process termination

请帮助我,我必须在我的应用程序中使用ffmpeg cmdline。我构建了ffmpeg二进制文件,现在我可以按如下方式开始使用ffmpeg了:

public class FfmpegCmd {
...
   public ProcessRunnable create(){
     final List<String> cmd = new LinkedList<String>();

     ... // filling ffmpeg parameters

     final ProcessBuilder pb = new ProcessBuilder(cmd);
     return new ProcessRunnable(pb);
}
...
}

我开始ffmpeg转换如下:

final FfmpegCmd task = new FfmpegCmd();

new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... arg0) {
                task.create().run();
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {                 
                Toast.makeText(MainActivity.this, "Ffmpeg cmd complete.", Toast.LENGTH_SHORT).show();
            }

        }.execute();

工作正常。但我想添加终止ffmpeg命令执行的能力。我怎样才能做到这一点?如何终止ProcessRunnable?

我需要“将CTRL + C发送到ProcessRunnable”

1 个答案:

答案 0 :(得分:1)

按如下方式解决:

Process ffmpeg = Runtime.getRuntime().exec(mFfmpegInstallPath + " -y -i
rtsp://192.168.1.254/xxx.mov -b 2M -vcodec mpeg4 /sdcard/video.avi\n");

...

private void kill_ffmpeg(){
    Log.d("output: ",ffmpeg.toString());

    /* define PID */
    try {
        String pid = ffmpeg.toString();
        pid = pid.substring(pid.indexOf("[") + 1, pid.indexOf("]"));
        Process process = Runtime.getRuntime().exec("kill -2 " + pid);

        process.waitFor();
        ffmpeg.waitFor();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}