Method loadVideoFromAsset must be called from UI thread - android

I am trying to implement 360 Video Viewer in my project but I am getting an error for the line:
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
This is the error
Method loadVideoFromAsset must be called from the UI thread, currently inferred
thread is worker
Following is my code:
package com.example.jal.jp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import com.google.vr.sdk.widgets.video.VrVideoEventListener;
import com.google.vr.sdk.widgets.video.VrVideoView;
import java.io.IOException;
public abstract class VR_Video extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private VrVideoView mVrVideoView;
private SeekBar mSeekBar;
private Button mVolumeButton;
private boolean mIsPaused;
private boolean mIsMuted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vr__video);
initViews();
}
public void onPlayPausePressed() {
}
public void onVolumeToggleClicked() {
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
private void initViews() {
mVrVideoView = (VrVideoView) findViewById(R.id.video_view);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
mVolumeButton = (Button) findViewById(R.id.btn_volume);
mVrVideoView.setEventListener(new ActivityEventListener());
mSeekBar.setOnSeekBarChangeListener(this);
mVolumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVolumeToggleClicked();
}
});
}
class VideoLoaderTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
try {
VrVideoView.Options options = new VrVideoView.Options();
options.inputType = VrVideoView.Options.TYPE_MONO;
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
} catch( IOException e ) {
//Handle exception
}
return true;
}
}
public void playPause() {
}
#Override
protected void onPause() {
super.onPause();
mVrVideoView.pauseRendering();
mIsPaused = true;
}
#Override
protected void onResume() {
super.onResume();
mVrVideoView.resumeRendering();
mIsPaused = false;
}
#Override
protected void onDestroy() {
mVrVideoView.shutdown();
super.onDestroy();
}
private class ActivityEventListener extends VrVideoEventListener {
#Override
public void onLoadSuccess() {
super.onLoadSuccess();
}
#Override
public void onLoadError(String errorMessage) {
super.onLoadError(errorMessage);
}
#Override
public void onClick() {
super.onClick();
}
#Override
public void onNewFrame() {
super.onNewFrame();
}
#Override
public void onCompletion() {
super.onCompletion();
}
}
}
Please help. I tried my best but couldn't fix.

Remove AsyncTask Implementation And Call Required Methods From UI Thread
Use Below Code :
private void initViews() {
mVrVideoView = (VrVideoView) findViewById(R.id.video_view);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
mVolumeButton = (Button) findViewById(R.id.btn_volume);
mVrVideoView.setEventListener(new ActivityEventListener());
try {
VrVideoView.Options options = new VrVideoView.Options();
options.inputType = VrVideoView.Options.TYPE_MONO;
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
} catch( IOException e ) {
//Handle exception
}
mSeekBar.setOnSeekBarChangeListener(this);
mVolumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVolumeToggleClicked();
}
});
}

I dont know much about videoview but I show in your code that you are trying to access some the features in doInbackground method. The doINbackground method runs on a separate thread from the UI thread so that complex ant time consuming tasks do not block the UI thread. You can implement the features you are implementing in doINbackground method in the onCreate method or if you still need to use doInbackground you can access the UI thread inside doInbackground using runOnUiThread as follows
runOnUiThread(new Runnable() {
#Override
public void run() {
//your code here
}
});

Related

Message is not dispatched into the thread in android

