actionscript 3.0 for air for android - android

I want to run my linked swf files on android mobile... I used adobe air for android extension in flash cs5.5 publish settings. When I published it generated filename.apk & filename.swf.
Here is the main problem is when i clicked next and previous button in one file it will not navigating to other file in android.
The individual file playing well, but I am not getting link from one file to other file using previou s and next buttons. Here is my code:
import flash.display.Loader;
import flash.events.Event;
import flash.events.MouseEvent;
// Vars
var currentMovieIndex:uint = 0;
var currentMovie:Loader;
// Put your movies here
var swfList:Array = ["apk1.swf", "apk2.swf", "apk3.swf"];
// Add the event listener to the next and previous button
previousButton.addEventListener(MouseEvent.CLICK, loadPrevious);
nextButton.addEventListener(MouseEvent.CLICK, loadNext);
// Loads a swf at secified index
function loadMovieAtIndex (index:uint) {
// Unloads the current movie if exist
if (currentMovie) {
removeChild(currentMovie);
currentMovie.unloadAndStop();
}
// Updates the index
currentMovieIndex = index;
// Creates the new loader
var loader:Loader = new Loader();
// Loads the external swf file
loader.load(new URLRequest(swfList[currentMovieIndex]));
// Save he movie reference
currentMovie = loader;
// Add on the stage
addChild(currentMovie);
}
// Handles the previous button click
function loadPrevious (event:MouseEvent) {
if (currentMovieIndex) { // Fix the limit
currentMovieIndex--; // Decrement by 1
loadMovieAtIndex(currentMovieIndex);
}
}
// Handles the next button click
function loadNext (event:MouseEvent) {
if (currentMovieIndex < swfList.length-1) { // Fix the limit
currentMovieIndex++; // Increment by 1
loadMovieAtIndex(currentMovieIndex);
}
}
// Load the movie at index 0 by default
loadMovieAtIndex(currentMovieIndex);
note:i also tested above code by replacing
var swfList:Array = ["apk1.swf", "apk2.swf", "apk3.swf"];
with
var swfList:Array = ["apk1.apk", "apk2.apk", "apk3.apk"];

Related

unity android gameobject not working

So in my app i pass a game object, called datacontroller through out my three scenes. The persistent scene is an empty scene, the menuscreen scene and then the game scene. My application works perfectly on my computer and in editor mode but when i download the apk to my android tablet it no longer works! iv'e read this may have to do with my code for my object but i dont think i written anything that only works in the editor.
enter code here
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using System.IO; // The System.IO namespace contains functions related to loading and saving
files
public class DataController : MonoBehaviour
{
private RoundData[] allRoundData;
private PlayerProgress playerProgress;
private string gameDataFileName = "data.json";
void Start()
{
DontDestroyOnLoad(gameObject);
LoadGameData();
LoadPlayerProgress();
SceneManager.LoadScene("MenuScreen");
}
public RoundData GetCurrentRoundData()
{
// If we wanted to return different rounds, we could do that here
// We could store an int representing the current round index in PlayerProgress
return allRoundData[0];
}
public void SubmitNewPlayerScore(int newScore)
{
// If newScore is greater than playerProgress.highestScore, update playerProgress with the new value and call SavePlayerProgress()
if (newScore > playerProgress.highestScore)
{
playerProgress.highestScore = newScore;
SavePlayerProgress();
}
}
public int GetHighestPlayerScore()
{
return playerProgress.highestScore;
}
private void LoadGameData()
{
// Path.Combine combines strings into a file path
// Application.StreamingAssets points to Assets/StreamingAssets in the Editor, and the StreamingAssets folder in a build
string filePath = Path.Combine(Application.streamingAssetsPath, gameDataFileName);
if (File.Exists(filePath))
{
// Read the json from the file into a string
string dataAsJson = File.ReadAllText(filePath);
// Pass the json to JsonUtility, and tell it to create a GameData object from it
GameData loadedData = JsonUtility.FromJson<GameData>(dataAsJson);
// Retrieve the allRoundData property of loadedData
allRoundData = loadedData.allRoundData;
}
else
{
Debug.LogError("Cannot load game data!");
}
}
// This function could be extended easily to handle any additional data we wanted to store in our PlayerProgress object
private void LoadPlayerProgress()
{
// Create a new PlayerProgress object
playerProgress = new PlayerProgress();
// If PlayerPrefs contains a key called "highestScore", set the value of playerProgress.highestScore using the value associated with that key
if (PlayerPrefs.HasKey("highestScore"))
{
playerProgress.highestScore = PlayerPrefs.GetInt("highestScore");
}
}
// This function could be extended easily to handle any additional data we wanted to store in our PlayerProgress object
private void SavePlayerProgress()
{
// Save the value playerProgress.highestScore to PlayerPrefs, with a key of "highestScore"
PlayerPrefs.SetInt("highestScore", playerProgress.highestScore);
}
}
I am starting to go through tutorials of unity myself so I am not an expert. :)
But what I would try is the first thing. using System.IO; not sure if this will work to get files on android because android has a different file structure. So I would first remove it and sort of hard code the file path or comment out the code using System.IO classes then recompile apk in unity and check if it works. I also saw this post : http://answers.unity3d.com/questions/1023391/systemio-dont-work-on-android.html
If that did not work I would comment functionality out and compile apk and check if its working if its not comment more code out until you find the line or the code that causes it to error on android. This method takes long to troubleshoot or get your code causing the problem but for me this has worked before.
I am guessing as it is working on you pc its a class or something its referencing that's not available in android.
Please share your findings if you figure out what part of the code does it. As I would also want to know to prevent me from doing it. :)
Avoid the use of System.IO on Android and in general on Unity.
Use "Resources" instead, just following this steps:
Create a folder called "Resources"
Move json file on it and rename in .txt
Use this code to get the string:
var file = Resources.Load("filename_here") as TextAsset;
Debug.Log(file.text)

