AS3 - Loading Image Coordinates from URL - android

I am developing an Android App in Air for Android using Flash Pro CC & I am tired of pushing updates all the time to change a spawn location for an image that needs to move every few days to a specific location. I won't know the location until just minutes before the update needs to be pushed & it would be much faster to simply have the app load the spawn coordinates for the image upon launch from my website in a .txt file. I would need something where I just type the X and Y coordinates in a file & then the information is loaded and AS3 spawns the image at those coordinates. If no coordinates are available in the text file (as 5 days of the week there won't be), I need a different image to be displayed wherever I place it. I will probably just have a separate frame for that though.
Any help is greatly appreciated & I'd prefer it if the image can be used in a motion tween but if not then I will work something out.
NOTE: I am new to AS3 coding but I have Flash itself figured out for animating with the timeline.

Have a look at URLRequest and URLLoader for retrieving the data. For spawning the image at a specific location, consider just moving it instead; Any object on stage is a DisplayObject, and DisplayObjects have properties x and y. For swapping out the images, look at DisplayObjectContainer, specifically the functions DisplayObjectContainer.addChild(child:DisplayObject) and DisplayObjectContainer.removeChild(child:DisplayObject). I have provided links to the documentation for each of the relevant functions.
If the update is on a daily basis, have a look at the Date class too - that will allow you to find out what date it is and whether you need to make an url request to load the textfile to display the image.
If you have any specific questions regarding the use of these classes, I think it's best if you make a new question with a link back to this one for context. You're good with English, not so good with AS3 (as you say), so I could explain the relevant bits where needed, but it would be a long and complex story if I were to explain this entire functionality in one go. ... I think you'll find that these class names will make googling easier too.
I expect that you'll have to use an URLLoader with an URLRequest to load the textfile, then depending on the results, display the image by adding it to stage via addChild if it's not there yet, and then setting its x and y values. You'll have to use the Date class to check whether you need to make a new request every time the user starts the application or does some specific action.

I have the finished code here. loadURL is the Document Class loaded by Flash. Everything works great!
package {
// IMPORTS EVENTS USED
import flash.display.MovieClip;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.UncaughtErrorEvent;
import flash.events.ErrorEvent;
import flash.events.Event;
// DECLARES VARIABLES
public class loadURL extends MovieClip {
public var Xurl:String = "URL GOES HERE";
public var Yurl:String = "URL GOES HERE";
public var URLloaderX:URLLoader = new URLLoader();
public var URLloaderY:URLLoader = new URLLoader();
public var marker:Marker = new Marker();
public var gone:Gone = new Gone();
public var connectionerr:ConnectionErr = new ConnectionErr();
// CODE EXECUTED UPON LAUNCH
public function loadURL() {
// constructor code
trace("Loaded");
URLloaderX.addEventListener(Event.COMPLETE, completeHandlerX);
URLloaderX.load(new URLRequest(Xurl));
URLloaderY.addEventListener(Event.COMPLETE, completeHandlerY);
URLloaderY.load(new URLRequest(Yurl));
loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError);
}
function completeHandlerX(event:Event):void
{
if(URLloaderX.data == null||URLloaderX.data==(""))
{addChild(gone)}
else{addChild(marker);marker.x = (URLloaderX.data)}
}
function completeHandlerY(event:Event):void
{
if(URLloaderY.data == null||URLloaderY.data==("")){}
marker.y = (URLloaderY.data)
}
private function onUncaughtError(e:UncaughtErrorEvent):void //Checks for no internet connection
{
e.preventDefault(); //leave this
// RESULT OF NO INTERNET HERE
addChild(connectionerr);
}
}
}

Related

Firebase SDK Auth Package Trouble with Automatically Loading Scene Once Authenticated Unity

