Turn on the flashlight in android Lollipop Programatically - android-5.0-lollipop

I have been trying to turn on Flashlight in android lollipop but the camera Api is deprecated and hence donot turn on the Flashlight. Has anyone tried doing that?

You can use below code snippet to turn on flash light:
mCam = Camera.open();
Camera.Parameters p = mCam.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCam.setParameters(p);
mPreviewTexture = new SurfaceTexture(0);
try {
mCam.setPreviewTexture(mPreviewTexture);
} catch (IOException ex) {
// Ignore
}
mCam.startPreview();
It works on Android 5.0.x. Add below permission in manifest for camera usage.
<uses-permission android:name="android.permission.CAMERA" />

Related

How to get a storage file from camera roll in windows phone 8.1

How can I create a Windows.Storage.StorageFile from a picture in Camera Roll for windows phone 8.1? I have tried the follwing:-
try{
Windows.Storage.StorageFolder folder = Windows.Storage.KnownFolders.CameraRoll;
Windows.Storage.StorageFile file = await folder.GetFileAsync(filename);
}
catch(Exception exc)
{
MessageBox.Show(exc.Message);
}
Which is producing an Access Violation Exception.
Can someone plz tell me how to do it in windows phone 8.1?
First, you may need to declare the capability in the package.appxmanifest.
Once you’ve done this you can now use the Windows.Storage.KnownFolders class to access the Picture Library.
Here is how to get to the camera roll, you can refer to.
public async Task<IEnumerable<StorageFile>> GetFilesInCameraRoll()
{
var cameraRoll = await KnownFolders.PicturesLibrary.GetFolderAsync("Camera Roll");
return await cameraRoll.GetFilesAsync();
}
More detailed information, you can refer to Access Camera Roll in Windows Phone 8.1

Phaser HTML5 app cannot play sound after porting by Phonegap Cloud Build

