2727import java .io .FileDescriptor ;
2828import java .io .FileInputStream ;
2929import java .io .IOException ;
30- import java .util .List ;
31- import java .util .concurrent .Executors ;
30+ import java .util .concurrent .Future ;
3231import java .util .concurrent .LinkedBlockingQueue ;
3332import java .util .concurrent .ThreadFactory ;
3433import java .util .concurrent .ThreadPoolExecutor ;
@@ -38,9 +37,11 @@ public class MediaTranscoder {
3837 private static final String TAG = "MediaTranscoder" ;
3938 private static final int MAXIMUM_THREAD = 1 ; // TODO
4039 private static volatile MediaTranscoder sMediaTranscoder ;
40+ private Future mFuture ;
4141 private ThreadPoolExecutor mExecutor ;
4242
4343 private MediaTranscoder () {
44+ mFuture = null ;
4445 mExecutor = new ThreadPoolExecutor (
4546 0 , MAXIMUM_THREAD , 60 , TimeUnit .SECONDS ,
4647 new LinkedBlockingQueue <Runnable >(),
@@ -161,8 +162,7 @@ public void transcodeVideo(final FileDescriptor inFileDescriptor, final String o
161162 Looper looper = Looper .myLooper ();
162163 if (looper == null ) looper = Looper .getMainLooper ();
163164 final Handler handler = new Handler (looper );
164- if (mExecutor .isShutdown ()) mExecutor = (ThreadPoolExecutor ) Executors .newCachedThreadPool ();
165- mExecutor .execute (new Runnable () {
165+ mFuture = mExecutor .submit (new Runnable () {
166166 @ Override
167167 public void run () {
168168 Exception caughtException = null ;
@@ -185,10 +185,11 @@ public void run() {
185185 Log .w (TAG , "Transcode failed: input file (fd: " + inFileDescriptor .toString () + ") not found"
186186 + " or could not open output file ('" + outPath + "') ." , e );
187187 caughtException = e ;
188+ } catch (InterruptedException e ) {
189+ Log .i (TAG , "Cancel transcode video file." , e );
190+ caughtException = e ;
188191 } catch (RuntimeException e ) {
189- if (!(e .getCause () instanceof InterruptedException )) {
190- Log .e (TAG , "Fatal error while transcoding, this might be invalid format or bug in engine or Android." , e );
191- }
192+ Log .e (TAG , "Fatal error while transcoding, this might be invalid format or bug in engine or Android." , e );
192193 caughtException = e ;
193194 }
194195
@@ -199,7 +200,7 @@ public void run() {
199200 if (exception == null ) {
200201 listener .onTranscodeCompleted ();
201202 } else {
202- if (exception . getCause () instanceof InterruptedException ) {
203+ if (exception instanceof InterruptedException ) {
203204 listener .onTranscodeCanceled ();
204205 } else {
205206 listener .onTranscodeFailed (exception );
@@ -211,8 +212,11 @@ public void run() {
211212 });
212213 }
213214
214- public List <Runnable > cancel () {
215- return mExecutor .shutdownNow ();
215+ /**
216+ * Cancel transcode video file
217+ */
218+ public boolean cancel () {
219+ return mFuture != null ? mFuture .cancel (true ) : false ;
216220 }
217221
218222 public interface Listener {
0 commit comments