As part of my learning Android Threading, I have done the below code.
package simple.learning.com.samplethread;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
MyThread myThread;
Button button;
private static class MyThread extends Thread {
public Handler mHandler;
public void run () {
Log.d ("TESTME", " iNSIDE RUN..");
Looper.prepare();
mHandler = new Handler () {
public void HandleMessage (Message msg) {
Log.d("TESTME", "iNSIDE HandleMessage");
if ( msg.what == 0) {
someWork();
}
}
};
Looper.loop();
}
public void someWork()
{
while (true) {
Log.d("TESTME", "Inside someWork ");
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myThread = new MyThread();
myThread.start();
Button btn = (Button) findViewById(R.id.button1);
assert btn != null;
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (myThread.mHandler != null) {
Log.d("TESTME", " bUTTON pRESSED..");
Message msg = myThread.mHandler.obtainMessage(0);
myThread.mHandler.sendMessage(msg);
}
}
});
}
}
When I Click the button, I expect the msg to be posted into the message queue. But, I don't see any output displayed. Any help would be appreciated.
You made a small mistake in overriding the handleMessage, instead of overriding the real one you added some method. Below is the working solution:
private static class MyThread extends Thread {
public Handler mHandler;
public void run() {
Log.d("TESTME", " iNSIDE RUN..");
Looper.prepare();
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.d("TESTME", "iNSIDE HandleMessage");
if (msg.what == 0) {
someWork();
}
}
};
Looper.loop();
}
public void someWork() {
while (true) {
Log.d("TESTME", "Inside someWork ");
}
}
}

How to set the library in android studio

