Repeating a sound - Android Software Development

Hey guys I'm building a metronome and am using the MediaPlayer.
Code:
MediaPlayer mp;
.....
public void run() {
if(playing) {
mp.seekTo(0);
mp.start();
}
else
{
mp = MediaPlayer.create(getBaseContext(), R.raw.cowbell);
mp.start();
playing = true;
}
}
the run method is called in regular intervals. There is a delay between the first and second click then it seems to run smoothly. Even so at higher tempos I feel like it is phasing in and out of time. Also the fastest the sound will play is about every 300ms anything faster and there is no noticeable difference.
Any thoughts?
Thanks,
Jordan

I've managed to smooth things out by using SoundPool instead of mediaplayer as its more suited to this sort of thing and I can assume uses less resources. My metronome is still inconsistent though. Is there a better timing method other than using handler/runnable/postdelayed?

Related

[Q] timer keeps going after app has been terminated?

I am making an app that plays sounds in a loop based on a timer. after I exit the program using finish(); the sounds keep playing in background anyway. Any ideas of why this is and how I can fix it (besides having to use a task killer every time)
thanks
hyperbyteX said:
I am making an app that plays sounds in a loop based on a timer. after I exit the program using finish(); the sounds keep playing in background anyway. Any ideas of why this is and how I can fix it (besides having to use a task killer every time)
thanks
Click to expand...
Click to collapse
finish() just closes the activity, it does *NOT* close the app. Threads will continue to run, services will continue to run, broadcast receivers will continue to receive, etc...
You need to actually stop/cancel the timer if you want it to stop.
I recommend reading this (and then re-reading it again): http://developer.android.com/guide/topics/fundamentals.html and this http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html
hyperbyteX said:
I am making an app that plays sounds in a loop based on a timer. after I exit the program using finish(); the sounds keep playing in background anyway. Any ideas of why this is and how I can fix it (besides having to use a task killer every time)
thanks
Click to expand...
Click to collapse
The timer probably uses the system timer service, Which calls your sound file again and again.
Stop the timer in the onDestory function of your activity.
how exactly do I stop it?
hyperbyteX said:
how exactly do I stop it?
Click to expand...
Click to collapse
Take a look at the documentation from google. probably something like .stop(timer)
don't know
heres the code Im using:
// set timer
TimerTask scanTask = null;
final Handler handler = new Handler();
Timer t = new Timer();
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
// stuff to run goes here
}
}
});
}};
t.schedule(scanTask, 1, 50); // time how often stuff happens
I've tried many ways to kill it but nothing seems to work
hyperbyteX said:
heres the code Im using:
// set timer
TimerTask scanTask = null;
final Handler handler = new Handler();
Timer t = new Timer();
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
// stuff to run goes here
}
}
});
}};
t.schedule(scanTask, 1, 50); // time how often stuff happens
I've tried many ways to kill it but nothing seems to work
Click to expand...
Click to collapse
Did you try TimerTask .cancel(); ?
Dark3n said:
Did you try TimerTask .cancel(); ?
Click to expand...
Click to collapse
yeah I tried that but it gives me an error saying "Cannot make a static reference to the non-static method cancel() from the type TimerTask"
Ok, thank you very much. I had to tweak it a bit but I got it!

Help writing something with setOnItemClickListener