I am stuck with a functionality of the Firebase SDK (Auth package) regarding the Scenes and it's integration. Here's how they work:
1st: Loading Scene
Here, I just added the FirebaseInit code EXACTLY as suggested by Patrick, which it's only function is to call the next scene (Login/Register) once everything loads correctly.
2nd: Login/Register Scene
Here I do all the Login AND ALSO the register logic. I set up a button that alternates between the two (Activating the respective parent gameObject within the Canvas). Once the user log's in, the 3rd scene comes into play.
3rd: App's Main Screen Scene
Main Screen of the app, where the user can LOGOUT and return to the Login Scene.
Problem
I added the 'LoadSceneWhenUserAuthenticated.cs' in the 2nd Scene, and it works (kind of).
It actually does what it is supposed to. If I log in, quit the game without loging out, and open it again, it does come back directly to the 3rd scene. BUT some things are happening and they aren't supposed to.
First
When I Sign Up a user, I call the method 'CreateUserWithEmailAndPasswordAsync()'. Once it completes, it should activate the login screen and stay there, waiting for the user to fill in the password, but the 'FirebaseAuth.DefaultInstance.StateChanged' comes into play and forces the 3rd screen to be loaded, skipping several other steps that should be taken (email registration for example).
Second
As I mentioned in the end of number 1 above, if I try to log in to an account that does not have it's email verified, it works! (due to the 'LoadSceneWhenUserAuthenticated.cs' which is added in the scene). Code:
var LoginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);
LoginTask.ContinueWithOnMainThread(task =>
{
if (task.IsCanceled || task.IsFaulted)
{
Firebase.FirebaseException e =
task.Exception.Flatten().InnerExceptions[0] as Firebase.FirebaseException;
GetErrorMessage((AuthError)e.ErrorCode, warningLoginText);
return;
}
if (task.IsCompleted)
{
User = LoginTask.Result;
if (User.IsEmailVerified == true)
{
UIControllerLogin.instance.MainScreenScene();
}
else
{
warningLoginText.text = Lean.Localization.LeanLocalization.GetTranslationText($"Login/VerifyEmail");
}
I know that it's possible to fix this issue by adding an extra scene just before the login scene (as Patrick does in the youtube video) but it doesn't make any sense in my app. It would actually only harm the UX of it.
Patrick's Video:
https://www.youtube.com/watch?v=52yUcKLMKX0&t=264s
I'm glad my video helped!
My architecture won't work for every game, and I tried to boil it down to the bare minimum to get folks started. You may be able to get the functionality you want by adding an additional check in HandleAuthStateChanged:
private void HandleAuthStateChanged(object sender, EventArgs e)
{
if (_auth.CurrentUser != null && !_auth.CurrentUser.IsAnonymous && _auth.CurrentUser.IsEmailVerified)
{
SceneManager.LoadScene(_sceneToLoad);
}
}
but it does sound like, at this point, you'll want to build out a more robust registration/sign in flow that fits your use case.
If you need more help, I might suggest re-posting on the community mailing list or the subreddit. Those resources may be more better suited to discussing various pros/cons of different architectures or spitballing ideas (and feel free to link to any new posts in a comment so myself or others interested can follow along).

Getting image download links from owncloud server

there is not much information out there for the newbies to owncloud.. not even here in Stack Overflow, a little background on what im trying to achieve is:
-Already managed to sync my project to the owncloud library via gradlle.
- The provided examples are not of much help for me you will see why.
I use this library https://github.com/bumptech/glide to stream images URLs to some imageviews in my app, as i was on a web server I had no problem but now that I moved to owncloud, I can do the same if i provide my app with the "download link" from the stored images.
That said, what I need is to some how be able to select the owncloud stored images(access the shared folder and download) by name and or read the download link from where ever is stored..
here is the use the glide library on my project
String url = null;
if (plato.getFoto_movil().equals("churrasco.jpg"))
{
url = "http://192.168.0.20/owncloud/index.php/s/EqX7LxLpUeBCzF4/download";
}
if (plato.getFoto_movil().equals("pizza.jpg"))
{
url = "http://192.168.0.20/owncloud/index.php/s/VGQJh6ii36PLGsN/download";
}
if (plato.getFoto_movil().equals("torta_chocolate.jpg"))
{
url = "http://192.168.0.20/owncloud/index.php/s/K0TaHRMPuMrs0Fx/download";
}
Glide.with(mContext).load(url).into(imageView);
which is sad because I had to manually get those URLs from my browser and it does not work with the newly added images from any othere device, so I need to be able to get any new image and show it too.
I have the library installed 100% and implemented but
private void startDownload(String filePath, File targetDirectory) {
DownloadRemoteFileOperation downloadOperation = new DownloadRemoteFileOperation(filePath, targetDirectory.getAbsolutePath());
downloadOperation.addDatatransferProgressListener((OnDatatransferProgressListener) mContext);
downloadOperation.execute( mClient, (OnRemoteOperationListener) mContext, mHandler);
}
#Override
public void onTransferProgress(long l, long l1, long l2, String s) {
mHandler.post( new Runnable() {
#Override
public void run() {
// do your UI updates about progress here
}
});
}
#Override
public void onRemoteOperationFinish(RemoteOperation remoteOperation, RemoteOperationResult remoteOperationResult) {
if (remoteOperation instanceof DownloadRemoteFileOperation) {
if (remoteOperationResult.isSuccess()) {
}
}
}
got those and
got also this two
mClient = OwnCloudClientFactory.createOwnCloudClient(serverUri,mContext,true);
mClient.setCredentials(OwnCloudCredentialsFactory.newBasicCredentials(username,password));
then I call the method
startDownload(plato.getFoto_movil(),downloadfolder);
the app crashes here when I call the startdowonload method
with the error java.lang.ClassCastException: com.eidotab.eidotab.MainActivity cannot be cast to com.owncloud.android.lib.common.network.OnDatatransferProgressListener
another relevant information is that im implementing the ownclod methods to
the viewholder of a recyclerview
public class VH extends RecyclerView.ViewHolder implements OnRemoteOperationListener, OnDatatransferProgressListener
but I could change to the main activity if needed, probably make it work from there but even if it does have success, don´t know where or how to get the download links, like I said, I need the download link from every image stored in the server..
is this possible?
thanks in advance
I changed the implementation of the owncloud library to the main activity as suggested (and was the logical move) and everything went smooth.. worked at first try, I knew it was going to, the thing is that I didnt want to store the images on the device memory, I want to capture the download links which was my main concern but for now it is working since im streaming the images directly from the local sd to the imageview and that should give me some more time to investigate further in the matter whats the thing with the URLS...
Thanks cricket for your comments

SystemClock() is not public in 'android.os.SystemClock'

I'm trying to code the game loop for an android game, however, i've come across this error when trying to access the current time (you know, for FPS management etc)
"SystemClock() is not public in 'android.os.SystemClock'. Cannot be accessed from outside package"
My code:
import android.os.SystemClock;
//...
SystemClock clock = new SystemClock();
Can you help me please? ^_^
SystemClock exposes static methods. So you should access them like this:
SystemClock.sleep(1000);
boolean b = SystemClock.setCurrentTimeMillis(1000)
long l = SystemClock.currentThreadTimeMillis();

Using BatteryStatsImpl internal class via Reflection in android

I am trying to get a list of running applications and the amount of battery used by each of them. I have google for a long time but didnt come up with a solution. However there have been a few references on the PowerProfile, PowerUsageSummary internal classes.
I used them through Reflection technique but didnt get what i was looking for. PowerUsageSummary shows the same details as you can see by going to Device Settings->Applications->Battery Use(This is how it can be seen in a Samsund device).
Then i used PowerProfile class but i got only the mA of current utilized by WIFI, AUDIO, VIDEO,GPS, BLUETOOTH etc(The mA values dont change so often. I am not sure if the values are correct). Another reference was the BatteryStatsImpl class. I tested this class but the values are 0 always. Still i am looking for the list of running applications and the amount of battery used by each of them. Any help is appreciated.
Thanks,
Here is the sample code that i tried for BatteryStatsImpl class.
String BATTERY_PROFILE_CLASS = "com.android.internal.os.BatteryStatsImpl";
Object mBatteryProfile = Class.forName(BATTERY_PROFILE_CLASS).getConstructor().newInstance();
Method batteryMeth = Class.forName(BATTERY_PROFILE_CLASS).getMethod("getBatteryUptime", long.class);
Object arglist1[] = new Object[1];
arglist1[0] = System.currentTimeMillis();
// This is to calculate the batteryUpTime since the current time.
Long batteryUptime = (Long) batteryMeth.invoke(mBatteryProfile, arglist1);
Method dischargeMeth = Class.forName(BATTERY_PROFILE_CLASS).getMethod("getDischargeStartLevel");
// This is to calculate the dischargeTime of the device battery
Integer dischargeTime = (Integer) dischargeMeth.invoke(mBatteryProfile);
First please note that you can't make use of this API unless you are installed on the system image and so can hold the BATTERY_STATS permission. This is not available to third part apps installed separately from the system.
To use this, you don't directly instantiate BatteryStatsImpl. You request an instance of it from the current stats being collected by BatteryStatsService. You can look for the source code of the settings app for how to do this: https://code.google.com/p/android-source-browsing/source/browse/src/com/android/settings/fuelgauge/PowerUsageSummary.java?repo=platform--packages--apps--settings
In particular:
import android.os.BatteryStats;
import com.android.internal.app.IBatteryStats;
import com.android.internal.os.BatteryStatsImpl;
IBatteryStats mBatteryInfo;
UserManager mUm;
BatteryStatsImpl mStats;
mBatteryInfo = IBatteryStats.Stub.asInterface(
ServiceManager.getService("batteryinfo"));
private void load() {
try {
byte[] data = mBatteryInfo.getStatistics();
Parcel parcel = Parcel.obtain();
parcel.unmarshall(data, 0, data.length);
parcel.setDataPosition(0);
mStats = com.android.internal.os.BatteryStatsImpl.CREATOR
.createFromParcel(parcel);
mStats.distributeWorkLocked(BatteryStats.STATS_SINCE_CHARGED);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException:", e);
}
}
the BatteryStatsService maintains the stats. Have a look in there how BatteryStatsImpl is used to do that (those note*() methods are called by the system when e.g. screen turns on)
Maybe you can get the current stats from there

How to reference stage? Using flex for Facebook actionscript mobile API login method

I'm trying to implement the 1.6 Mobile Facebook API (http://code.google.com/p/facebook-actionscript-api/downloads/detail?name=GraphAPI_Mobile_1_6.swc) into an Air for Android application. I've succesfully used the Web and Desktop API's however with the mobile app it's expecting an extra parameter to a stageReference, see:
login(callback:Function, stageRef:Stage, extendedPermissions:Array, webView:StageWebView = null)
But, using i'm using Flex and not Flash CS5, i can't just pass in this.stage or this or anything like that.
What exactly would you guys think I need to pass into that using Flash builder Flex? I can't seem to find any examples for the mobile actionscript API so i'm kinda in the dark, anyone have any ideas?
Here's the login information from the Mobile API Docs:
login () method
public static function login(callback:Function, stageRef:Stage, extendedPermissions:Array, webView:StageWebView = null):void
Opens a new login window so the current user can log in to Facebook.
Parameters
callback:Function — The method to call when login is successful. The handler must have the signature of callback(success:Object, fail:Object); Success will be a FacebookSession if successful, or null if not.
stageRef:Stage — A reference to the stage
extendedPermissions:Array — (Optional) Array of extended permissions to ask the user for once they are logged in.
webView:StageWebView (default = null) — (Optional) The instance of StageWebView to use for the login window For the most current list of extended permissions, visit http://developers.facebook.com/docs/authentication/permissions
If you're using Flex, you have FlexGlobals.topLevelApplication which will point to your mx:Application or s:Application so you can call stage on that to get a reference to it.
Otherwise, any DisplayObject attached to the stage or attached to another DisplayObject attached to the stage, will have it's stage property set (If it's not attached to anything, stage will be null).
Other than that, normally what people do is keep a static somewhere that they can access through the code, that's set when the program starts. For example, your typical main class could be something like:
package
{
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
public class Main extends Sprite
{
public static var stage:Stage = null;
public function Main():void
{
// if we have our stage, go directly to _init(), otherwise wait
if ( this.stage ) this._init();
else this.addEventListener( Event.ADDED_TO_STAGE, this._init );
}
private function _init( e:Event = null ):void
{
// remove the listener
this.removeEventListener( Event.ADDED_TO_STAGE, this._init );
// hold the stage
Main.stage = this.stage;
// do everything else
...
}
}
}
After that, anywhere in your code, you can call Main.stage to get access to the stage.

Categories

Resources