This's a simple Phaser audio example. It works well on my Android web browser. However, it's muted after porting to Android app by Phonegap cloud build.
I know how to play sound (and loop) in Phonegap app (How to loop a audio in phonegap?) but don't know how to apply it into the Phaser JS framework.
Here's the ported app. I can install and run it but without sound. Do I miss something or Phonegap Cloud Build does support the WebAudio in Phaser JS?
https://build.phonegap.com/apps/1783695/
My config.xml is:
<?xml version="1.0" encoding="UTF-8" ?>
<widget id="com.phaser.phasersound" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
<name>Phaser sound complete</name>
<description>
Phaser sound phonegap
</description>
<gap:plugin name="org.apache.cordova.media" />
<icon src="icon.png" />
<preference name="splash-screen-duration" value="1"/>
<!--
If you do not want any permissions to be added to your app, add the
following tag to your config.xml; you will still have the INTERNET
permission on your app, which PhoneGap requires.
-->
<preference name="permissions" value="none"/>
</widget>
The source code is: (I changed the local audio files from local to github links to run on code snippet)
var game = new Phaser.Game(600, 800, Phaser.AUTO, 'phaser-example', { preload: preload, create: create });
function preload() {
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
//have the game centered horizontally
game.scale.pageAlignHorizontally = true;
game.scale.pageAlignVertically = true;
game.stage.backgroundColor = '#414040';
// I changed the local audio files from local to github links to run on code snippet
/*
game.load.audio('explosion', 'assets/audio/SoundEffects/explosion.mp3');
game.load.audio('sword', 'assets/audio/SoundEffects/sword.mp3');
game.load.audio('blaster', 'assets/audio/SoundEffects/blaster.mp3');
*/
game.load.audio('explosion', 'https://raw.githubusercontent.com/nguoianphu/phaser-sound-complete-phonegap/master/www/assets/audio/SoundEffects/explosion.mp3');
game.load.audio('sword', 'https://raw.githubusercontent.com/nguoianphu/phaser-sound-complete-phonegap/master/www/assets/audio/SoundEffects/sword.mp3');
game.load.audio('blaster', 'https://raw.githubusercontent.com/nguoianphu/phaser-sound-complete-phonegap/master/www/assets/audio/SoundEffects/blaster.mp3');
}
var explosion;
var sword;
var blaster;
var text;
var text1;
var text2;
var text3;
function create() {
var style = { font: "65px Arial", fill: "#52bace", align: "center" };
text = game.add.text(game.world.centerX, 100, "decoding", style);
text.anchor.set(0.5);
explosion = game.add.audio('explosion');
sword = game.add.audio('sword');
blaster = game.add.audio('blaster');
// Being mp3 files these take time to decode, so we can't play them instantly
// Using setDecodedCallback we can be notified when they're ALL ready for use.
// The audio files could decode in ANY order, we can never be sure which it'll be.
game.sound.setDecodedCallback([ explosion, sword, blaster ], start, this);
}
var keys;
function start() {
text.text = 'Press 1, 2 or 3';
var style = { font: "48px Arial", fill: "#cdba52", align: "center" };
text1 = game.add.text(game.world.centerX, 250, "Blaster: Stopped", style);
text1.anchor.set(0.5);
text2 = game.add.text(game.world.centerX, 350, "Explosion: Stopped", style);
text2.anchor.set(0.5);
text3 = game.add.text(game.world.centerX, 450, "Sword: Stopped", style);
text3.anchor.set(0.5);
explosion.onStop.add(soundStopped, this);
sword.onStop.add(soundStopped, this);
blaster.onStop.add(soundStopped, this);
keys = game.input.keyboard.addKeys({ blaster: Phaser.Keyboard.ONE, explosion: Phaser.Keyboard.TWO, sword: Phaser.Keyboard.THREE });
keys.blaster.onDown.add(playFx, this);
keys.explosion.onDown.add(playFx, this);
keys.sword.onDown.add(playFx, this);
// And for touch devices you can also press the top, middle or bottom of the screen
game.input.onDown.add(onTouch, this);
}
function onTouch(pointer) {
var b = game.height / 3;
if (pointer.y < b)
{
playFx(keys.blaster);
}
else if (pointer.y > b * 2)
{
playFx(keys.sword);
}
else
{
playFx(keys.explosion);
}
}
function playFx(key) {
switch (key.keyCode)
{
case Phaser.Keyboard.ONE:
text1.text = "Blaster: Playing";
blaster.play();
break;
case Phaser.Keyboard.TWO:
text2.text = "Explosion: Playing";
explosion.play();
break;
case Phaser.Keyboard.THREE:
text3.text = "Sword: Playing";
sword.play();
break;
}
}
function soundStopped(sound) {
if (sound === blaster)
{
text1.text = "Blaster: Complete";
}
else if (sound === explosion)
{
text2.text = "Explosion: Complete";
}
else if (sound === sword)
{
text3.text = "Sword: Complete";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.4.4/phaser.js"></script>
UPDATE 2015-12-01
Here is my completed source code. It has both .mp3 and .ogg sound files. You can play them on Android native browser (tested on 4.4.4 Samsung E5).
Source: https://github.com/nguoianphu/phaser-sound-complete-phonegap
Here is the ported app on Phonegap. It can display the screen but can't play sounds.
https://build.phonegap.com/apps/1783695/builds
You are trying to play the audio with the webview library. It is likely using the HTML5 API for audio or webaudio. If it is neither of these, then you need to ask the author.
Next, it is not best practice to use external source (http:). Your assests (javascript, css, audio files, etc) should live on the device. If you load files from the web, then the sound quality could be poor (or the audio may not play at all - see whitelist below). Load from the device.
Android 4.4.4 is Kitkat. The standard webview library was exchanged for the chromium version. This means your audio library might be confused about this or you need to give the library knowledge about this library. This also means your code may not work on devices before 4.4.4. (Mostly, because you cannot test it.)
The link you point to is likely using the core media plugin, even though they dont say so. In addition, the post is over 3 years old. Many thing have changed since them. NOTE: you have installed the media plugin in your config.xml. This is likely why your loop works.
You should start over. You've made many errors. In addition, to all that you have, You will need to implement the whitelist plugin (if you are going to import files, or talk to the network).
FIRST TRY this sample app - example plays on Android and iOS. You can download the Android version and test it. The iOS version requires I have your UUID compiled in.
There are 16 audio plugins you can choose from. I know a few do real time audio playback and have better control than the "core" plugin.
You should read:
Top Mistakes by Developers new to Cordova/Phonegap - read the bold sentences.
HOW TO apply the Cordova/Phonegap the whitelist system
HOWTO Core Plugins Setup
Phonegap--Generic-Boilerplate7 - just wrote this. It works.
Phonegap Demo Apps
Phonegap-Media-Test - source code for the example that plays on Android and iOS. You can download the Android version and test it.
UPDATE: 2015-12-01 - 2am Previously, I had forgotten to add a wild-card (*) to the CSP meta tag. I am now including this. This meta tag should be added to the header of the index.html file that is playing the audio.
NOTE YOUR APP IS NOW INSECURE. IT IS UP TO YOU TO SECURE YOUR APP.
<meta http-equiv="Content-Security-Policy"
content="default-src *;
style-src * 'self' 'unsafe-inline' 'unsafe-eval';
script-src * 'self' 'unsafe-inline' 'unsafe-eval';">
UPDATE: 2015-12-01 - 3pm
#Tuan, I've applied all the fixes as outlined in
HOW TO apply the Cordova/Phonegap the whitelist system
HOWTO Core Plugins Setup
Phonegap--Generic-Boilerplate7 - just wrote this. It works.
The audio is now working on my Android LG Leon/Android 5.1.1
Truthfully, I would never do this on my own, but your code had enough working that after I tested it on my firefox(v34) browser, I was fairly certain it would work.
UPDATE: 2016-04-15
The code has been removed. Ask in the comments, if you need code.
There should be enough code in place for you to work off of.
- Code
- Working Android App
- Phonegap Build Documentation

intent open chrome in a url - not in lollipop

public void onClickApp(View view){
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main"));
intent.addCategory("android.intent.category.LAUNCHER");
intent.setData(Uri.parse("http://www.google.com"));
startActivity(intent);
}
This code open Google Chrome and open the web www.google.com.
On Android 5, only open Google Chrome but not load www.google.com.
why?
sorry for my bad english.
thanks
I think thats beacuse the activity doesn't exist in android lollipop.
Try with this:
public void onClickApp(View view){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.google.com"));
intent.setPackage("com.android.chrome");
startActivity(intent);
}

How to collect application logs in windows phone 8.1?

I am new to windows phone platform.Is there anything available like logcat in android for windows for collecting logs?Thanks in advance.
Windows 8.1 introduced new classes to simplify logging. These classes are LoggingChannel, LoggingSession and others.
Here's an example:
App.xaml.cs
LoggingSession logSession;
LoggingChannel logChannel;
public App()
{
this.InitializeComponent();
this.UnhandledException += App_UnhandledException;
}
void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
logChannel.LogMessage("Unhandled exception: " + e.Message);
logSession.SaveToFileAsync(Windows.Storage.ApplicationData.Current.LocalFolder, "MainLog.log").AsTask().Wait();
}
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
logSession = new LoggingSession("MainLogSession");
Resources["MainLogSession"] = logSession;
logChannel = new LoggingChannel("AppLogChannel");
logSession.AddLoggingChannel(logChannel);
}
MainPage.xaml.cs
LoggingChannel logChannel;
public MainPage()
{
this.InitializeComponent();
var logSession = (LoggingSession)Application.Current.Resources["MainLogSession"];
logChannel = new LoggingChannel("MainPageLogChannel");
logSession.AddLoggingChannel(logChannel);
logChannel.LogMessage("MainPage ctor", LoggingLevel.Information);
}
I highly recommend watching the Making your Windows Store Apps More Reliable keynote during the 2013 build conference, where Harry Pierson demonstrates these new APIs in more detail (including uploading the log file to a backend server using a background task that gets executed when the phone is connected to AC power).
You can use System.Diagnostics.Debug to view the logs on Visual Studio Console Window but you won't be able to collect them later because it's only shown during debug.
I recommend the use of MetroLog, a lightweight logging system designed specifically for Windows Store and Windows Phone apps.
You can install it using NuGet
Install-Package MetroLog
Here's an quick example:
using MetroLog;
using MetroLog.Targets;
LogManagerFactory.DefaultConfiguration.AddTarget(LogLevel.Trace, LogLevel.Fatal, new FileStreamingTarget());
GlobalCrashHandler.Configure();
ILogger log = LogManagerFactory.DefaultLogManager.GetLogger<MainPage>();
log.Trace("This is a trace message.");
You can find a tutorial explaining how to add it on your project at http://talkitbr.com/2015/06/11/adicionando-logs-em-universal-apps. Also there is an explanation regarding retrieving these logs.

