How to launch another Android app using cocos2d-x? - android-ndk

I'm making a game with cocos2d-x for Android using C++. Now I'm looking for a way to open another Android App (likes YouTube, Google Play Store, ...) using their package name from inside my game through a button . I have searched around and found that it could be done in Java code with something like this:
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.package.address");
if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
}
My question is: Is it possible to open another Android App in my native code (.cpp files) or I have to put them in java side (.java files)? If I have to do it in .java files, where should I put it? I always work with .cpp files in Visual Studio, compile with cmd and run with emulator on Android Studio, I have never worked with .java files that generated by cocos2d-x in Android Studio, the engine just makes everything ready for me so I got a little confused here.
Update 1:
Abhishek Aryan's advice works but my Game crashed on resume when I'm in another App. I'm trying to performs some actions before opening others app and they might cause the crash because I could run it without any problem if I remove those action and leave openApp function alone.
My expect: Press the button => pause my game and open You Tube on Android => Press Back Button => pause You Tube and resume my game.
What happens: I could open You Tube but my App crashed when I press back button. I got the following error code from Android Studio:
A/libc: Fatal signal 11 (SIGSEGV) at 0x0004fb18 (code=1), thread 1975 (Thread-55)
Any idea how could I fix it?
My code :
auto imageOpeningAction = CallFunc::create([&]() {
mOpeningImage->setEnabled(true);
mOpeningImage->setOpacity(255);
mOpeningImage->setPosition(menuItem->getPosition());
mOpeningImage->runAction(fullScale);
});
auto imageClosingAction = CallFunc::create([&]() {
mOpeningImage->runAction(reverseScale);
mOpeningImage->setOpacity(0);
mOpeningImage->setEnabled(false);
});
auto openAnotherApp = CallFunc::create([&]() { // Open YouTube app
HelloWorld::openApp(packageName);
});
runAction(Sequence::create(imageOpeningAction->clone(), DelayTime::create(0.5f), openAnotherApp->clone(), nullptr));
Your attention and help is very much appreciated.

You need to use JNI for your requirement.
Create a method that open any app in your AppActivity.
public class AppActivity extends Cocos2dxActivity {
private static Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity=this;
}
public static void openOtherApp(String packageName){
Intent launchIntent = activity.getPackageManager().getLaunchIntentForPackage(packageName);
if (launchIntent != null) {
activity.startActivity(launchIntent);
}
}
}
Done !
Not yet, now only I need to call openOtherApp method from c++ so I create a method in my .cpp file.
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/jni/JniHelper.h"
#endif
void openApp(std::string packageName){
#if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
JniMethodInfo methodInfo;
const char* class_name="org/cocos2dx/cpp/AppActivity";
const char* method_name="openOtherApp";
const char* parameter= "(Ljava/lang/String;)V";
if (! cocos2d::JniHelper::getStaticMethodInfo(methodInfo, class_name, method_name ,parameter )) {
return;
}
jstring jStringParam = methodInfo.env->NewStringUTF(packageName.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID,jStringParam);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
#endif
}
Want to open facebook call openApp(com.facebook.katana);

Related

unity udp dgram socket not working on hololens

