Import my custom class and call its method?

I created a custom class for my Android project called Sounds. I want to be called out of my activity. The contents of my class are as follows:

package com.mypackage;

import java.util.HashMap;

import android.content.Context;
import android.media.SoundPool;

public class Sounds {

private static boolean sound = true;

private static final int FLIP_SOUND = 1;

private static Context context;
private static SoundPool soundPool;
private static HashMap<Integer, Integer> soundPoolMap;

public static void initSounds() {
    soundPoolMap.put(FLIP_SOUND, soundPool.load(context, R.raw.flip, 1));
}

public static void playFlip() {
        soundPool.play(soundPoolMap.get(FLIP_SOUND), 1, 1, 1, 0, 1);
}

public static void setSound(Boolean onOff) {
    sound = onOff;
}
}

In my main Activity class, I tried to import the class by instantiating it, but I think I just don’t understand how this is done. Can someone point me in the right direction?

+5
source share
4 answers

Edited: from class Activity:

private Sounds s;

@Override
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);        
        s = new Sounds(this);
        s.initSounds();
}

You can also send the context with the constructor to your own class.

Delete static variables and methods:

public class Sounds {

private boolean sound = true;

private int FLIP_SOUND = 1;

private Context context;
private SoundPool soundPool;
private HashMap soundPoolMap;

public Sounds(Context context){
   this.context = context;
   soundPoolMap = new HashMap();
   soundPool = new SoundPool(0, AudioManager.STREAM_MUSIC, 0);
}

public void initSounds() {
   soundPoolMap.put(FLIP_SOUND, soundPool.load(context, R.raw.flip, 1));
}

public void playFlip() {
    soundPool.play(soundPoolMap.get(FLIP_SOUND), 1, 1, 1, 0, 1);
}

public void setSound(Boolean onOff) {
   sound = onOff;
}
}
+9
source

. Android , WebInterface.

Shane Oliver .

Activity:

Private JavaScriptInterface myJavaScriptInterface;
myJavaScriptInterface.Toastshow("Hi EveryOne");

:

JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(this);

JavaScriptInterface:

 public class JavaScriptInterface {

    Context myContext;

    //Instanciar o interface e definir o conteudo 
    JavaScriptInterface(Context c) {
        myContext = c;
    }


    public void Toastshow(String toast_msg)
    {


        Toast.makeText(myContext, toast_msg, Toast.LENGTH_LONG).show();
    }
}

, ...

+2

Try

Sounds s = new Sounds();
s.initSounds();
s.playFlip();
s.setSound(true);
+1

static. , Sounds.initSound() . , , . static ( FLIP_SOUND), , .

+1

All Articles