I'm developing a APP to android using LIGBDX, i need to get the MAC ADDRES or IMEI or any other unique code from the phone. When using NetworkInterface from Java.net works fine on Desktop project, but on Android it doesnt work, so i saw on the internet the WifiManger,
is a API (i guess) from android.
WifiManager wifiMan = (WifiManager) this.getSystemService( Context.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
String macAddr = wifiInf.getMacAddress();
And it seens it works, BUT i'm using LIBGDX and i not getting to import Android.Net on my project, saw one guys talking when i try to references pure android on LIbgdx i have to work only on android not in Core, but i dont know how to do this.
Maybe add Wifimanager.java into library i tried that but not work.
Note: i am using Gdx Net and edited the manifest, i am dowloading and send data from iternet, i cant do only the mac part
Try this:
1)
Declare an Interface in your core project with a method to retrieve the number you want.
public interface IActivityRequestHandler {
public String getUniqueId();
}
In your core project, add a constructor to your Game class that takes a IActivityRequestHandler as a parameter:
public abstract class MyGame extends Game {
...
public IActivityRequestHandler handler;
...
public MyGame(IActivityRequestHandler handler){
this.handler = handler;
}
You will use "handler" to call platform specific methods.
2)
Make the android MainActivity implement this interface and write the methood to return the value you need.
3) In your Android MainActivity, when you instantiate your AndroidGame, pass the MainActivity as a parameter:
public class MainActivity extends AndroidApplication implements IActivityRequestHandler{
...
ApplicationListener game;
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
game = new AndroidMyGame(this);
...
}
public String getUniqueId(){
return uniqueId;
}
...
}
4) Now when you need the id from the core you call: handler.getUniqueId() (from MyGame class)
This will be calling the method on your Android MainActivity if you are running the game from an Android Device.
Important notes:
1) This should work if you don't have any contraints regarding the UI Thread in Android.
This is, to return a value it should work. If you call anything that can only be called in the UIThread this won't work and, aditionally, you have to use a Handler to communicate between threads.
2) Your Desktop version will also have to implement IActivityRequestHandler.
3) Getting a unique id in Android devices is something I haven't found a nice solution yet.
a) Tablets, unless they have a phone line, don't have IMEI or telephone number.
b) MAC Addresses are not unique (you have 3g, wifi, bluetooth) and sometimes are not available for example if wifi is turned off.
4) You might be better off generating a unique id yourself and storing it on the phone.
google "Java UUID".
Related
I am trying to use the Activity Result APIs to handle the picking of a single photo for an app I am developing. I am trying to use one of the predefined contracts to keep things simple. So, I am attempting to use the ActivityResultContracts.PickVisualMedia() contract.
I am setting the Activity Result Launcher up as follows:
private ActivityResultLauncher<PickVisualMediaRequest> pickVisualMediaActivityResultLauncher;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
pickVisualMediaActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.PickVisualMedia(),
this::onPickVisualMediaActivityResult
);
}
And I am attempting to construct a PickVisualMediaRequest and launch the Activity Result Launcher here:
private void onSelectNewPhotoButtonClick() {
PickVisualMediaRequest request = new PickVisualMediaRequest.Builder()
.setMediaType(new ActivityResultContracts.PickVisualMedia.ImageOnly())
.build();
pickVisualMediaActivityResultLauncher.launch(request);
}
Issue is that Android Studio is complaining about ActivityResultContracts.PickVisualMedia.ImageOnly() not having proper visibility to be used, even though it is a valid VisualMediaType and the docs imply that it should be used this way:
I can't really find any code samples on this particular scenario. Am I missing something? Does the API have a visibility defect or am I just dumb today?
After some help from CommonsWare, I determined that setMediaType() accepts a Kotlin object instance. So, the above bad function I had should be:
private void onSelectNewPhotoButtonClick() {
ActivityResultContracts.PickVisualMedia.VisualMediaType mediaType = (ActivityResultContracts.PickVisualMedia.VisualMediaType) ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE;
PickVisualMediaRequest request = new PickVisualMediaRequest.Builder()
.setMediaType(mediaType)
.build();
pickVisualMediaActivityResultLauncher.launch(request);
}
Android Studio complains about the type casting, but the code does compile and work as expected. Very bizarre.
I'm currently working with the enableReaderMode function. I tried out the code from this stack: https://stackoverflow.com/a/64921434/2373819
and it worked perfectly.
Now my Issue is, I want to run this function outside of the Activity. So my MAIN Activity calls a function from an outside Class e.g. from a Android Library. Passing the Context Object from my MAIN Activity to the outside Class enables me to use the nfcAdapter.enableRederMode function.
Now the issue is that the onTagDiscovered function is never used. This callback function runs on a separated Thread and is being skip.
Is there a way to build a Listener or "join" the Thread so the process only continues once the onTagDiscovered function is used.
In this code example the getNFCMessage runs through without errors but doesn't listen or wait until the Tag is discovered.
public class NFCExample implements NfcAdapter.ReaderCallback {
public void getNFCMessage(NfcAdapter nfcAdapter, Activity activity) {
if (nfcAdapter != null) {
Bundle options = new Bundle();
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
nfcAdapter.enableReaderMode(activity,
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
#Override
public void onTagDiscovered(Tag tag) {
System.out.println("Tag Discovered");
}
}
This might be a helpful indication for everyone looking for something simliar. Link
I found this public repo of a flutter plugin which uses the NfcEnableReaderMode function and the Callback onTagDiscovery in a non Activity environment.
It looks like their using a sort of listener to detect the Callback functions once they are used.
BaseActivity.java
Language switching
Intent
OnClickListener
Error demo
No error message was prompted.
You are using old style of language switching which were deprecated and removed after releasing android 8, It completely get removed. However, if you want to use your application for android prior to 26, you have to change your code on language switching Image as follow:
Configuration config = new Configuration(resources.getConfiguration());
New instance of Configuration have to be passed to resources.updateConfiguration();. above line will solve your problem.
On the other hand if you want to publish your application for higher api level, follow link below:
#Override
protected void attachBaseContext(Context newBase){
Configuration configuration = new Configuration(newBase.getResoureces().getConfiguration());
configuration.setLocale(/* selected locale which you have to get from user or your app configuration*/);
super.attachBaseContext(newBase.createConfigurationContext(configuration));
}
Override above method for each activity which you have declared;
This might be a very naive question but I can't get this java.lang.Exception error to go away. I also just started learning java and android so... this might be an easy problem to solve.
So I have a main activity in android and I want to implement a weka ml classifier within the app. Right now I'm just trying to load some data.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ml_classifiers ml_object = new ml_classifiers();
int number = ml_object.loadData();
Trying to load data...
public class ml_classifiers {
public int loadData() {
ConverterUtils.DataSource source = new ConverterUtils.DataSource("C:/Users/Seth/Desktop/iris.arff");
Instances data = source.getDataSet();
int num = data.numInstances();
return num;
}
}
Why does java.lang.exception occur?
Why does java.lang.exception occur?
In the future, when you encounter crashes, use LogCat to examine the Java stack trace associated with the crash. If you do not understand the stack trace or otherwise cannot identify the problem, and you want help here, post the stack trace along with the code. As it stands, we have to guess exactly what is going wrong in your app.
In this case, while you may be crashing elsewhere, you will definitely crash with:
ConverterUtils.DataSource source = new ConverterUtils.DataSource("C:/Users/Seth/Desktop/iris.arff");
assuming that this is code in your Android app.
You are attempting to read data from C:/Users/Seth/Desktop/iris.arff. That is a path to a file on a Windows machine. Android is not Windows. There are ~2 billion Android devices in use, and none of them have access to files on your Windows' machine's desktop.
You need to get this data onto the Android device, such as:
by putting it in the assets/ directory in your module (to package it with your app), then using AssetManager to get an InputStream on that asset, hopefully passing that directly to ConverterUtils.DataSource
downloading the file from the Internet, perhaps into internal storage (e.g., getCacheDir())
expecting the user to copy the file onto their device by hand, such as via external storage
I'm trying to make an Activity Transition using Shared Elements on a pre-Lollipop device (4.x). Is it possible? So far, I'm trying this:
public class RewardDetail extends ActionBarActivity {
#Override
public void onCreate(final Bundle savedInstanceState) {
...
ViewCompat.setTransitionName(imageView, TRANSITION_NAME);
}
...
public static void launch(ActionBarActivity activity, View transitionView, WelcomeReward detailData) {
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, transitionView, TRANSITION_NAME);
Intent intent = new Intent(activity, RewardDetail.class);
intent.putExtra(PARAM_DATA, detailData);
ActivityCompat.startActivity(activity, intent, options.toBundle());
}
}
called by:
#Override
public void onClick(final View v) {
int position = recyclerView.getChildPosition(v);
WelcomeReward welcomeReward = data.get(position);
RewardDetail.launch(WelcomeRewardActivity.this, v.findViewById(R.id.reward_view), welcomeReward);
}
But it results in a "regular" transition (no shared element). Any ideas?
EDIT
According to this video, it could be done:
https://www.youtube.com/watch?v=RhiPJByIMrM&index=8&list=WL
Is there a library already implementing this for pre Lollipop ?
No, Activity/Fragment Transitions are not possible on pre-Lollipop devices. According to the documentation:
Start an activity with additional launch information, if able.
In Android 4.1+ additional options were introduced to allow for more control on activity launch animations. Applications can use this method along with ActivityOptionsCompat to use these animations when available. When run on versions of the platform where this feature does not exist the activity will be launched normally.
See also George Mount's answer to this StackOverflow question.
You can check out this library for activity and fragment transitions for pre lollipop devices
dependencies {
compile 'com.albinmathew:PreLollipopTransition:1.1.2'
}
https://github.com/albinmathew/PreLollipopTransition
Although the fancy Lollipop Activity/Fragment transitions are not available pre-Lollipop (without the use of a 3rd party library), you can still override the animation used to transition between activities.
Just before/after you start invoke startActivity() you can make a call to [Activity.overridePendingTransition](http://developer.android.com/reference/android/app/Activity.html#overridePendingTransition(int, int)). When you leave your activity, call the same method.
Similarly you can use ActivityOptionsCompat to define a custom animation to use during a transition.
ActivityOptionsCompat opts =
ActivityOptionsCompat.makeCustomAnimation(getActivity(), R.anim.in, R.anim.out);
startActivity(intent, opts.toBundle());
There is a support library, but it does not support (all) transitions on Android versions below 5.0. There are however some alternatives:
Unofficial Compatibility libraries https://github.com/andkulikov/transitions-everywhere
https://github.com/takahirom/PreLollipopTransition
https://github.com/lgvalle/Material-Animations
Android KitKat http://www.doubleencore.com/2013/11/new-transitions-framework/ and a
sample found in your SDK samples folder.
Posted earlier to a duplicate of this question here: https://stackoverflow.com/a/27344471/1683141