Can I turn on WiFi-Direct from code? on Android API-14 (ICS)

I'm using the new Wi-Fi Direct API from google on Android 4.0
and in Sample code they send the User to Settings, to activate WiFi -Direct Mode.
Is there a way to Start it by code???
all they offer is to listen to WIFI_P2P_STATE_CHANGED_ACTION intent, and then use this code
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// UI update to indicate wifi p2p status.
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wifi Direct mode is enabled
} else {
// Wifi Direct mode is disabled
}
Yes there is a way using reflection. Works on my GSII (and fails gracefully on non Wifi Direct HTC Sensation) but as this is reflection it may not work on all phones.
p2pManager = (WifiP2pManager) getSystemService(WIFI_P2P_SERVICE);
channel = p2pManager.initialize(getApplicationContext(),
getMainLooper(), null);
try {
Class<?> wifiManager = Class
.forName("android.net.wifi.p2p.WifiP2pManager");
Method method = wifiManager
.getMethod(
"enableP2p",
new Class[] { android.net.wifi.p2p.WifiP2pManager.Channel.class });
method.invoke(p2pManager, channel);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please note:
On Jelly Bean and above, when you try to use the WifiP2pManager API, WiFi-Direct is automatically enabled (as long as WiFi is on), so there is no need to use this hack.
No, all you could do is notify the user to turn on WiFi.
On some devices, even though Wi-Fi direct is supported, it's not enabled due to some system bugs. Here's a more reliable way to check whether it's enabled (unfortunately it requires root) using Kotlin.
val matcher = "^mNetworkInfo .* (isA|a)vailable: (true|false)"
.toPattern(Pattern.MULTILINE)
.matcher(su("dumpsys ${Context.WIFI_P2P_SERVICE}"))
if (!matcher.find()) return "Root unavailable"
if (matcher.group(2) != "true") return "Wi-Fi Direct unavailable"
return "Wi-Fi Direct available"
This should work for Android 4.3 - 8.1. Check source code below:
https://android.googlesource.com/platform/frameworks/base/+/f0afe4144d09aa9b980cffd444911ab118fa9cbe%5E%21/wifi/java/android/net/wifi/p2p/WifiP2pService.java
https://android.googlesource.com/platform/frameworks/opt/net/wifi/+/a8d5e40/service/java/com/android/server/wifi/p2p/WifiP2pServiceImpl.java#639
https://android.googlesource.com/platform/frameworks/base.git/+/f0afe4144d09aa9b980cffd444911ab118fa9cbe/core/java/android/net/NetworkInfo.java#433
https://android.googlesource.com/platform/frameworks/base.git/+/220871a/core/java/android/net/NetworkInfo.java#415