I'm developing a Whack-a-mole game in Android Studio and I'm having a hard time with AsyncTask (our teacher told us to use it).
Basically the AsyncTasks are not doing anything.
I tried using one asynctask to increase an int and change a textview with the new value each time it increased and it worked, however it doesn't work for what I want it to do.
TextView tv;
ImageView iv1;
ImageView iv2;
ImageView iv3;
ImageView iv4;
boolean salir = false;
int puntuacion = 0;
int vidas = 3;
Hilo hilo;
Hilo hilo2;
Hilo hilo3;
Hilo hilo4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
tv = findViewById(R.id.textView);
iv1 = findViewById(R.id.imageView);
iv2 = findViewById(R.id.imageView2);
iv3 = findViewById(R.id.imageView3);
iv4 = findViewById(R.id.imageView4);
hilo = new Hilo(iv1);
hilo2 = new Hilo(iv2);
hilo3 = new Hilo(iv3);
hilo4 = new Hilo(iv4);
hilo.execute();
hilo2.execute();
hilo3.execute();
hilo4.execute();
}
public void updatePuntuacion() {
tv.setText("Puntuacion: " + puntuacion);
}
public void updateVidas() {
}
private class Hilo extends AsyncTask<Void, Void, Integer> {
boolean estado = false;
ImageView img;
public Hilo (ImageView img) {
this.img = img;
}
#Override
protected Integer doInBackground(Void... voids) {
while(!salir){
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (estado) {
puntuacion++;
updatePuntuacion();
} else {
vidas--;
updateVidas();
}
}
});
if(estado) {
try {
Thread.sleep(Math.round(Math.random()*5000+2000));
} catch (InterruptedException e) {
e.printStackTrace();
}
img.setImageResource(R.drawable.topo);
estado=true;
publishProgress();
} else {
try {
Thread.sleep(Math.round(Math.random()*3000+1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
img.setImageResource(R.drawable.blank);
estado=false;
publishProgress();
}
if(puntuacion == 100) {
salir=true;
}
if(vidas == 0) {
salir = true;
}
}
return puntuacion;
}
}
I expect the imageviews to change it's image every X secs (those are random) but they don't.
I hope you guys can help me, thanks in advance!!!
You need to understand how an Async task works.
You cannot do all the work in "doInBackground" .
You need to remove the onClickListener form "doInBackground" .
Start your async task in the imageview onClick and
After your complete your background processing stuff in "doInBackground" ,
set the image to imageview in "onPostExecute" .
Please go through this https://developer.android.com/reference/android/os/AsyncTask
to understand what an Async Task is first
Related
I have been trying to figure this out all day, as I would like to add an image depending on the outcome of the emotion may detect. Just wanted to add some some images but I'm still new to this. Can anyone help me with this one to.
btw here's my code:
public class DetectionActivity extends AppCompatActivity {
// Background task of face detection.
private class DetectionTask extends AsyncTask<InputStream, String, Face[]> {
private boolean mSucceed = true;
#Override
protected Face[] doInBackground(InputStream... params) {
// Get an instance of face service client to detect faces in image.
FaceServiceClient faceServiceClient = SampleApp.getFaceServiceClient();
try {
publishProgress("Detecting...");
// Start detection.
return faceServiceClient.detect(
params[0], /* Input stream of image to detect */
true, /* Whether to return face ID */
true, /* Whether to return face landmarks */
new FaceServiceClient.FaceAttributeType[]{
FaceServiceClient.FaceAttributeType.Emotion,
});
} catch (Exception e) {
mSucceed = false;
publishProgress(e.getMessage());
addLog(e.getMessage());
return null;
}
}
#Override
protected void onPreExecute() {
mProgressDialog.show();
addLog("Request: Detecting in image " + mImageUri);
}
#Override
protected void onProgressUpdate(String... progress) {
mProgressDialog.setMessage(progress[0]);
setInfo(progress[0]);
}
#Override
protected void onPostExecute(Face[] result) {
if (mSucceed) {
addLog("Response: Success. Detected " + (result == null ? 0 : result.length)
+ " face(s) in " + mImageUri);
}
// Show the result on screen when detection is done.
setUiAfterDetection(result, mSucceed);
}
}
// Flag to indicate which task is to be performed.
private static final int REQUEST_SELECT_IMAGE = 0;
// The URI of the image selected to detect.
private Uri mImageUri;
// The image selected to detect.
private Bitmap mBitmap;
// Progress dialog popped up when communicating with server.
ProgressDialog mProgressDialog;
// When the activity is created, set all the member variables to initial state.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detection);
//this hides the back button and I thank you
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle(getString(R.string.progress_dialog_title));
// Disable button "detect" as the image to detect is not selected.
setDetectButtonEnabledStatus(false);
LogHelper.clearDetectionLog();
}
// Save the activity state when it's going to stop.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("ImageUri", mImageUri);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menuAbout:
// Toast.makeText(this, "You clicked about", Toast.LENGTH_SHORT).show();
View messageView = getLayoutInflater().inflate(R.layout.about, null, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.smile);
builder.setTitle(R.string.app_name);
builder.setView(messageView);
builder.create();
builder.show();
break;
case R.id.menuHelp:
// Toast.makeText(this, "You clicked settings", Toast.LENGTH_SHORT).show();
// Intent help = new Intent(this, HelpActivity.class);
//startActivity(help);
// break;
View messageViewh = getLayoutInflater().inflate(R.layout.help, null, false);
AlertDialog.Builder builderh = new AlertDialog.Builder(this);
builderh.setIcon(R.drawable.smile);
builderh.setTitle(R.string.app_nameh);
builderh.setView(messageViewh);
builderh.create();
builderh.show();
break;
}
return true;
}
// Recover the saved state when the activity is recreated.
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageUri = savedInstanceState.getParcelable("ImageUri");
if (mImageUri != null) {
mBitmap = ImageHelper.loadSizeLimitedBitmapFromUri(
mImageUri, getContentResolver());
}
}
// Called when image selection is done.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_SELECT_IMAGE:
if (resultCode == RESULT_OK) {
// If image is selected successfully, set the image URI and bitmap.
mImageUri = data.getData();
mBitmap = ImageHelper.loadSizeLimitedBitmapFromUri(
mImageUri, getContentResolver());
if (mBitmap != null) {
// Show the image on screen.
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageBitmap(mBitmap);
// Add detection log.
addLog("Image: " + mImageUri + " resized to " + mBitmap.getWidth()
+ "x" + mBitmap.getHeight());
}
// Clear the detection result.
FaceListAdapter faceListAdapter = new FaceListAdapter(null);
ListView listView = (ListView) findViewById(R.id.list_detected_faces);
listView.setAdapter(faceListAdapter);
// Clear the information panel.
setInfo("");
// Enable button "detect" as the image is selected and not detected.
setDetectButtonEnabledStatus(true);
}
break;
default:
break;
}
}
// Called when the "Select Image" button is clicked.
public void selectImage(View view) {
Intent intent = new Intent(this, SelectImageActivity.class);
startActivityForResult(intent, REQUEST_SELECT_IMAGE);
}
// Called when the "Detect" button is clicked.
public void detect(View view) {
// Put the image into an input stream for detection.
ByteArrayOutputStream output = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
ByteArrayInputStream inputStream = new ByteArrayInputStream(output.toByteArray());
// Start a background task to detect faces in the image.
new DetectionTask().execute(inputStream);
// Prevent button click during detecting.
setAllButtonsEnabledStatus(false);
}
// View the log of service calls.
public void viewLog(View view) {
Intent intent = new Intent(this, DetectionLogActivity.class);
startActivity(intent);
}
// Show the result on screen when detection is done.
private void setUiAfterDetection(Face[] result, boolean succeed) {
// Detection is done, hide the progress dialog.
mProgressDialog.dismiss();
// Enable all the buttons.
setAllButtonsEnabledStatus(true);
// Disable button "detect" as the image has already been detected.
setDetectButtonEnabledStatus(false);
if (succeed) {
// The information about the detection result.
String detectionResult;
if (result != null) {
detectionResult = result.length + " face"
+ (result.length != 1 ? "s" : "") + " detected";
// Show the detected faces on original image.
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageBitmap(ImageHelper.drawFaceRectanglesOnBitmap(
mBitmap, result, true));
// Set the adapter of the ListView which contains the details of the detected faces.
FaceListAdapter faceListAdapter = new FaceListAdapter(result);
// Show the detailed list of detected faces.
ListView listView = (ListView) findViewById(R.id.list_detected_faces);
listView.setAdapter(faceListAdapter);
} else {
detectionResult = "0 face detected";
}
setInfo(detectionResult);
}
mImageUri = null;
mBitmap = null;
}
// Set whether the buttons are enabled.
private void setDetectButtonEnabledStatus(boolean isEnabled) {
Button detectButton = (Button) findViewById(R.id.detect);
detectButton.setEnabled(isEnabled);
}
// Set whether the buttons are enabled.
private void setAllButtonsEnabledStatus(boolean isEnabled) {
Button selectImageButton = (Button) findViewById(R.id.select_image);
selectImageButton.setEnabled(isEnabled);
Button detectButton = (Button) findViewById(R.id.detect);
detectButton.setEnabled(isEnabled);
// Button ViewLogButton = (Button) findViewById(R.id.view_log);
// ViewLogButton.setEnabled(isEnabled);
}
// Set the information panel on screen.
private void setInfo(String info) {
TextView textView = (TextView) findViewById(R.id.info);
textView.setText(info);
}
// Add a log item.
private void addLog(String log) {
LogHelper.addDetectionLog(log);
}
// The adapter of the GridView which contains the details of the detected faces.
private class FaceListAdapter extends BaseAdapter {
// The detected faces.
List<Face> faces;
// The thumbnails of detected faces.
List<Bitmap> faceThumbnails;
// Initialize with detection result.
FaceListAdapter(Face[] detectionResult) {
faces = new ArrayList<>();
faceThumbnails = new ArrayList<>();
if (detectionResult != null) {
faces = Arrays.asList(detectionResult);
for (Face face : faces) {
try {
// Crop face thumbnail with five main landmarks drawn from original image.
faceThumbnails.add(ImageHelper.generateFaceThumbnail(
mBitmap, face.faceRectangle));
} catch (IOException e) {
// Show the exception when generating face thumbnail fails.
setInfo(e.getMessage());
}
}
}
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public int getCount() {
return faces.size();
}
#Override
public Object getItem(int position) {
return faces.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.item_face_with_description, parent, false);
}
convertView.setId(position);
// Show the face thumbnail.
((ImageView) convertView.findViewById(R.id.face_thumbnail)).setImageBitmap(
faceThumbnails.get(position));
// Show the face details.
String getEmotion;
// String improve = improveMessage(getEmotion);
DecimalFormat formatter = new DecimalFormat("#0.0");
//add
// String message = findMessage(getEmotion());
// String improve = improveMessage(getEmotion);
String face_description = String.format("Emotion: %s\n",
getEmotion(faces.get(position).faceAttributes.emotion)
);
((TextView) convertView.findViewById(R.id.text_detected_face)).setText(face_description);
return convertView;
}
private String getEmotion(Emotion emotion) {
String emotionType = "";
double emotionValue = 0.0;
String emotionInfo = "";
if (emotion.anger > emotionValue) {
emotionValue = emotion.anger;
emotionType = "Anger";
emotionInfo = "If you haven't fed him/her yet maybe this precious one is thirsty or hungry.\n Try giving your attention. If your baby is acting unusual it's best to seek for medical help.";
}
if (emotion.contempt > emotionValue) {
emotionValue = emotion.contempt;
emotionType = "Contempt";
emotionInfo = "You go girl!";
}
if (emotion.disgust > emotionValue) {
emotionValue = emotion.disgust;
emotionType = "Disgust";
emotionInfo = "Look! If your baby is feeling this way mabye she/he doesn't like this. \n If what your doing right now is good for him/her maybe you can support that.";
}
if (emotion.fear > emotionValue) {
emotionValue = emotion.fear;
emotionType = "Fear";
emotionInfo = "Your baby looks somewhat uncomfortable.\n Make your baby feel comfortable and take note of what makes them feel like that. ";
}
if (emotion.happiness > emotionValue) {
emotionValue = emotion.happiness;
emotionType = "Happiness";
emotionInfo = "Just continue what you are doing. It is important to remember what can make them happy. \n";
}
if (emotion.neutral > emotionValue) {
emotionValue = emotion.neutral;
emotionType = "Neutral";
emotionInfo = "Maybe you should just observe first";
}
if (emotion.sadness > emotionValue) {
emotionValue = emotion.sadness;
emotionType = "Sadness";
emotionInfo = "Just cuddle or dandle your baby.";
}
if (emotion.surprise > emotionValue) {
emotionValue = emotion.surprise;
emotionType = "Surprise";
emotionInfo = "Oooh look. Play with your baby. Try doing peek a boo";
}
return String.format("%s: %f \n\n%s", emotionType, emotionValue, emotionInfo);
}
}
}
Just would like to add some images like happy if that is the detected emotion. Please do help me. Any help is highly appreciated. Thank you :)
I would like to add that after the emotionInfo.
I guess detectWithStream is you want.
Official Doc: Faces.detectWithStream Method
From Java SDK, the List<DetectedFace> object will return if successful.
I'm having problems in the following context, I need to make signatures on a form that is an image in PNG or JPG, this functionality belongs to a mobile application with Android system.
The status is in the following situation, I can place the signature in the place where the user clicked. But I'm having trouble resizing the signature bitmap proportionally to the amount of zoom that was given. You need to position the signature Bitmap at the point the user clicked on, but referring to the image and not the screen.
I have browsed a lot of topics on the internet, many here in StackOverflow, but I do not find any that gives me any idea how I can do such an activity. I have already arrived several times on the third page of Google.
Can anyone help me, or can you give me some insight into how I can do this?
problem sketch
My code
public class SignatureActivity extends Activity implements OnClickListener {
private LinearLayout mContent;
private Button mClear, mSave, mCancel;
private View view;
private Dialog dialog;
private Signature mSignature;
private TouchImageView img;
private float xPosition;
private float yPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_signature);
img = (TouchImageView) findViewById(R.id.iv_form);
img.setImageResource(R.drawable.imp_009_tiss_1200x859);
img.setOnClickListener(this);
// Dialog Function
dialog = new Dialog(SignatureActivity.this);
// Removing the features of Normal Dialogs
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_signature);
dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mSignature = (Signature) dialog.getWindow().findViewById(R.id.signatureView1);
dialog.setCancelable(true);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_form:
dialog_action();
break;
default:
break;
}
}
public void carregaComponentes() {
mContent = (LinearLayout) dialog.findViewById(R.id.ll_area_assinatura);
mClear = (Button) dialog.findViewById(R.id.clear);
mSave = (Button) dialog.findViewById(R.id.save);
mCancel = (Button) dialog.findViewById(R.id.cancel);
mSignature = (Signature) dialog.findViewById(R.id.signatureView1);
}
public void dialog_action() {
carregaComponentes();
mSignature.setBackgroundColor(Color.WHITE);
mSignature.setSigColor(255, 0, 0, 255);
view = mContent;
mClear.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Cleared");
mSignature.clearSignature();
}
});
mSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Saved");
view.setDrawingCacheEnabled(true);
if (saveSignature(view)) {
dialog.dismiss();
} else {
mSignature.clearSignature();
}
}
});
mCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Canceled");
dialog.dismiss();
mSignature.clearSignature();
}
});
dialog.show();
}
public boolean saveSignature(View view) {
DisplayMetrics dm = new DisplayMetrics();
float dpi = dm.scaledDensity;
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenW = dm.widthPixels;
int screenH = dm.heightPixels;
Bitmap assinatura = mSignature.getImage();
Bitmap assinaturaRedimensionada = Bitmap.createScaledBitmap(
assinatura,
(Integer.valueOf((int) (screenW * 0.20))),
(Integer.valueOf((int) (screenH * 0.070))),
false);
img.buildDrawingCache();
Bitmap imgGto = img.getDrawingCache();
Bitmap gtoAssinada = Bitmap.createBitmap(imgGto.getWidth(), imgGto.getHeight(), imgGto.getConfig());
Canvas canvas = new Canvas(gtoAssinada);
canvas.drawBitmap(imgGto, new Matrix(), null);
canvas.drawBitmap(assinaturaRedimensionada, TouchImageViewListener.x, TouchImageViewListener.y, null);
// Creating Separate Directory for saving Generated Images
File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pic_name = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String StoredPath = "GTO_assinada" + pic_name + ".png";
File fichero = new File(sd, StoredPath);
try {
if (sd.canWrite()) {
fichero.createNewFile();
OutputStream os = new FileOutputStream(fichero);
gtoAssinada.compress(Bitmap.CompressFormat.PNG, 90, os);
os.close();
img.setImageBitmap(gtoAssinada);
mSignature.clearSignature();
Toast.makeText(getApplicationContext(), "GTO Assinada com Sucesso!", Toast.LENGTH_LONG).show();
}
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
I am currently working on Chat application. In this there is feature of sending voice notes. The sending and playing of voice notes is working fine. But the problem is that when I play the voice notes, the previous voice notes playing not stoping.. both are playing together.
here is my code for playing voice notes,
public static class MessageViewHolder extends RecyclerView.ViewHolder {
private TextView messageTextView;
private ImageView messageImageView;
private TextView timeTextView;
private LinearLayout textMessageLayout;
private TextView messengerNameTextView;
private CircleImageView messengerPhotoImageView;
ImageView leftQuackImage, rightQuackImage;
private LinearLayout voiceNotesLayout;
private ImageView playImageView, stopImageView;
private SeekBar progressSeekbar;
private MediaPlayer mPlayer;
double timeElapsed = 0, finalTime = 0;
Handler durationHandler = new Handler();
Runnable updateSeekBarTime;
boolean isPlaying;
public MessageViewHolder(View itemView) {
super(itemView);
messageTextView = (TextView) itemView.findViewById(R.id.messageTextView);
messageImageView = (ImageView) itemView.findViewById(R.id.messageImageView);
timeTextView = (TextView) itemView.findViewById(R.id.timeTextView);
textMessageLayout = (LinearLayout) itemView.findViewById(R.id.textMessageLayout);
messengerNameTextView = (TextView) itemView.findViewById(R.id.messengerTextView);
messengerPhotoImageView = (CircleImageView) itemView.findViewById(R.id.messengerImageView);
leftQuackImage = (ImageView) itemView.findViewById(R.id.leftQuackImage);
rightQuackImage = (ImageView) itemView.findViewById(R.id.rightQuackImage);
voiceNotesLayout = (LinearLayout) itemView.findViewById(R.id.voiceNotesLayout);
playImageView = (ImageView) itemView.findViewById(R.id.playImageView);
stopImageView = (ImageView) itemView.findViewById(R.id.stopImageView);
progressSeekbar = (SeekBar) itemView.findViewById(R.id.progressSeekbar);
isPlaying = false;
mPlayer = new MediaPlayer();
}
public void setupAudioPlay(final long duration, final String url){
progressSeekbar.setMax((int) duration);
progressSeekbar.setClickable(false);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(url);
mPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}catch (IllegalStateException e){
e.printStackTrace();
}
playImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Media player","isPlaying"+mPlayer.isPlaying()+isPlaying);
if (mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
if (!isPlaying) {
isPlaying = true;
mPlayer.start();
playImageView.setVisibility(View.GONE);
stopImageView.setVisibility(View.VISIBLE);
timeElapsed = mPlayer.getCurrentPosition();
progressSeekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 100);
} else {
isPlaying = false;
mPlayer.pause();
}
}
});
stopImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isPlaying) {
if (stopPlaying()) {
playImageView.setVisibility(View.VISIBLE);
stopImageView.setVisibility(View.GONE);
}
}
}
});
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (mp != null) {
mPlayer.seekTo(0);
isPlaying = false;
progressSeekbar.setProgress(0);
}
playImageView.setVisibility(View.VISIBLE);
stopImageView.setVisibility(View.GONE);
}
});
updateSeekBarTime = new Runnable() {
public void run() {
if (mPlayer != null) {
if (mPlayer.isPlaying()) {
timeElapsed = mPlayer.getCurrentPosition();
progressSeekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(this, 100);
} else {
mPlayer.pause();
isPlaying = false;
progressSeekbar.setProgress(0);
playImageView.setVisibility(View.VISIBLE);
stopImageView.setVisibility(View.GONE);
}
}
}
};
}
private boolean stopPlaying() {
mPlayer.pause();
mPlayer.seekTo(0);
if (!mPlayer.isPlaying()) {
return true;
}
return false;
}
}
here the mPlayer.isPlaying always gets false.
Please Help me!
From the documentation:
When the call to pause() returns, the MediaPlayer object enters the Paused state. Note that the transition from the Started state to the Paused state and vice versa happens asynchronously in the player engine. It may take some time before the state is updated in calls to isPlaying(), and it can be a number of seconds in the case of streamed content.
This may be the case here. The reasons why sound is not stopping and why isPlaying() returns true might be different. For example multiple instances of MediaPlayer might exist in parallel, making mPlayer static would exclude such an option.
You can check the system Audio status whenever it is necessary. In your case, whenever the play button is clicked the condition below should be checked first.
AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
{
// to do
}
In to do part you should implement the primary action which is:
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PAUSE);
audioManager.dispatchMediaKeyEvent(event);
You can find the whole documentation here
This question already has answers here:
Android "Only the original thread that created a view hierarchy can touch its views."
(33 answers)
Closed 8 years ago.
So I understand the error. I'm trying to adjust the UI with a thread that isn't the main UI thread. But that's inherently the problem. Doing image processing (in this case greyscaling multiple bitmaps) is a CPU intensive task. Therefore, wouldn't me trying to launch a thread that deals with image processing be the right thing to do? Or is my thought just an ideal thought that simply isn't possible because of the valid error I am receiving? Is there a work around that I'm unaware of?
Actual error message:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
//Package declaration
//Many import statements
public class PhotoViewer extends Activity implements OnClickListener {
private Button refresh_;
private Button grey_;
private ImageView image1_;
private ImageView image2_;
private ImageView image3_;
private ImageView image4_;
private GreyBitmaps gMap_;
private Bitmap bMap1_;
private Bitmap bMap2_;
private Bitmap bMap3_;
private Bitmap bMap4_;
private int num_;
private boolean makeGrey_;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photos);
// this GreyBitmaps class creates the other thread
gMap_ = new GreyBitmaps();
refresh_ = (Button) findViewById(R.id.refresh);
grey_ = (Button) findViewById(R.id.grey);
image1_ = (ImageView) findViewById(R.id.view1);
image2_ = (ImageView) findViewById(R.id.view2);
image3_ = (ImageView) findViewById(R.id.view3);
image4_ = (ImageView) findViewById(R.id.view4);
refresh_.setOnClickListener(this);
grey_.setOnClickListener(this);
makeGrey_ = false;
getPhotos();
setBitmap();
//num_ =0;
}
public void onClick(View v) {
Log.d("onClick", "Begin");
if(v == refresh_){
refreshPhoto();
}else if (v == grey_){
greyPhoto();
}
Log.d("onClick", "end");
}
protected void onResume(){
super.onResume();
gMap_.resume();
}
protected void onPause(){
super.onPause();
gMap_.pause();
}
private void refreshPhoto(){
getPhotos();
}
private void greyPhoto(){
makeGrey_ = true;
}
private void getPhotos(){
bMap1_ = BitmapFactory.decodeResource(getResources(), R.drawable.p1);
bMap2_ = BitmapFactory.decodeResource(getResources(), R.drawable.p2);
bMap3_ = BitmapFactory.decodeResource(getResources(), R.drawable.p3);
bMap4_ = BitmapFactory.decodeResource(getResources(), R.drawable.p4);
}
private void setBitmap(){
image1_.setImageBitmap(bMap1_);
image2_.setImageBitmap(bMap2_);
image3_.setImageBitmap(bMap3_);
image4_.setImageBitmap(bMap4_);
}
private Bitmap goGrey(Bitmap bmIn){
final double gs_red = 0.299;
final double gs_green = 0.587;
final double gs_blue = 0.114;
int width = bmIn.getWidth();
int height = bmIn.getHeight();
Bitmap bmOut = Bitmap.createBitmap(width, height, bmIn.getConfig());
int a, r, g, b;
int pix;
for(int x = 0; x<width; x++){
for(int y = 0; y<height; y++){
pix = bmIn.getPixel(x, y);
a = Color.alpha(pix);
r = Color.red(pix);
g = Color.green(pix);
b = Color.blue(pix);
r = g = b = (int) (gs_blue*b +gs_green*g +gs_red*r);
//write out
bmOut.setPixel(x, y, Color.argb(a, r, g, b));
}
}
return bmOut;
}
public class GreyBitmaps implements Runnable{
Thread t = null;
boolean isActive = false;
public void run() {
Log.d("Runnable", "running");
//num_ = 100;
while(isActive) {
Log.d("Runnable", "running2");
num_ = 200;
setBitmap();
try {
Thread.sleep(100);
if (makeGrey_) {
goGrey(bMap1_);
goGrey(bMap2_);
goGrey(bMap3_);
goGrey(bMap4_);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void pause(){
isActive = false;
while(true){
try{
t.join();
}catch (InterruptedException e) {
e.printStackTrace();
Log.e("Error", "Failed to join thread");
}
break;
}
t = null;
}
public void resume(){
isActive = true;
t = new Thread(this);
t.start();
}
}
}
Call your setBitmap() method in runOnUiThread thread.
See this link for runOnUiThread method implementation https://stackoverflow.com/a/11140429/4384828
Well my question is rather simple
In my layout I have a EditText and two ImageView
I type in any word EditText in two ImageView that I have to be to display images according to the letter, send it as the word of EditText call my problem arises when you want to call one letter for example:
if I enter the word "home" should go in the word and show the two ImageView image according to the letter then would show C (image C) then A (Picture A)
the problem is that I can make the process of finding one letter, I've tried with a for but only recognizes the last letter, I also tried to make a kind of delay (delay) but did not work
part of my code:
public class deletreo extends Activity {
protected TextView tv;
protected EditText etxt;
protected ImageView img,img2;
final Handler handle = new Handler();
protected void mth(){
Thread t = new Thread(){
public void run(){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
handle.post(proceso);
}
};
t.start();
}
final Runnable proceso = new Runnable(){
public void run(){
letra();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
tv = new TextView(this);
setContentView(R.layout.deletreo);
etxt = (EditText)findViewById(R.id.text);
Button btn = (Button)findViewById(R.id.btn7);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mth();
}
});
}//fin bundle
private void letra() {
String t = etxt.getText().toString();
char[] array = t.toCharArray();
int p = array.length;
for(int j=0; j<p;j++){
if(array[j] == 'a' || array[j] == 'A'){
img = (ImageView)findViewById(R.id.img);
img.setImageResource(R.drawable.aa);
img2 = (ImageView)findViewById(R.id.img2);
img2.setImageResource(R.drawable.image_1);
onStop();
}
if(array[j] == 'b' || array[j] == 'B'){
img = (ImageView)findViewById(R.id.img);
img.setImageResource(R.drawable.bb);
img2 = (ImageView)findViewById(R.id.img2);
img2.setImageResource(R.drawable.image_2);
}
any idea how to solve this problem?
the problem is that I can make the process of finding one letter, I've
tried with a for but only recognizes the last letter, I also tried to
make a kind of delay (delay) but did not work
Of course, it behaves that way. Because you are putting delay for 1 second in starting and after that you are calling method letra() which sets image resource in both imageviews in a loop. So you can see only images associated with last letter.
Try it this way instead:
public class deletreo extends Activity {
protected TextView tv;
protected EditText etxt;
protected ImageView img,img2;
final Handler handle = new Handler();
protected void mth(){
Thread t = new Thread(){
public void run(){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
};
t.start();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
tv = new TextView(this);
setContentView(R.layout.deletreo);
etxt = (EditText)findViewById(R.id.text);
Button btn = (Button)findViewById(R.id.btn7);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
letra();
}
});
}//fin bundle
private void letra() {
String t = etxt.getText().toString();
char[] array = t.toCharArray();
int p = array.length;
for(int j=0; j<p;j++){
if(array[j] == 'a' || array[j] == 'A'){
img = (ImageView)findViewById(R.id.img);
img.setImageResource(R.drawable.aa);
img2 = (ImageView)findViewById(R.id.img2);
img2.setImageResource(R.drawable.image_1);
onStop();
}
if(array[j] == 'b' || array[j] == 'B'){
img = (ImageView)findViewById(R.id.img);
img.setImageResource(R.drawable.bb);
img2 = (ImageView)findViewById(R.id.img2);
img2.setImageResource(R.drawable.image_2);
}
mth();
}
}
}
Call delay function mth() after each round of loop. Hope it works.