Search code examples
javaandroidandroid-activityandroid-custom-viewsoundpool

How to use soundPool in a custom view class?


I am making a simple demo which with a custom view class extends the view which want to shows random circle with random color who can appear randomly on a canvas.

I have already make the random issue and set a onTouchEvent to judge whether the Click is in the circle,if the circle was clicked then the app plays a short sound. But at the step,I met some problems.

I uses the SoundPool to get the music played,but since it can not be used under customview(Mine is MyView.java)So I put it back to the MainActivity.java under the onCreate function under MainActivity extends Activity,after the setting,the functions seems ok but I still can not use soundpool.play in my customview.java.

How to fix it?I am just a rookie so I am still not clear about all these things,can you help me?

The code is here(MainActivity.java)

package com.example.luckbag2;

import java.util.HashMap;
import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;

public class MainActivity extends Activity {
private SoundPool soundPool;
private HashMap<Integer,Integer> soundMap= new HashMap<Integer,Integer>();

@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState)
{
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    MyView v = new MyView(getApplicationContext());
    setContentView(v);           
    soundPool =new SoundPool(10,AudioManager. STREAM_SYSTEM,5);
    soundMap.put(1,soundPool.load(this,R.raw.collide,0));    
}
public SoundPool getSoundPool() {
    return soundPool;
}
public void setSoundPool(SoundPool soundPool) {
    this.soundPool = soundPool;
}
public HashMap<Integer,Integer> getSoundMap() {
    return soundMap;
}
public void setSoundMap(HashMap<Integer,Integer> soundMap) {
    this.soundMap = soundMap;
}
}

Myview.java

package com.example.luckbag2;

import java.util.HashMap;
import java.util.Random;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;


@SuppressWarnings("deprecation")
@SuppressLint({ "DrawAllocation", "ClickableViewAccessibility" }) class MyView extends View
{
 private Handler mHandler;

 private int mColor;

 private float cx;

 private float cy;

 private float radius;

 private float x;

 private float y;

 private int score;


public MyView(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
    mHandler = new Handler(getMainLooper());

    setBackgroundColor(Color.WHITE);

    Thread mThread = new Thread(new Runnable() {

        @Override
        public void run()
        {
            // TODO Auto-generated method stub
            MyView.this.invalidate();
            mHandler.postDelayed(this, 500);
        }
    });
    mThread.start();


}
private Callback getMainLooper() {
    // TODO Auto-generated method stub
    return null;
}
@Override
protected void onDraw(Canvas canvas)
{

    int w = this.getWidth();
    int h = this.getHeight();
    Log.d("CustomView", "w = " + w + ", h = " + h);

    // TODO Auto-generated method stub
    super.onDraw(canvas);
    update();
    Paint p = new Paint();
    p.setColor(mColor);
    canvas.drawCircle(cx, cy, radius, p);

}

private void update()
{
    Random random = new Random();
    cx =(float)(250+random.nextInt(580));        
    cy =(float)(250+random.nextInt(1057));        
    radius =(float)( 100 + random.nextInt(150));      

    int r = random.nextInt(256);
    int g= random.nextInt(256);
    int b = random.nextInt(256);
    mColor = Color.rgb(r, g, b);                   
}

protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
}

public boolean onTouchEvent(MotionEvent event){

    x = event.getX();
    y = event.getY();

    if ((x - cx) * (x - cx) + 
            (y - cy) * (y - cy) < radius * radius) { 
            Log.d("CustomView", "circle got clicked");
            SoundPool.play(SoundPool.get(1), 1,1,0,0,1);

    }

    return false;

}

public int getScore() {
    return score;
}
public void setScore(int score) {
    this.score = score;
}

}


Solution

  • To call soundPool.play from MyView class pass MainActivity class context to using MyView constructor :

    MainActivity mActivity;
    public MyView(Context context,MainActivity mActivity) {
        super(context);
    this.mActivity=mActivity;
    
    }
    

    From MainActivity create MyView class object as:

    MyView v = new MyView(getApplicationContext(),this);
    

    Now use mActivity for accessing methods from MainActivity :

    To get SoundPool object in MyView class:

    SoundPool soundPool= mActivity.getSoundPool();
    

    Use soundPool object to call play method :

    SoundPool soundPool= mActivity.getSoundPool();
    soundPool.play(mActivity.getSoundMap().get(1), 1,1,0,0,1)