In my Android app, I have a sound that I want to play when a certain selection has been made from a spinner, but I want it to play the when the user actually makes the proper selection (or just after). My problem is that although the sound does play when they make the correct selection, as long as that selection stays chosen, it also plays every time the app starts up, when it should ONLY play at the time it's chosen. I think I need to change my setOnItemSelectedListener to setOnItemClickListener, but I'm not sure how (still pretty new to java). Can any generous soul out there show me how to change this up (assuming that's how to best solve this problem)?
Here is the code I have now:
Code:
fitnessSpinner = (Spinner) findViewById(R.id.fitness_spinner);
ArrayAdapter adapter4 = ArrayAdapter.createFromResource(
this, R.array.fitness_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fitnessSpinner.setAdapter(adapter4);
fitnessSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
Log.d("test", "p: " + position + " " + i);
if(position == 0) {
//First Entry
MediaPlayer mp = MediaPlayer.create(mContext, R.raw.bowchica);
mp.start();
} if(position == 4) {
MediaPlayer mp = MediaPlayer.create(mContext, R.raw.debbie2);
mp.start();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
I haven't try the below code but you can try it on your own and tell us.
In onCreate() declare MediaPlayer mp;
In every if statement that you use for check insert this code:
Code:
if(mp!=null){mp.release();}
int resid = R.raw.yoursound;
mp = MediaPlayer.create(this, resid);
After that override the methods onPause() and onResume() and insert this:
if(mp!=null){mp.release();}
If it is still playing a sound when you start your app, then you should check your code again if you have set as default option any of your selection options.
I would LOVE to try this out...Unfortunately, I'm way too dumb at this point point ot figure out exactly where those code snippets would go inside of what I already have.
Does anyone have a couple of minutes to show me where it would go?
Below is a sample code. Since i don't know your code I give you a snippet that you should adjust it to your code.
Code:
public class SampleSound extends Activity{
private Spinner fitnessSpinner;
private MediaPlayer mp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//here goes your layout
setViews();//here you will set all your views(spinners buttons textviews etc..)
setAdapters();//set your adapters here
setListeners();//
}
private void setListeners() {
fitnessSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
Log.d("test", "p: " + position + " " + i);
if(position == 0) {
//First Entry
if(mp!=null){mp.release();}
int resid = R.raw.bowchica;
mp = MediaPlayer.create(this, resid);
mp.start();
} if(position == 4) {
if(mp!=null){mp.release();}
int resid = R.raw.debbie2;
mp = MediaPlayer.create(this, resid);
mp.start();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
private void setAdapters() {
ArrayAdapter adapter4 = ArrayAdapter.createFromResource(this, R.array.fitness_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fitnessSpinner.setAdapter(adapter4);
}
private void setViews() {
fitnessSpinner = (Spinner) findViewById(R.id.fitness_spinner);
}
public void onResume(){
super.onResume();
if(mp!=null){mp.release();}
}
public void onPause(){
super.onPause();
if(mp!=null){mp.release();}
}
}
I really appreciate the help. I put the code in my routine, but it still plays the sound every time the activity is loaded (as long as the selection in the spinner is correct). It should only play the sound when the correct selection is made.
Any other ideas?
I am sure that your Spinner is set to some value (since you have values to display). Because your Spinner points to a selection (doesn't matter if you have selected or it is selected by default) your sound plays (even when you start the app).
A way to stop the sound playing at start is to declare and an other Item like you did with the previous 4 and set it as default selection of your Spinner.
To sum up:
1.You have to append in R.array.fitness_array an Item (like you did with the previous Items) and give it a name.
2.At the end of method setAdapters() insert this:
Code:
fitnessSpiner.setSelection(5);// or whatever is your selection number
Now it should work but you should know that this is not a good practice and you should try make a ListView or something else.
I'd be happy to change this out to a listview, or whatever would work. I just have to give my user a choice of 4 or 5 items, from which they can choose only one. Something like a drop down box, but in Android, I thought my only option was a spinner. But whatever I use, I have to be able to play a sound when certain items are chosen, but ONLY when those items are chosen, NOT whenever the activity is called up.
Any specific ideas of what I might change to?
What if I had another control like a textview or an edittext (with it's visibility property set to false) that I programatically populated with the users selection (when it's the selection that I want) and then have an OnItemClcickListener set to play the sound?
Could that work?
I will answer from the last to the top of your questions.
1.You can do whatever you want with android. You want TextViews and EditTexts with complex and nested Layouts you can do it. Write services that will communicate with your contacts through a content provider? You can do it.
Write, read and test code. Only this way you will actually learn.
2.Read developer.android.com. Read the android tutorials from there and specifically the Notepad example. You will learn a lot.
A good resource with small examples for ListViews is this.
3.Have you tried the changes I told you from the last post? Did it worked?
Since you just started with android and programming you must first be happy if you have the expected result and then read more to make your code better
Your suggested changes (fitnessSpiner.setSelection(5);// or whatever is your selection number) would stop the sound from playing, but defeat the apps purpose. Every time this activity is loaded, the spinners hit preferences to load the previously stored data. So if I force the spinner to a different selection to NOT play sound when the activity loads, then I would be displaying the wrong data for the user.
Yes you are right. So it is better to make a ListActivity. Read developer.android.com and the link i gave you before. You will be ok with this!
You're using "setOnItemSelectedListener", which sounds like when the app starts, its getting "selected" again.
Have you tried using "setOnItemClickListener" instead?
fitnessSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener () {
public void onItemClicked() {}
};
Lakers16 said:
You're using "setOnItemSelectedListener", which sounds like when the app starts, its getting "selected" again.
Have you tried using "setOnItemClickListener" instead?
fitnessSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener () {
public void onItemClicked() {}
};
Click to expand...
Click to collapse
onClickListener doesn't work for the spinner...I wish it did.
I REALLY need the drop down functionality of teh spinner, so I guess I'm going to try and figure out a way to have an invisible edittext that I set to the spinner selection and then use onClickListener or onChange...

[Q] Repeat Button Action

Hello. New here and I hope this post is okay. The "Is this a question?" checkbox says it not the QA forum but it is?
Working on an app that all it's supposed to do is repeat taking a picture every 5 seconds after pressing a button. Now, I've looked at handler, timer, etc but I can't figure out the right way to do it. This is the code currently, and the onCameraClick of course runs when the button on the screen is pressed. I want that button to activate some kind of repeater so the picture gets taken every 5000ms.
Code:
public class CameraImage extends Activity {
public static int cameraID = 0;
public static ImageView image;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cameraimage);
image = (ImageView) findViewById(R.id.imgView);
}
public void onCameraClick(View v)
{
cameraID = 1;
Intent i = new Intent(CameraImage.this, CameraView.class);
startActivityForResult(i, 9999);
}
}
Now, this is something I'd definitely like to use but I'm not sure how to implement this correctly into the code above. Been trying trial and error for past few hours and nothing. Tried out a timer example someone put on another website, 10792454/image-capture-in-android-automatically but not much there.
At the same time however though, I'm not sure if the code should go in the other class with all the functions to run the camera. Any suggestions/tip or help I'd greatly appreciate it.
Try a loop. I'm not sure if you have tried this or if it will work with launching an activity, but it sounds like that is what you want to do. I don't know how you determine when to stop taking pictures but you can use a "for loop" or a "while loop".
example "for loop":
Code:
for (int i; i > someNumber; i++){
//Your code here
}
someNumber would be perhaps the number of pictures you want to take and you can use i to number each picture.
example "while loop":
Code:
Boolean buttonClick = false;
onCreate(){
OnButtonClick(){
OnClick(){
if(buttonClick == true){
buttonClick = false;
}else{
buttonClick = true;
}
onCameraStart(buttonClick);
}
public void onCameraStart(boolean runCamera){
while (runCamera == true){
//Your code here
}
}
This example I showed you how you would be able to start the camera on the first click and stop it when clicked again. The OnButtonClick would be the OnClickListener for your button.
Both these examples may need a little refinement but this should point you in the right direction. Hope this helps. You can put these in threads and pause the thread at the end of the loop for 5 secs so it will wait (I think).
It's simple use a timer and invoke it on first click
Sent from my GT-S5302 using Tapatalk 2

Android game programming questions

Hey,
I want to learn how to create android games, I know how to write 2D games in C++ using Allegro library.
I've recently started to learn java so that I can make such games for Android devices.
I have two books - "Android Game Programming for Dummies" and "Beginning Android Games" -
the thing is the latter is too complicated for me, and they are using frameworks which is kinda advanced - I want to start from very simple apps so that I can really understand how it all works.
The former on the other hand started well, I've learned how to make activities and switch between them, show bitmaps and simple shapes like rectangles.
However the first game in this book is a card game that is turn based - and I want to make something different entirely - a game where I need timer events - what it means is that every given amount of time some actions are executed.
How do I do it ?
Here's part of my code where I would like to include a timer and actions that will be executed.
This code shows 3 rectangles in random positions and a circle. When I touch the screen, the circle is redrawn there.
Code:
public class GameView extends View{
private Paint redPaint;
private int circleX;
private int circleY;
private float radius;
List<Obstacles> listaL = new ArrayList<Obstacles>();
List<Obstacles> listaR = new ArrayList<Obstacles>();
List<Obstacles> listaT = new ArrayList<Obstacles>();
List<Obstacles> listaB = new ArrayList<Obstacles>();
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
for (int i=0;i<3;i++)
{
Obstacles obs = new Obstacles();
listaL.add(obs);
}
Random rand = new Random();
for (int i=0;i<listaL.size();i++)
{
listaL.get(i).y=rand.nextInt(400)+20;
listaL.get(i).x=rand.nextInt(760)+20;
}
}
public GameView(Context context) {
super(context);
redPaint = new Paint();
redPaint.setAntiAlias(true);
redPaint.setColor(Color.RED);
circleX = 100;
circleY = 100;
radius = 30;
}
[user=439709]@override[/user]
protected void onDraw(Canvas canvas)
{
canvas.drawCircle(circleX, circleY, radius, redPaint);
redPaint.setStrokeWidth(1);
for (int i=0;i<listaL.size();i++){
canvas.drawRect(listaL.get(i).x,listaL.get(i).y,listaL.get(i).x+40,listaL.get(i).y+40,redPaint);
}
}
public boolean onTouchEvent(MotionEvent event)
{
int eventaction = event.getAction();
int x = (int)event.getX();
int y = (int)event.getY();
switch (eventaction)
{
case MotionEvent.ACTION_DOWN:
circleX = x;
circleY = y;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
break;
}
invalidate();
return true;
}
}
There is the Timer class in Java with a schedule method.
Check this: http://javarevisited.blogspot.de/2013/02/what-is-timer-and-timertask-in-java-example-tutorial.html
Okay thanks I'll try this.
However, is this how I am supposed to do it in android apps/games? I've read that I should measure deltatime so that on different devices it all runs equally fast. How do you make games such as linerunner where the obstacles move towards you?
I can make such a game in c++, where every time timer is executed x coordinates of obstacles are reduced by a constant so that it looks as if they were moving towards the player
Wampirate said:
Okay thanks I'll try this.
However, is this how I am supposed to do it in android apps/games? I've read that I should measure deltatime so that on different devices it all runs equally fast. How do you make games such as linerunner where the obstacles move towards you?
I can make such a game in c++, where every time timer is executed x coordinates of obstacles are reduced by a constant so that it looks as if they were moving towards the player
Click to expand...
Click to collapse
Of course, measuring the delta time and then calculating the movement is better if you want it for moving things.
I thought you want to do something every 2 or more seconds. In that case the delta time would be useless.
I want to do it every 1/60 of a second
Can you guide me how to implement the loop that measures the delta time and executes actions?
BTW: The method you gave the link to me works but its a bit laggy on my phone.
Wampirate said:
I want to do it every 1/60 of a second
Can you guide me how to implement the loop that measures the delta time and executes actions?
BTW: The method you gave the link to me works but its a bit laggy on my phone.
Click to expand...
Click to collapse
Here you go. That should work:
Code:
boolean running = true;
int oldTime = System.currentTimeInMillis();
int newTime;
while (running) {
newTime = System.currentTimeInMillis();
int deltaTime = newTime - oldTime;
//example for moving an image:
int step = speed * deltaTime;
//TODO: move the image
}
EDIT: Of course, put this into a new Thread:
Code:
Thread thread = new Thread() {
[user=439709]@override[/user]
public void run() {
//TODO: Code from above goes here
}
};
thread.start;
---------- Post added at 02:56 PM ---------- Previous post was at 02:47 PM ----------
This tutorial should be exactly what you are looking for: http://www.javacodegeeks.com/2011/06/android-game-development-tutorials.html
I used it, too.
However, using an engine like AndEngine makes every thing much easier.
I guess you should study Thread Synchronization using java that might just do the trick
As u mentioned you have C++ experience I strongly recomend you to code using NDK its lots faster and will give a vast platform via Open GL ES
Sent from my GT-S5302 using Tapatalk 2
sak-venom1997 said:
I guess you should study Thread Synchronization using java that might just do the trick
As u mentioned you have C++ experience I strongly recomend you to code using NDK its lots faster and will give a vast platform via Open GL ES
Sent from my GT-S5302 using Tapatalk 2
Click to expand...
Click to collapse
However, programming with the NDK is much harder. And there are less tutorials.
Thanks a lot guys! Especially you nikwen, answering to all my questions You both got thanks from me.
I will try and implement the delta time timer solution.
@sak-venom1997 As I wrote my C++ experience was only in 2d, allegro library, not a big deal. I didn't learn OpenGL.
I was drawing some bitmaps and a I can't understand one thing. I have a sprite, a png file which has all the poses of the character in it, and each one of them is 41x41 pixels. They are connected so that if I want to make a movement animation I have to show some of them one after another.
The thing is when I want to draw a piece of a bitmap, and my source rectangle is 41x41 and so is the destination rectangle, it cuts some of the character.
Why is it that I have to make my source rectangle 1,5 times bigger than it is in reality? Each pose in sprite is 41x41.
Not sure if you can follow what I mean ;D I use this drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint)
My sprite.png is 123 pixels high - and there are 3 rows of different stands, so obviously one is 41 pixels high. So is their width. Yet when I make my source rectangle 41x41 it only draws some of the stand. I have to say for example new Rect(0,0,62,62) to get the first full stand visible.
Wampirate said:
Thanks a lot guys! Especially you nikwen, answering to all my questions You both got thanks from me.
I will try and implement the delta time timer solution.
@sak-venom1997 As I wrote my C++ experience was only in 2d, allegro library, not a big deal. I didn't learn OpenGL.
I was drawing some bitmaps and a I can't understand one thing. I have a sprite, a png file which has all the poses of the character in it, and each one of them is 41x41 pixels. They are connected so that if I want to make a movement animation I have to show some of them one after another.
The thing is when I want to draw a piece of a bitmap, and my source rectangle is 41x41 and so is the destination rectangle, it cuts some of the character.
Why is it that I have to make my source rectangle 1,5 times bigger than it is in reality? Each pose in sprite is 41x41.
Not sure if you can follow what I mean ;D I use this drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint)
My sprite.png is 123 pixels high - and there are 3 rows of different stands, so obviously one is 41 pixels high. So is their width. Yet when I make my source rectangle 41x41 it only draws some of the stand. I have to say for example new Rect(0,0,62,62) to get the first full stand visible.
Click to expand...
Click to collapse
Welcome.
Are you sure that the original images are 41x41? That sounds like strange dimensions.
Could you please post some code? We cannot help you without your code (just the important parts).
Code:
characterGraphic=BitmapFactory.decodeResource(getResources(),R.drawable.sprite); // this is character sprite loading from drawable folder in res
charsrc = new Rect(62,62,124,124);
chardst = new Rect(100,charY-46,193,charY+45); // these are character source and destrination rectangles, my code is kinda messy but you can see my character source rectangle is 62x62 which is about 1,5 bigger than 41x41, and I see one full stand
// theres the whole painting method
protected void onDraw(Canvas canvas)
{
//canvas.drawCircle(circleX, circleY, radius, redPaint);
if (bLost)
{
redPaint.setTextSize(72);
redPaint.setColor(Color.rgb(0,0,0));
canvas.drawText("You died. Touch screen to return.", 100, 240, redPaint);
}
else
{
canvas.drawBitmap(backgroundGraphic, bgsrc,bgdst,null);
if (!onGround()) canvas.drawBitmap(characterGraphic,charjsrc,chardst,null);
else canvas.drawBitmap(characterGraphic, charsrc, chardst, null);
redPaint.setStrokeWidth(1);
for (int i=0;i<listaL.size();i++){
canvas.drawRect(listaL.get(i).x,listaL.get(i).y,listaL.get(i).x+30,listaL.get(i).y+30,redPaint);
}
}
}
Heres the link to the properties of sprite.png so you dont think I'm crazy.
Where it says 123 it is the height and 410 is the width.
You woudnt be restricted to only using OpenGl via NDK you can happily use any c/c++ libs
Not to mention the performance boost you get
Anyway its your call do what you.feel you're comfortable with
Sent from my GT-S5302 using Tapatalk 2
Wampirate said:
Code:
characterGraphic=BitmapFactory.decodeResource(getResources(),R.drawable.sprite); // this is character sprite loading from drawable folder in res
charsrc = new Rect(62,62,124,124);
chardst = new Rect(100,charY-46,193,charY+45); // these are character source and destrination rectangles, my code is kinda messy but you can see my character source rectangle is 62x62 which is about 1,5 bigger than 41x41, and I see one full stand
// theres the whole painting method
protected void onDraw(Canvas canvas)
{
//canvas.drawCircle(circleX, circleY, radius, redPaint);
if (bLost)
{
redPaint.setTextSize(72);
redPaint.setColor(Color.rgb(0,0,0));
canvas.drawText("You died. Touch screen to return.", 100, 240, redPaint);
}
else
{
canvas.drawBitmap(backgroundGraphic, bgsrc,bgdst,null);
if (!onGround()) canvas.drawBitmap(characterGraphic,charjsrc,chardst,null);
else canvas.drawBitmap(characterGraphic, charsrc, chardst, null);
redPaint.setStrokeWidth(1);
for (int i=0;i<listaL.size();i++){
canvas.drawRect(listaL.get(i).x,listaL.get(i).y,listaL.get(i).x+30,listaL.get(i).y+30,redPaint);
}
}
}
Heres the link to the properties of sprite.png so you dont think I'm crazy.
Where it says 123 it is the height and 410 is the width.
Click to expand...
Click to collapse
Thanks. Will check it later.
sak-venom1997 said:
You woudnt be restricted to only using OpenGl via NDK you can happily use any c/c++ libs
Click to expand...
Click to collapse
I didn't know about it. That's interesting, could you tell me a bit more about it? Where do I start ?
@nikwen Thanks
Wampirate said:
I didn't know about it. That's interesting, could you tell me a bit more about it? Where do I start ?
@nikwen Thanks
Click to expand...
Click to collapse
Sure
Ill fetch some links for you
EDIT :
http://stackoverflow.com/a/4920992/2408192
This should get you started
Sent from my GT-S5302 using Tapatalk 2
Another question emerged ;D
Code:
// its a function in my GameView class extending View
public void gameUpdate()
{
postInvalidate();
}
public class GameLoopThread extends Thread{
private boolean running;
public void setRunning()
{
running=!running;
}
[user=439709]@override[/user]
public void run() {
while (running)
{
GameView.gameUpdate();
}
}
}
And beneath the method from GameView class is my game loop thread class, how do I make the drawing initiate, because GameView.gameUpdate(); doesnt work, says I cant make a static reference to a non-static method, and when I change gameUpdate method to static then there is a problem with postInvalidate(); which cant be in a static method?
Wampirate said:
Another question emerged ;D
Code:
// its a function in my GameView class extending View
public void gameUpdate()
{
postInvalidate();
}
public class GameLoopThread extends Thread{
private boolean running;
public void setRunning()
{
running=!running;
}
[user=439709]@override[/user]
public void run() {
while (running)
{
GameView.gameUpdate();
}
}
}
And beneath the method from GameView class is my game loop thread class, how do I make the drawing initiate, because GameView.gameUpdate(); doesnt work, says I cant make a static reference to a non-static method, and when I change gameUpdate method to static then there is a problem with postInvalidate(); which cant be in a static method?
Click to expand...
Click to collapse
Replace GameView.gameUpdate();
With gameUpdate()
Sent from my GT-S5302 using Tapatalk 2
---------- Post added at 01:48 PM ---------- Previous post was at 01:45 PM ----------
Sry if GameThread is an inner class use GameView.this.gameUpdate()
Sent from my GT-S5302 using Tapatalk 2
sak-venom1997 said:
Replace GameView.gameUpdate();
With gameUpdate()
Sent from my GT-S5302 using Tapatalk 2
---------- Post added at 01:48 PM ---------- Previous post was at 01:45 PM ----------
Sry if GameThread is an inner class use GameView.this.gameUpdate()
Sent from my GT-S5302 using Tapatalk 2
Click to expand...
Click to collapse
What if it's not an inner class? Does it have to be? I never know when I can make another class file and use methods/variables from another class file
Because its not inner in my case, and alone gameUpdate(); doesnt work either.
Wampirate said:
What if it's not an inner class? Does it have to be? I never know when I can make another class file and use methods/variables from another class file
Because its not inner in my case, and alone gameUpdate(); doesnt work either.
Click to expand...
Click to collapse
If you intend to call it from GameView class use ..
Sent from my GT-S5302 using Tapatalk 2
---------- Post added at 01:58 PM ---------- Previous post was at 01:54 PM ----------
Add this field to GameThread
private GameView mGameView;
Add this constructor
public GameThread(GameView view)
{
mGameView = view;
}
Now you can call
mGameView.your public method(args)
Sent from my GT-S5302 using Tapatalk 2
Thanks a lot ! Not sure how this works but it does

[Q] Animation, ratation image

Hello everyone, I am new to android app making.
I would like to make an app that works like a spining bottle, Onclick start spinning and the the arrow stops in a radom place after random time.
So my picture spins but on click it stops at the start position.
Please help thank you !
I would like to show you my code but i can't sorry
ed37 said:
Hello everyone, I am new to android app making.
I would like to make an app that works like a spining bottle, Onclick start spinning and the the arrow stops in a radom place after random time.
So my picture spins but on click it stops at the start position.
Please help thank you !
I would like to show you my code but i can't sorry
Click to expand...
Click to collapse
Not sure anyone can help you if you dont really ask a question.... what you have currently reads like
I want to do "abcdefghijklmnopqrstuvwxyz" can someone tell me how ?
You should really be asking how do I do "a" but having some idea and learned the basics yourself ...then maybe someone could be constructive in helping
Ok, well how to I get an image view to stop rotating after a random time like 2 to 15 secs?
ed37 said:
Ok, well how to I get an image view to stop rotating after a random time like 2 to 15 secs?
Click to expand...
Click to collapse
using a timer/thread , never actually done something like that but I suspect you can get the frame that is currently being played and work out the rotation, stop the animation and set that rotation.
Or maybe even rotate the thing yourself and do all of it in onDraw of a view or by manually drawing it on a canvas/surface
Use a canvas object, like that you get a drawn object you can completely personalize. Also the rotation angle
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods (but only for the first time ;D)
---------------------------------
Gesendet von Tapatalk
Here is what I have so far
Code:
public class SpinFragment extends Fragment {
public SpinFragment(){}
private Button btnRotate, btnstop;
private ImageView imgview;
AnimationListener listener;
Random rand = new Random();
int milis = (rand.nextInt(10) + 2)*1000;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_spin, container, false);
TextView txt = (TextView) rootView.findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/harabara.ttf");
txt.setTypeface(font);
final ImageView iv = (ImageView) rootView.findViewById(R.id.image_arrow);
btnRotate = (Button) rootView.findViewById(R.id.start);
btnstop = (Button) rootView.findViewById(R.id.stop);
final Animation rotation = AnimationUtils.loadAnimation(getActivity(), R.anim.button_rotate);
rotation.setRepeatCount(Animation.INFINITE);
rotation.setAnimationListener(listener);
btnRotate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
iv.startAnimation(rotation);
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
iv.clearAnimation();
}
}, milis);
}
});
return rootView;
}
}

Categories

Resources