I am trying to set a waveInApp library http://www.materialup.com/posts/waveinapp
I have declared all the required thing .The app
working but the background wave is not working .I am not able to set the wave function as a beginner in android development .
I am able to set the all the basic things including the media player.
Here I am not able to set the speech recognization handler
Here is what I have done
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import com.cleveroad.audiovisualization.AudioVisualization;
import com.cleveroad.audiovisualization.DbmHandler;
import com.cleveroad.audiovisualization.SpeechRecognizerDbmHandler;
import com.cleveroad.audiovisualization.VisualizerDbmHandler;
public class MainActivity extends AppCompatActivity {
private AudioVisualization audioVisualization;
private Context context;
private ImageButton button1,button2;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audioVisualization = (AudioVisualization)findViewById(R.id.visualizer_view);
button1=(ImageButton)findViewById(R.id.imageButton);
button2=(ImageButton)findViewById(R.id.imageButton2);
mediaPlayer =MediaPlayer.create(this,R.raw.song);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"playing",Toast.LENGTH_SHORT).show();
mediaPlayer.start();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"pause",Toast.LENGTH_SHORT).show();
mediaPlayer.pause();
VisualizerDbmHandler vizualizerHandler = DbmHandler.Factory.newVisualizerHandler(getContext(), 0);
audioVisualization.linkTo(vizualizerHandler);
// set speech recognizer handler
SpeechRecognizerDbmHandler speechRecHandler = DbmHandler.Factory.newSpeechRecognizerHandler(context);
speechRecHandler.innerRecognitionListener(...);
audioVisualization.linkTo(speechRecHandler);
}
});
}
#Override
public void onResume() {
super.onResume();
audioVisualization.onResume();
}
#Override
public void onPause() {
audioVisualization.onPause();
super.onPause();
}
}
So how to set the above handeler. I am not able to set the connect audio visualization view to audio output . How to set the following method with the media player
// set speech recognizer handler
SpeechRecognizerDbmHandler speechRecHandler = DbmHandler.Factory.newSpeechRecognizerHandler(context);
speechRecHandler.innerRecognitionListener(...);
audioVisualization.linkTo(speechRecHandler);
// set audio visualization handler. This will REPLACE previously set speech recognizer handler
VisualizerDbmHandler vizualizerHandler = DbmHandler.Factory.newVisualizerHandler(getContext(), 0);
audioVisualization.linkTo(vizualizerHandler);
Except this all are working.any hint or advice will be helpfull.
I tried to search
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.cleveroad.audiovisualization.AudioVisualization;
import com.cleveroad.audiovisualization.DbmHandler;
import com.cleveroad.audiovisualization.SpeechRecognizerDbmHandler;
public class SpeechRecognitionFragment extends Fragment {
public static SpeechRecognitionFragment newInstance() {
return new SpeechRecognitionFragment();
}
private AudioVisualization audioVisualization;
private Button btnRecognize;
private SpeechRecognizerDbmHandler handler;
private boolean recognizing;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gles, container, false);
audioVisualization = (AudioVisualization) view.findViewById(R.id.visualizer_view);
btnRecognize = (Button) view.findViewById(R.id.btn_recognize);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btnRecognize.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recognizing) {
handler.stopListening();
} else {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getContext().getPackageName());
handler.startListening(intent);
}
btnRecognize.setEnabled(false);
}
});
handler = DbmHandler.Factory.newSpeechRecognizerHandler(getContext());
handler.innerRecognitionListener(new SimpleRecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
super.onReadyForSpeech(params);
onStartRecognizing();
}
#Override
public void onResults(Bundle results) {
super.onResults(results);
onStopRecognizing();
}
#Override
public void onError(int error) {
super.onError(error);
onStopRecognizing();
}
});
audioVisualization.linkTo(handler);
}
private void onStopRecognizing() {
recognizing = false;
btnRecognize.setText(R.string.start_recognition);
btnRecognize.setEnabled(true);
}
private void onStartRecognizing() {
btnRecognize.setText(R.string.stop_recognition);
btnRecognize.setEnabled(true);
recognizing = true;
}
#Override
public void onDestroyView() {
audioVisualization.release();
super.onDestroyView();
}
private static class SimpleRecognitionListener implements RecognitionListener {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
}
#Override
public void onResults(Bundle results) {
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
}
}
from https://github.com/Cleveroad/WaveInApp/blob/master/app/src/main/java/com/cleveroad/example/SpeechRecognitionFragment.java
So can some one tell me why fragment is used and how I can set this in my main activity?
I know i am late to post this answer...but for future use try this
check my code you will find your answer
first of all in the liberay you have to make some changes in your xml.
<com.cleveroad.audiovisualization.GLAudioVisualizationView
android:id="#+id/visualizer_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:av_bubblesSize= "#dimen/bubble_size"
app:av_bubblesRandomizeSizes= "true"
app:av_wavesHeight= "#dimen/wave_height"
app:av_wavesFooterHeight="#dimen/footer_height"
app:av_wavesCount="7"
app:av_layersCount="4" />
then
private VisualizerDbmHandler handler;
MediaPlayer mp ;
private AudioVisualization audioVisualization;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View ve = inflater.inflate(R.layout.cat, container, false);
ibCapture = (ImageButton) ve.findViewById(R.id.ibCapture);
audioVisualization = (AudioVisualization)ve.findViewById(R.id.visualizer_view);
hell();
return ve;
}
ibCapture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (bool) {
bool = false;
mp = MediaPlayer.create(getContext(), R.raw.blackcat);
mp.setLooping(true);
handler = VisualizerDbmHandler.Factory.newVisualizerHandler(getContext(),mp);
audioVisualization.linkTo(handler);
mp.start();
((home)getActivity()).vis();
} else {
bool = true;
((home)getActivity()).visgone();
stopPlaying();
}
}
});
Replace
audioVisualization = (AudioVisualization) glAudioVisualizationView;
With
audioVisualization = (AudioVisualization)findViewById(R.id.glAudioVisualizationView);
glAudioVisualizationView should be id of AudioVisualization in your layout file
define
private AudioVisualization audioVisualization;
initialize it
audioVisualization = (AudioVisualization) view.findViewById(R.id.visualizer_view);
for speech use below code
SpeechRecognizerDbmHandler speechRecHandler = DbmHandler.Factory.newSpeechRecognizerHandler(getContext());
speechRecHandler.innerRecognitionListener();
audioVisualization.linkTo(speechRecHandler);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getContext().getPackageName());
speechRecHandler.startListening(intent);
for a media on your device use below code, Sandeep Singh Answer
MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.blackcat);
mp.setLooping(true);
handler = VisualizerDbmHandler.Factory.newVisualizerHandler(getContext(),mp);
audioVisualization.linkTo(handler);
mp.start();

Start AsyncTask in Application class; use listener to inform activity