I tried to connect between hololens and python server. So I used dgram socket but this is not working on hololens.
this is my code sample.
hololens client
public string conHost = "192.168.0.58";
public int conPort = 3174;
void Start()
{
ipep = new IPEndPoint(IPAddress.Parse(conHost), conPort);
clientThread = new Thread(setupSocket);
clientThread.Start();
}
public void setupSocket()
{
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
void Update()
{
if(Send)
{
Send = false;
byte[] bytes = Encoding.UTF8.GetBytes("124306324602435");
byte[] buffer = Encoding.UTF8.GetBytes(bytes.Length.ToString());
mySocket.SendTo(buffer, buffer.Length, SocketFlags.None, ipep);
}
}
python server
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#server_address = "192.168.0.18", 9029
#print('starting up on {} port {}'.format(*server_address))
sock.bind(("192.168.0.58", 3174))
ready=True
while(ready):
try:
epoch_time = time.time()
data,address = sock.recvfrom(100)
fileLength = data.decode("utf-8")
print(fileLength)
except:
continue
When I play this code in unity project, it works. But in hololens, not working.
I used try-catch, I got this error messege on Update
System.NullReferenceException: Object reference not set to an instance of an object [0x00000] in <000000000000000000000000000000000>:0
It occurs because the variable mySocket is not initialized as an expected value. Actually, the implementation of System.Threading has changed in .NET 4.x in a way that is not backward compatible, and the HoloLens app uses IL2CPP scripting backend with.NET4.x but the Unity Editor uses Mono scripting backend with.NET2.x. So, it works in Unity Editor but fails to start your thread in .NET4.x, we recommended that using System.Threading.Tasks class instead. Besides, to use WinRT APIs in Unity projects built for the UWP you need to use preprocessor directives, more information please see:WinRT APIs with Unity for HoloLens

How to use LibvlcSharp on Linux?

I'm trying to use LibvlcSharp on a linux installation (Ubuntu 18.04). I'm following all the instructions, including this one Getting started on LibVLCSharp.Gtk for Linux but my application always crash. It's working perfectly on windows, because there we can add VideoLAN.LibVLC.Windows package, but I couldn't find someting similar for Linux.
My code:
static void Main(string[] args)
{
// Record in a file "record.ts" located in the bin folder next to the app
var currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var destination = Path.Combine(currentDirectory, "record.ts");
// Load native libvlc library
Core.Initialize();
using (var libvlc = new LibVLC())
//var libvlc = "/usr/lib/x86_64-linux-gnu/";
using (var mediaPlayer = new MediaPlayer(libvlc))
{
// Redirect log output to the console
libvlc.Log += (sender, e) => Console.WriteLine($"[{e.Level}] {e.Module}:{e.Message}");
// Create new media with HLS link
var urlRadio = "http://transamerica.crossradio.com.br:9126/live.mp3";
var media = new Media(libvlc, urlRadio, FromType.FromLocation);
// Define stream output options.
// In this case stream to a file with the given path and play locally the stream while streaming it.
media.AddOption(":sout=#file{dst=" + destination + "}");
media.AddOption(":sout-keep");
// Start recording
mediaPlayer.Play(media);
Console.WriteLine($"Recording in {destination}");
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
The error message:
Unhandled Exception: LibVLCSharp.Shared.VLCException: Failed to perform instanciation on the native side. Make sure you installed the correct VideoLAN.LibVLC.[YourPlatform] package in your platform specific project
at LibVLCSharp.Shared.Internal..ctor(Func1 create, Action1 release)
at RadioRecorderLibVlcSharp.Program.Main(String[] args) in /media/RadioRecorderLibVlcSharp/Program.cs:line 19
Anyone can help me?
thanks
Can you try apt-get install vlc? That seems to help getting all the required plugins/deps on your system (though it will pull vlc 2.x from the official ubuntu rep probably).

Pubnub library not compiling on Particle Photon

I am trying to publish a message using pubnub on the Particle Photon. The code snippet below comes straight out of the Pubnub example code.
The code will not compile, with the message from the compiler as follows:
PubNub/PubNub.h:87:47: error: expected class-name before '{' token
class PubSubClient: public PubNub_BASE_CLIENT {
^
PubNub/PubNub.h: In constructor 'PubSubClient::PubSubClient()':
PubNub/PubNub.h:23:28: error: class 'PubSubClient' does not have any field named 'WiFiClient'
#define PubNub_BASE_CLIENT WiFiClient
^
The code for this tiny project is as follows:
// This #include statement was automatically added by the Particle IDE.
#include "PubNub/PubNub.h"
char pubkey[] = "<key here>";
char subkey[] = "<key here>";
char channel[] = "Channel";
void setup() {
Serial.begin(9600);
Particle.publish("Serial set up");
PubNub.begin(pubkey, subkey);
}
void loop() {
TCPClient *client;
char msg[64] = "{\"photon\":\"on\"}";
client = PubNub.publish(channel, msg);
client->stop();
Delay (30000);
}
Has anyone had a similar problem, and if so, can you guide me as to how to fix this.
Thanks.
It looks like the library available in Build IDE was in an older version (0.0.1). Fixed, latest version (0.0.2) has been published.
To update library in your app you need to remove the PubNub library from your app in Apps drawer:
And then go to Libraries drawer, find PubNub library, click Include in App, select your app and confirm:

Error.getStackTrace() returns a string unparseable in flashdevelop?

Accessing a string created by an Error's getStackTrace function is resulting in very unusual behaviour in the FlashDevelop IDE.
package
{
import flash.display.Sprite;
public class Main extends Sprite
{
public function Main():void
{
print("Start");
var err:Error = new Error();
var stack:String = err.getStackTrace();
print(stack);
// also occurs when this is replaced with stack.length or stack[0]
print("End");
}
private function print(input:*):void
{
trace(input);
trace("---");
}
}
}
When run in flash CS4 that outputs
Start
---
Error
at Main()
---
End
---
But when run in FlashDevelop (replacing trace() with FlashConnect.trace()) it outputs
Start
---
Is that a bug, or is it FlashDevelop handling errors in a different way intentionally?
If it is the latter is there a workaround to access the stacktrace of an error?
I managed to fix this by switching to using a dubugging version of the flash player, i hope this helps anyone else with this problem.
instructions for specifying a debug player
Make sure you are compiling in Debug configuration and you may have to enable (set True) "Verbose Stack Trace" in your Project Properties > Compiler Options

Playing wav/mp3 from Windows 7 service

I need to play a sound file (wav or mp3 is fine) from a service in Windows 7/2008... the way we did it in WinXP doesn't work anymore. I've followed this question Play wave file from a Windows Service (C#) with no success, in various combinations. The sound plays fine through the debugger but once I install it as a service it doesn't play, and event logs prove the call is being made. I've also followed the http://bresleveloper.blogspot.co.il/2012/06/c-service-play-sound-with-naudio.html link with the same result.
Code snippet follows below. It is a C# service with VS 2010, .Net 4.0, NAudio 1.5.4.0. I am using
InstallUtil to install/remove the service.
WRT the code, I comment out the Wav or MP3 stuff and one of the methods each time... they all play the sound sucessfully.
static class Program
{
[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();
static void Main(string[] args)
{
m_eventLog = new EventLog();
m_eventLog.Source = "EventLoggerSource";
if(args.Length > 0 && args[0].ToLower() == "/console")
{
AllocConsole();
EventLoggerApp app = new EventLoggerApp();
app.Start();
m_eventLog.WriteEntry("INFO (Calling Player)");
string fileFullPath=#"c:\aaasound\bunny_troubles.wav",fileFullPath2=#"c:\aaasound\dreams.mp3";
// Wav file
IWavePlayer wavePlayer=new WaveOutEvent(); // Method 1
IWavePlayer wavePlayer=new WasapiOut(NAudio.CoreAudioApi.AudioClientShareMode.Shared,false,100); // Method 2
AudioFileReader audioFile=new AudioFileReader(fileFullPath);
audioFile.Volume = (float)1.0;
wavePlayer.Init(audioFile);
// MP3 file
IWavePlayer wavePlayer=new WasapiOut(NAudio.CoreAudioApi.AudioClientShareMode.Shared,true,100); // Method 1- EventSync/not both work
IWavePlayer wavePlayer=new WasapiOut(NAudio.CoreAudioApi.AudioClientShareMode.Exclusive,false,100); // Method 2- EventSync must be false or throws an exception
WaveStream mp3Reader = new Mp3FileReader(fileFullPath2);
WaveChannel32 inputStream=new WaveChannel32(mp3Reader);
WaveStream wavStream=new WaveChannel32(inputStream);
wavePlayer.Init(wavStream);
//this.wavePlayer.PlaybackStopped += new EventHandler(wavePlayer_PlaybackStopped);
wavePlayer.Play();
while(wavePlayer.PlaybackState == PlaybackState.Playing)
{
Thread.Sleep(100);
}

Resources