LibGDX - check if compass needs calibration - libgdx

How to check if compass is calibrated well in LibGDX (on Android). I've found how to do it on native Android:
In Android can I programmatically detect that the compass is not yet calibrated?
But couldn't find if that's implemented in LibGDX.

What you want is described in the wiki article Interfacing with platform specific code. LibGDX doesn't have any functionality for it because it isn't common and it doesn't make any sense for other backends.
In the core module you'll have something like this:
public interface GameListener {
void calibrateCompassIfNeeded()
}
public class Application extends ApplicationAdapter {
private GameListener listener;
public Application(GameListener listener) {
this.listener = listener;
}
#Override
public void create() {
// Call listener.calibrateCompassIfNeeded() whenever needed.
}
public void onCompassChanged(float[] values) {
// Do something...
}
}
And in the android module:
public class AndroidLauncher extends AndroidApplication implements GameListener, SensorEventListener {
private static final int COMPASS_ACCURACY_UNKNOWN = -1;
private Application app;
private int compassAccuracy = COMPASS_ACCURACY_UNKNOWN;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor compassSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
sensorManager.registerListener(this, compassSensor, SensorManager.SENSOR_DELAY_GAME)
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
app = new Application(this);
initialize(app, config);
}
#Override
public void calibrateCompassIfNeeded() {
if (compassAccuracy != COMPASS_ACCURACY_UNKNOWN && compassAccuracy < SENSOR_STATUS_ACCURACY_MEDIUM) {
// Calibrate only if accuracy is below medium.
// Show whatever is needed so user calibrates the compass.
}
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
app.onCompassChanged(event.values);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
compassAccuracy = accuracy;
}
}
I haven't tried it and I have never used the compass before but I'm pretty sure this will work fine.

Related

Libgdx different way for fling gesture detection

In my game I implement fling gesture detection. Everything work fine , but I want to modify fling detection
From documentation for fling: https://github.com/libgdx/libgdx/wiki/Gesture-detection
fling: A user dragged the finger across the screen, then lifted it. Useful to implement swipe gestures.
I want to modify this and fling to work without lifting touch, only when user drag some distance not lifting it.
Here is my code:
public class SimpleDirectionGestureDetector extends GestureDetector {
public interface DirectionListener {
void onLeft();
void onRight();
void onUp();
void onDown();
}
public SimpleDirectionGestureDetector(DirectionListener directionListener) {
super(new DirectionGestureListener(directionListener));
}
private static class DirectionGestureListener extends GestureAdapter{
DirectionListener directionListener;
public DirectionGestureListener(DirectionListener directionListener){
this.directionListener = directionListener;
}
#Override
public boolean fling(float velocityX, float velocityY, int button) {
if(Math.abs(velocityX)>Math.abs(velocityY)){
if(velocityX>0){
directionListener.onRight();
}else{
directionListener.onLeft();
}
}else{
if(velocityY>0){
directionListener.onDown();
}else{
directionListener.onUp();
}
}
return super.fling(velocityX, velocityY, button);
}
}
}
public SimpleDirectionGestureDetector gestureDetector = new SimpleDirectionGestureDetector(
new SimpleDirectionGestureDetector.DirectionListener() {
#Override
public void onUp() {
onUpSwipe();
}
#Override
public void onRight() {
onRightSwipe();
}
#Override
public void onLeft() {
onLeftSwipe();
}
#Override
public void onDown() {
onDownSwipe();
}
});
Any help would be appreciated
Thanks

JavaFX - Object with Constructor