I start in Application class, in onCreate, a background thread (AsyncTask) which does some time consuming job (between 15 - 70 seconds).
In an activity I need to make some operations only if that task started in Application onCreate() method is completed.
My solution for this is:
Application class
create an interface with a single method
in AsyncTask onPostExecute method I update the listener
I have also a boolean variable to know from poutside if asyncTask is in progress or is terminated
MyActivity class
I implement the listener
when pressing the button:
if asyncTask is in progress I set the listener and I will be informed in onCommandEnded when AsyncTask is done and do there the operations
if asyncTask job is done I do here the following operations.
I'm not sure if this is the correct way to do it...
import android.app.Application;
import android.content.Context;
import android.os.AsyncTask;
public class MyApplicationClass extends Application {
protected static MyApplicationClass instance;
public static MyApplicationClass getInstance() {
return instance;
}
private ApplicationListener listener;
public void setListener(ApplicationListener listener) {
this.listener = listener;
}
public static interface ApplicationListener {
void onCommandEnded();
}
private boolean isInProgress;
#Override
public void onCreate() {
super.onCreate();
instance = this;
CommandAsyncTask copyFfmpeg = new CommandAsyncTask();
copyFfmpeg.execute();
}
private class CommandAsyncTask extends AsyncTask<Void, Void, Double> {
#Override
protected void onPreExecute() {
super.onPreExecute();
isInProgress = true;
}
#Override
protected Double doInBackground(Void... params) {
//do some time consuming operations here
return null;
}
#Override
protected void onPostExecute(Double aDouble) {
if (listener != null) {
listener.onCommandEnded();
}
isInProgress = false;
super.onPostExecute(aDouble);
}
}
public boolean isInProgress() {
return isInProgress;
}
}
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MyActivity extends Activity implements MyApplicationClass.ApplicationListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (MyApplicationClass.getInstance().isInProgress()) {
MyApplicationClass.getInstance().setListener(MyActivity.this);
} else {
//start new asynctask
}
}
});
}
#Override
public void onCommandEnded() {
//start here new asynctask
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MyActivity"
/>
</LinearLayout>

Starting new activity triggered by boolean in GameThread (android)

I am making a "Defend the castle" style android application. The game is complete, however I just need help closing my surfaceview and starting a new activity for when the the player has lost the game.
The condition for losing the game is just a boolean variable in my GameThread class. The variable is called "lost" and is by default set to false. When the life of the castle drops below 1, lost is set to true and a sound effect plays.
Ideally, I would like to stop the currently looping sound effects and open a new activity (which is already made and working) upon lost=true.
The main activity is as follows:
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends Activity {
Button btn_startGame;
Activity activity;
GameView mGameView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
activity = this;
setContentView(R.layout.main);
btn_startGame = (Button) findViewById(R.id.btnStartGame);
btn_startGame.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
mGameView = new GameView(activity);
setContentView(mGameView);
mGameView.mThread.doStart();
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
try {
mGameView.mThread.onTouch(event);
} catch(Exception e) {}
return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// ignore orientation/keyboard change
super.onConfigurationChanged(newConfig);
}
}
The surfaceview is created in this class called GameView:
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
public class GameView extends SurfaceView implements Callback {
Context mContext;
GameThread mThread;
public GameView(Context context) {
super(context);
this.mContext = context;
getHolder().addCallback(this);
mThread = new GameThread(getHolder(), mContext, new Handler() {
#Override
public void handleMessage(Message m) {
// Use for pushing back messages.
}
});
setFocusable(true);
}
//#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.d(this.getClass().toString(), "in SurfaceChanged()");
}
//#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(this.getClass().toString(), "in SurfaceCreated()");
mThread.running = true;
mThread.start();
}
//#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(this.getClass().toString(), "in SurfaceDestroyed()");
boolean retry = true;
mThread.running = false;
while (retry) {
try {
mThread.join();
retry = false;
} catch (InterruptedException e) {
}
GameThread.music.stop();
GameThread.groan1.stop();
GameThread.groan2.stop();
GameThread.walk.stop();
GameThread.music.release();
GameThread.groan1.release();
GameThread.groan2.release();
GameThread.walk.release();
GameThread.shoot.release();
}
}
}
The GameThread class contains all of the drawing, the logic and all a run method (below).
#Override
public void run() {
// check if condition here
if(lost){
mContext.runOnUiThread(new Runnable() {
#Override
public void run() {
//start Activity here
Intent intent = new Intent(mContext, LoseActivity.class);
mContext.startActivity(intent);
}
});
}
else{
if (running == true) {
while (running) {
Canvas c = null;
try {
c = mHolder.lockCanvas();
if (width == 0) {
width = c.getWidth();
height = c.getHeight();
player.x = 50;
player.y = 45;
}
synchronized (mHolder) {
long now = System.currentTimeMillis();
update();
draw(c);
ifps++;
if (now > (mLastTime + 1000)) {
mLastTime = now;
fps = ifps;
ifps = 0;
}
}
} finally {
if (c != null) {
mHolder.unlockCanvasAndPost(c);
}
}
}
}
}
The activity that I want to start is called LoseActivity.class. Thank you in advance for any and all help. If anybody needs any further code/explanations, I will be more than happy to post it.
Use runOnUiThread for starting Activity from Thread as:
Change your main Activity as:
public class MainActivity extends Activity {
Button btn_startGame;
Activity activity;
GameView mGameView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
activity = this;
setContentView(R.layout.main);
btn_startGame = (Button) findViewById(R.id.btnStartGame);
btn_startGame.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
mGameView = new GameView(activity,MainActivity.this);
setContentView(mGameView);
mGameView.mThread.doStart();
}
});
}
///your code.....
Change your GameView class as:
public class GameView extends SurfaceView implements Callback {
Context mContext;
Activity contextx;
GameThread mThread;
public GameView(Context context,Activity contextx) {
super(context);
this.mContext = context;
this.contextx=contextx;
getHolder().addCallback(this);
mThread = new GameThread(getHolder(), mContext, new Handler() {
#Override
public void handleMessage(Message m) {
// Use for pushing back messages.
}
});
setFocusable(true);
}
//your code here..........
#Override
public void run() {
// check if condition here
if(lost){
contextx.runOnUiThread(new Runnable() {
#Override
public void run() {
//start Activity here
Intent intent = new Intent(contextx, LoseActivity.class);
contextx.startActivity(intent);
}
});
}
else{
//your code here.........

Async task wont stop

package com.example.asynctask;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
ProgressBar progressbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressbar = (ProgressBar) findViewById(R.id.progressBar);
}
class ProgressTask extends AsyncTask<Integer, Integer, Void> {
private boolean flag = true;
#Override
protected void onPreExecute() {
progressbar.setMax(100);
}
#Override
protected void onCancelled() {
//progressbar.setMax(0);
flag = false;
Log.v("onCancelled:flag", String.valueOf(flag));
}
#Override
protected Void doInBackground(Integer... params) {
// TODO Auto-generated method stub
int start = params[0];
for (int i = start; i <= 100; i=i+10) {
if (!flag) {
break;
} else {
publishProgress(i);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e("ThreadError", e.toString());
}
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
progressbar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
Log.v("Progress", "Finish");
}
}
public void onClick(View v) {
ProgressTask task = new ProgressTask();
switch (v.getId()) {
case R.id.start:
task.execute(10);
break;
case R.id.stop:
task.cancel(true);
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Here is a symple AsyncTask app which starts to update the progress bar when you hit Start. But when you will hit stop, it wont stop. Thing is when you call task.cancel(true), onCancelled() methods does gets invoked and changes the value of flag to false but in onCancelled() value of flag remains true. I have also tried isCancelled() in place of flag varaible with no success. For a moment my problem is similar to Ollie C, but no exceptions are thrown in my case.
As Wenhui pointed out in the comment, I made a silly mistake in which I declared and instantiated task inside onClick(View v).

Categories

Resources