adobe flash as3 for android get access file from sdcard

i was made a simple video playback for android application with adobe flash using action script 3, where a flvplayback access playlist from xml file "xmlVideoPlayer.xml", and i put in folder "media/PustakaXML/xmlVideoPlayer.xml" where parent folder same with myfile.fla (project file).
can somebody help me, how to ; if i put myxml file on SDCARD on android mobile. so if i publish it, to APK, and instal on android mobile, the aplication can access myxml file on SDCARD.
below the script on my adobe flash actionscript code.
import fl.video.*;
import flash.events.Event;
import flash.net.*;
// Set Variables
var flvControl:FLVPlayback = display;
var flvIndex:Number = 0;
var loopAtEnd:Boolean = true;
// Load XML file...
var xmlList:XML;
var xmlPath:String = "media/PustakaXML/xmlVideoPlayer.xml";
//HELP HERE if file put in SDCARD
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.load(new URLRequest(xmlPath));
// Receive the XML and load the first video
function xmlLoadedHandler(event:Event):void
{
// Save XML
xmlList = new XML(xmlLoader.data);
// Set video (Start)
flvControl.source = xmlList.video[0];
}
xmlLoader.addEventListener(Event.COMPLETE, xmlLoadedHandler);
// 3. Handle video completion (load next video)
function completeHandler(event:fl.video.VideoEvent):void
{
// Get next item in list
flvIndex++;
// Validate index
if( flvIndex == xmlList.video.length() ){
if( loopAtEnd ){
flvIndex = 0;
}
else{
return;
}}
// Load next video
flvControl.source = xmlList.video[flvIndex];
}
flvControl.addEventListener(fl.video.VideoEvent.COMPLETE, completeHandler);
i am sorry my English no good enough...

Re-loading Swf file from sdcard as3 Android

I am working on an android app where I wish to download swf files from an external server, save them to sdcard and load them later in the app. Downloading works fine and the swf is saved in the application directory. Here is my code that loads the swf from the sdcard :
var myloader:Loader = new Loader();
var myhomeButton:btnHome = new btnHome();
addChild(myloader);
var swfFilePath:File = File.applicationStorageDirectory.resolvePath("Android/data/myswffile.swf");
var inFileStream:FileStream = new FileStream();
inFileStream.open(swfFilePath, FileMode.READ);
var swfBytes:ByteArray = new ByteArray();
inFileStream.readBytes(swfBytes);
inFileStream.close();
var loaderContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
loaderContext.allowCodeImport = true;
myloader.contentLoaderInfo.addEventListener(Event.COMPLETE, mycompleteHandler);
myloader.loadBytes(swfBytes, loaderContext);
function mycompleteHandler(evt:Event):void
{
myloader.contentLoaderInfo.removeEventListener(Event.COMPLETE, mycompleteHandler);
addChild(myhomeButton);
myhomeButton.height = _height * 0.08;
myhomeButton.width = myhomeButton.height;
myhomeButton.x = 10;
myhomeButton.y = 10;
myhomeButton.addEventListener(MouseEvent.CLICK, myexitfftn);
}
function myexitftn(evt:Event):void
{
myloader.unloadAndStop(true);
removeChild(myhomeButton);
gotoAndStop(1, "SomeOtherFrame");
}
the problem is when I click the exit button the swf unloads but when I reload it, it starts from the second frame of the loaded swf, the third time from the third frame and so on... Where am I going wrong or what is an alternative solution, please guide.
Try, addChild(myloader) in Complete handler and removeChild and null while exiting, so that loaded swf is completely removed from the memory like so:
function mycompleteHandler(evt:Event):void
{
myloader.contentLoaderInfo.removeEventListener(Event.COMPLETE, mycompleteHandler);
addChild(myloader);
//... Rest of code remains same
}
function myexitftn(evt:Event):void
{
myloader.unloadAndStop();
removeChild(myloader);
myloader = null;
removeChild(myhomeButton);
gotoAndStop(1, "SomeOtherFrame");
}