I'm working with JavaFX and my Idea was to have my own JavaFX Object which I can create like this:
public class Main {
public static void main(String[] args) throws Exception
TSS t = new TSS();
}
}
My JavaFX Main class looks like this:
public class TSS extends Application {
private Scene scene;
private Stage stage;
public void redrawGui() throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("tss.fxml"));
scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
#Override
public void start(Stage stage) throws Exception {
this.stage = stage;
this.stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("tss.fxml"));
scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Normally the main method in TSS is called and its working but I want to create my own TSS-Object in its constructor, it creates the Gui.
Does anyone know how to do this?
In JavaFX, you should (typically) think of the Application subclass as the "main" class (i.e. the application entry point) and its start(...) method as the replacement for the main(...) method in a "traditional" Java Application.
If you want to factor your code out into a class that is separate from the Application subclass (which is generally a good idea), then you can do so, but you need to just reorganize things a little:
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
TSS t = new TSS();
Scene scene = new Scene(t.getView());
primaryStage.setScene(scene);
primaryStage.show();
}
// not really needed in Java 8, but some IDEs need this to execute this class:
public static void main(String[] args) { launch(args);}
}
And then you can define your own class as follows:
public class TSS {
private Parent view ;
private TssController controller ; // controller class specified in FXML
public TSS() throws Exception {
load();
}
private void load() throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("tss.fxml"));
view = loader.load();
controller = loader.getController();
}
public Parent getView() {
return view ;
}
public void restartGui() throws Exception {
Scene scene = view.getScene();
Stage stage = null ;
if (scene != null) {
Window window = scene.getWindow();
if (window instanceof Stage) {
stage = (Stage) window ;
}
}
load();
if (stage != null) {
stage.setScene(new Scene(view));
}
}
public void doOtherStuff() {
controller.doSomething();
}
}
You could also consider implementing the TSS class above using the custom control pattern described in the FXML documentation. I marginally prefer the style I showed here, as it favors composition over inheritance, but it is a minimal difference.

My Libgdx game slow when integrated Admob

I am a new game developing with libgdx. I have a problem with Admob ads. When I call "adView.loadAd(adRequest);" my game is slowl, when I start game, FPS ~ 60 , when I call adView.loadAd(adRequest) my game is slowly FPS ~ 30.
Here is my
public class MainActivity extends AndroidApplication implements IActivityRequestHandler {
protected AdView adView;
AdRequest adRequest;
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
protected Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_ADS: {
System.out.println("SHOW ADVIEW");
adView.setVisibility(View.VISIBLE);
break;
}
case HIDE_ADS: {
adView.setVisibility(View.GONE);
break;
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libgdx View
View gameView = initializeForView(new MyGdxGame(this), false);
// Create and setup the AdMob view`enter code here`
adView = new AdView(this, AdSize.BANNER, "XXXXXX"); // Put in your
// secret key
// here
adRequest = new AdRequest();
adView.loadAd(adRequest);
// adView.loadAd(new AdRequest());
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
}
// This is the callback that posts a message for the handler
#Override
public void showAds(boolean show) {
handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}
}
I read topic Using interstitials from Admob in a Libgdx game for Android, it's slow when dismissing it
but not solution
Please help me if you have a solution.
This is a known issue and at the moment you cant change it.
Post at the libgdx Forum
It has nothing todo with your code. I think

Basic JUnit test for JavaFX 8

I want to create basic JUnit test for JavaFX 8 application. I have this simple code sample:
public class Main extends Application {
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Tabs");
Group root = new Group();
Scene scene = new Scene(root, 400, 250, Color.WHITE);
TabPane tabPane = new TabPane();
BorderPane borderPane = new BorderPane();
for (int i = 0; i < 5; i++) {
Tab tab = new Tab();
tab.setText("Tab" + i);
HBox hbox = new HBox();
hbox.getChildren().add(new Label("Tab" + i));
hbox.setAlignment(Pos.CENTER);
tab.setContent(hbox);
tabPane.getTabs().add(tab);
}
// bind to take available space
borderPane.prefHeightProperty().bind(scene.heightProperty());
borderPane.prefWidthProperty().bind(scene.widthProperty());
borderPane.setCenter(tabPane);
root.getChildren().add(borderPane);
primaryStage.setScene(scene);
primaryStage.show();
}
}
I only have this code so far:
import javafx.application.Application;
import javafx.stage.Stage;
import org.junit.BeforeClass;
public class BasicStart extends Application {
#BeforeClass
public static void initJFX() {
Thread t = new Thread("JavaFX Init Thread") {
#Override
public void run() {
Application.launch(BasicStart.class, new String[0]);
}
};
t.setDaemon(true);
t.start();
}
#Override
public void start(Stage primaryStage) throws Exception {
// noop
}
}
Can you tell me how I can create JUnit test for the above code?
I use a Junit Rule to run unit tests on the JavaFX thread. The details are in this post. Just copy the class from that post and then add this field to your unit tests.
#Rule public JavaFXThreadingRule javafxRule = new JavaFXThreadingRule();
This code works for both JavaFX 2 and JavaFX 8.
The easiest aproach is the following:
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.Stage;
import org.junit.Test;
public class BasicStart {
#Test
public void testA() throws InterruptedException {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
new JFXPanel(); // Initializes the JavaFx Platform
Platform.runLater(new Runnable() {
#Override
public void run() {
new Main().start(new Stage()); // Create and
// initialize
// your app.
}
});
}
});
thread.start();// Initialize the thread
Thread.sleep(10000); // Time to use the app, with out this, the thread
// will be killed before you can tell.
}
}
Hope it helps!
Based on Brian Blonski 's answer I created a JUnit-Testrunner, that does essentially the same thing, but is a bit simpler to use in my opinion.
Using it, your test would look like this:
#RunWith( JfxTestRunner.class )
public class MyUnitTest
{
#Test
public void testMyMethod()
{
//...
}
}