Adobe AIR SharedObject - Android/iOS - On update not found

As the title states, my user's on iOS and Android are reporting their save data has been deleted when I push an update to the respected storefronts. The game saves and restores data properly on application load and exit. I have not changed any save information locations or package names... Just mere bug fixes, build, push.
Any clarification would be helpful, or proposed redundant data backup scheme's I should pursue to ensure the end-user experience is from henceforth not affected negatively. I would also like to understand better how I can test this as a release package is not allowed to update a market installed application.
var so:SharedObject = SharedObject.getLocal("storage");
var u:User;
if(so.data != null){
u = so.data.user;
}
trace("Loading application...");
if(u != null){
trace("LOADING SAVE DATA");
user = u;
}else{
trace("NO SAVE DATA EXISTS");
user = new User();
}
I have discovered the cause of this issue and it seems that Adobe has identified and fixed the issue as well (as of AIR 3.5). https://bugbase.adobe.com/index.cfm?event=bug&id=3347676
SharedObjects are stored within a directory named according to the SWF used by your application, so if your application is running off "myApp.swf" the SharedObject will be stored in a directory "myApp". If you change the name of this SWF (i.e. the corresponding XML build sheet configuration file for your AIR project) any subsequent builds will store their SharedObjects in a new location.
The issue described in this bug was specifically denoted for iOS, wherein the application was not storing the SharedObject in the corresponding SWF location as described above but in a separate location denoted by the "filename" attribute in your project's XML build sheet.
I have also discovered that Adobe does indeed condone the use of a SharedObject for persistent storage on a mobile platform.
I have developed a simple backup for future version save redundancy in case future updates fail to persist the SharedObject.
/** the last timestamp a deep save was completed */
private var mLastSave:Number = -1;
/**
* save the state of the globals object and all of its
* sub objects.
* #warning
* all objects must implement variables in a "public" state.
* Private variables are not saved within the persistance manager
*/
public function save():void{
var so:SharedObject = SharedObject.getLocal("storage");
so.data.user = user;
so.flush();
saveDeep();
}
/**
* Save the SharedObject to denoted mobile applicationStorageDirectory.
*/
public function saveDeep():void{
// save on first application save or after
// every 5 minutes
if(mLastSave == -1 || mLastSave < getTime() + 300000){
mLastSave = getTime();
var file:File = File.applicationStorageDirectory.resolvePath("userSave");
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
var ba:ByteArray = new ByteArray();
ba.writeObject(user);
fileStream.writeBytes(ba);
fileStream.close();
}
}
/**
* Load the application from the SharedObject be default
* if the SharedObject DNE attempt to load from the
* applicationStorageDirectory, if neither exist
* create new User object
*/
public function load():void{
registerClassAlias("user", User);
// Create/read a shared-object named "userData"
var so:SharedObject = SharedObject.getLocal("storage");
var u:User;
if(so.data != null){
u = so.data.user;
}
trace("Loading application...");
if(u != null){
trace("LOADING SAVE DATA");
user = u;
}else{
trace("NO SAVE DATA EXISTS");
var file:File = File.applicationStorageDirectory.resolvePath("userSave");
if(file.exists){
trace("Found userSave backup -attempting to load");
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var ba:ByteArray = new ByteArray();
fileStream.readBytes(ba);
fileStream.close();
try{
user = (ba.readObject() as User);
}catch( e : EOFError ){
trace("SharedObject did not exist, attempted userSave load, failed");
}
}else{
user = new User();
trace("created New user...");
}
}
}