JPopupMenu doesn't dissapear/move when minimising/moving the JFrame it is in

I am making an mp3 player, with several JLists in my JFrame. When I right click on a JList item, a popup with some options for that song appears. But when this popup is visible, and I minimise my JFrame, this popup stays visible! Also, when the popup is visible, and I drag my JFrame to somewhere else on the screen, the popup stays on it's original position (so it does not stay on the same position relative to the JFrame)... Can someone please help me out with this? I tried to strip down this class as much as possible :)
I would be really grateful if someone could help me out !!
Joe
public class playListPanel extends JPanel implements MouseListener {
private DefaultListModel model;
private Interface interFace;
private JList list;
private boolean emptyPlaylist;
private ArrayList<Song> currentPlayList;
private Song rightClickedSong;
private JPopupMenu popup;
private Point panelLocation;
public playListPanel(Interface interFace) // Interface extends JFrame,
// playListPanel is a part of
// this JFrame.
{
this.interFace = interFace;
this.panelLocation = new Point(559, 146);
setBackground(SystemColor.controlHighlight);
setBorder(new TitledBorder(null, "", TitledBorder.LEADING,
TitledBorder.TOP, null, null));
setBounds((int) panelLocation.getX(), (int) panelLocation.getY(), 698,
368);
setLayout(null);
currentPlayList = new ArrayList<Song>();
model = new DefaultListModel();
list = new JList(model);
list.setVisible(true);
list.addMouseListener(this);
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setBounds(5, 5, 688, 357);
add(scrollPane);
emptyPlaylist = true;
}
private void openMenuPopup(Point point)
{
removePopup();
popup = new JPopupMenu();
int x = (int) point.getX();
int y = (int) point.getY();
popup.setLocation((int) (x+panelLocation.getX()),(int) (y+panelLocation.getY()));
//popup.setLabel("popup voor playlist");
JMenuItem removeSong;
popup.add(removeSong = new JMenuItem("Remove Song from Playlist", new ImageIcon("image.jpg")));
ActionListener menuListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(event.getActionCommand().equals("Remove Song from Playlist"))
{
System.out.println("Remove Song from Playlist");
interFace.getPlaylistManager().removeOneSong(rightClickedSong);
removePopup();
}
};
//ADD THE LISTENERS TO THE MENU ITEMS
removeSong.addActionListener(menuListener);
popup.setVisible(true);
}
public void removePopup()
{
if(popup!==null)
{
popup.setVisible(false);
System.out.println("popup removed");
}
}
private int getRow(Point point) {
return list.locationToIndex(point);
}
public void refreshPlayList(ArrayList<Song> playlist) {
this.currentPlayList = playlist;
model.clear();
for (Song song : playlist) {
model.add(model.getSize(), song.getPlaylistString());
}
list.setVisible(true);
}
public void highlightSong(int index) {
list.setSelectedIndex(index);
}
public int getRowOfList(Point point) {
return list.locationToIndex(point);
}
#Override
public void mouseClicked(MouseEvent e) {
interFace.getPlaylistManager().doubleClickOnPlaylist(e);
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
rightClickedSong = currentPlayList.get(getRow(e.getPoint()));
openMenuPopup(e.getPoint());
System.out.println("should open popup at "
+ e.getPoint().toString());
}
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
There are some basic flaws in the way you are handling click for showing popup.
It is not advisable to call popup.setVisible in simple scenarios like this. Instead, you may rely on its default behavior. Also, better to use e.isPopupTrigger() than to check SwingUtilities.isRightMouseButton(e) to show popup.
You may do something like the following :
//at classlevel,
private JPopupMenu popup = new JPopupMenu();
//create a Popuplistener
PopupListener pl = new PopupListener();
list.addMouseListener(pl);
//Implementation of your popuplistener
class PopupListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger())
//e.getSource - and construct your popup as required.
//and then.
popup.show(((JApplet) e.getComponent()).getContentPane(), e
.getX(), e.getY());
}
}