How do I open a directory of images in Androids Navite Image Gallery with PhoneGap?

I have an app developed and want a link to open a gallery of images. The images are locally bundled and included in my assets/www/img directory.
I would like this to seamlessly resemble the native image gallery.
Is this possible?
I have tried to use the following but cant get a response.
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
}
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getDirectory("img/china", {create: false, exclusive: false}, getDirSuccess, fail);
}
function getDirSuccess(dirEntry) {
// Get a directory reader
var directoryReader = dirEntry.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(readerSuccess,fail);
}
var numDirs = 0;
var numFiles = 0;
var readerTimeout = null, millisecondsBetweenReadSuccess = 100;
function readerSuccess(entries) {
var i = 0, len = entries.length;
for (; i < len; i++) {
if (entries[i].isFile) {
numFiles++;
entries[i].file(fileSuccess,fail);
} else if (entries[i].isDirectory) {
numDirs++;
getDirSuccess(entries[i]);
}
if (readerTimeout) {
window.clearTimeout(readerTimeout);
}
}
if (readerTimeout) {
window.clearTimeout(readerTimeout);
}
readerTimeout = window.setTimeout(weAreDone, millisecondsBetweenReadSuccess);
}
// additional event to call when totally done
function weAreDone() {
// do something
}
The Camera docs cover this. Is this not working for you?
If Camera.sourceType = Camera.PictureSourceType.PHOTOLIBRARY or Camera.PictureSourceType.SAVEDPHOTOALBUM, then a photo chooser dialog is shown, from which a photo from the album can be selected.
http://docs.phonegap.com/phonegap_camera_camera.md.html
Also refer...
Browsing Image Gallery With PhoneGap & Android
I am porting an application I wrote for the iphone over to Android and I wanted to start with the Camera functionality. I looked around and Googled and I could not find where it was documented on how to browse the image gallery on the Android device. I decided to bang out some simple modifications to the existing Camera object to support that functionality for now. I the future, hopefully this is implemented better by the PhoneGap guys and I can put this code out to pasture.
This code needs to be added to the phoneGap.js file. It creates the prototype for the new method for browsing the gallery on the device
1 //
2 // add the new prototype to support the browse function
3 //
4 // i have created a new class 'PixCameraLauncher' so I did not have to modify
5 // the original class file provided by PhoneGap
6 //
7 com.phonegap.CameraLauncherProxy.prototype.browseImages = function(quality) {
8 return PhoneGap.exec("com.phonegap.gapTest.PixCameraLauncher", "browseImages", [quality]);
9 };
This the modification I made to the CameraLauncher class provided by PhoneGap. Add a new intent to launch the image gallery
01 /**
02 * Get a picture from the Image Gallery.
03 *
04 * in DroidGap.onActivityResult, which forwards the result to
05 * this.onActivityResult.
06 *
07 * #param quality
08 * Compression quality hint (0-100: 0=low quality & high
09 * compression, 100=compress of max quality)
10 */
11 public void browseImages(int quality) {
12 this.mQuality = quality;
13
14 // Display camera
15 Intent intent = new Intent(Intent.ACTION_PICK,
16 android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
17
18 this.ctx.startActivityForResult((Plugin) this, intent);
19 }
Also we need to handle the returned file. I left it simple, but this could be cleaned up a bit What I do is assume that if there is a URI in the data field, then an image has been picked and should be processed by the utility. In the beginning of the
1 void onActivityResult(int requestCode, int resultCode, Intent intent)
add the code below. This will handle re-assigning the URI to the selected file
1 // If image available
2 if (resultCode == Activity.RESULT_OK) {
3
4 //
5 // this means the user selected an image, so just pass it back!!
6 //
7 if (intent.getData() != null) {
8 imageUri = intent.getData();
9 }
After a little more testing and code cleanup, I will make the complete project for the android work and the iphone work available. If there are any questions, post it below.
The problem is you are trying to use the File API to read files inside of your applications assets directory. That directory is not actually part of the file system. When you do a window.requestFileSystem(LocalFileSystem.PERSISTENT, ...) you are actually getting the /sdcard (most probably) back. So when you try to load "img/china" that directory does not exist.
You would need to copy the files from your assets directory to the local file system during the onCreate method of your main Java class. Then you can use the DirectoryReader to get a list of all the files.
Alternatively, if you know all the images ahead of time you could create your own JSON file that lists them all. Then load that file and be able to loop through all the entries to create your own gallery.

Categories

Resources