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

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

Related

Windows Phone app not receiving push notification from Parse.com

I have followed this tutorial on setting up Parse push notification in a Windows Phone app. This is my code:
public App() {
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard XAML initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Language display initialization
InitializeLanguage();
// Show graphics profiling information while debugging.
if (Debugger.IsAttached) {
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Prevent the screen from turning off while under the debugger by disabling
// the application's idle detection.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
// Initialize the Parse client with your Application ID and .NET Key found on
// your Parse dashboard
ParseClient.Initialize("grpTmrClet8K35yeXg2HQKK8wl59VeC9ijH0I0dn", "os8EfSFq9maPBtDJ91Mq0xnWme8fLANhttTPAqKu");
// After calling ParseClient.Initialize():
this.Startup += async (sender, args) =>
{
// This optional line tracks statistics around app opens, including push effectiveness:
ParseAnalytics.TrackAppOpens(RootFrame);
// By convention, the empty string is considered a "Broadcast" channel
// Note that we had to add "async" to the definition to use the await keyword
await ParsePush.SubscribeAsync("testchannel");
};
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private async void Application_Launching(object sender, LaunchingEventArgs e) {
await ParseAnalytics.TrackAppOpenedAsync();
}
When I send a push notification from the Parse dashboard it doesn't get received. I have tried running both on the emulator (Windows Phone 8.0) and device (8.1), with app in foreground, background and closed with the same negative result.
When I use a channel like "testchannel" above and use the segment options, the channel name appears in the dropdown list of options indicating that the app is at least connecting Parse, but it just wont receive the notifications.
Hope someone can help me identify what I am missing. Thanks in advance.
If you are developing a Windows Phone 8.1 app, make sure you've enabled toast notification in the manifest file.
I don't quite understand everything about Parse just yet, but this is what works for me.
In App.xaml.cs:
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
ParseClient.Initialize("wSjuNTbtjVLRaedXvOoaf9S5cTbkuQohTulNZ2vS", "nWZMhXRet9Wotlgikb9aUdKf5GFtRiMvduw7w68z");
}
We subscribe and enable analytics OnLaunched:
protected async override void OnLaunched(LaunchActivatedEventArgs e)
//Generated codes go here
await ParsePush.SubscribeAsync("testchannel");
await ParseAnalytics.TrackAppOpenedAsync();
That would simply do the trick. You should modify the code according to your needs. Hope this helps.

Windows phone 8 notification hub unregister

Can someone show me or tell some example how to unregister from notification hub in windows phone 8. I tried on this way but it doesn't work.
public void registerForNotifications(string[] tags)
{
var channel = HttpNotificationChannel.Find("xxx");
if (channel == null)
{
channel = new HttpNotificationChannel("xxx");
channel.Open();
channel.BindToShellToast();
}
string[] tagsToSubscribeTo = tags;
channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(async (o, args) =>
{
var hub = new NotificationHub("xxx", "xxx");
await hub.RegisterNativeAsync(args.ChannelUri.ToString(), tagsToSubscribeTo);
});
}
public async void unregisterFromNotifications()
{
var channel = HttpNotificationChannel.Find("xxx");
var hub = new NotificationHub("xxx", "xxx");
await hub.UnregisterAllAsync(channel.ChannelUri.ToString());
}
You didn't say what "it didn't work" means. Did you get an error message? Did it report success but actually fail? In your questions, it really helps more if you share those things. But I'll take a stab at this anyway.
I suspect that you might be using the DefaultListenSharedAccessSignature endpoint from your Windows Phone 8 app.
According to http://msdn.microsoft.com/en-us/library/dn495373.aspx, the Listen access level grants permission to:
Create/Update registration.
Read registration.
Read all registrations for a handle.
Delete registration.
Reading that last one, I wonder if the UnregisterAllAsync method might require a higher access level to delete all registrations, rather than just one.
But rather than use the DefaultFullSharedAccessSignature endpoint, I would rather just try the UnregisterAsync method instead of UnregisterAllAsync.
Disclaimer: I have not tried this out. It may not help at all.

Windows Phone 8 HRESULT: 0X80042706

I'm developing a Windows Phone 8 Application that uses the map control. I have followed the tutorial, but I keep geeting the messagebox error: HRESULT: 0X80042706. Here is the code from the tutorial
protected override void OnNavigatedTo(NavigationEventArgs e)
{
map.ColorMode = MapColorMode.Light; map.CartographicMode = MapCartographicMode.Road; map.LandmarksEnabled = true; map.PedestrianFeaturesEnabled = true; map.ZoomLevel = 17;
routeQuery.TravelMode = TravelMode.Walking; routeQuery.QueryCompleted += rq_QueryCompleted;
base.OnNavigatedTo(e);
}
...
void rq_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e) {
if (null == e.Error) {
//Recommended way to display route on map
Route MyRoute = e.Result;
MapRoute MyMapRoute = new MapRoute(MyRoute);
map.AddRoute(MyMapRoute);
}
else
MessageBox.Show("Error occured:\n" + e.Error.Message);
}
I tried to search what kind of error HRESULT: 0X80042706 was from here, but I have no idea what that meant.
I even tried to switch the if condition to e.Error == null, but still no good. Can anyone help me?
The error is because your device does not support CHAP authentication while connecting to Virtual Disk Service (i.e. Maps)
This is because you don't have an authentication id from Microsoft.
Follow the details here ( for wp8 maps another authentication is required)
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207033(v=vs.105).aspx
I received the same error from the same tutorial, and found it was due to no internet access to my PC (and hence no map data). Restored Internet access and the error resolved itself.
Please once check your Manifestfile and select Capability option click in ID_CAP_MAP.

Always move to specific uiviewcontroller

I have a IOS app, that uses a network connection, and at times, it looses this network connection, whenever it does, I want the app to move back to a specific UIViewController.. What is the best way to achieve this?
Can I do this from the appDelegate?
Are you using the Reachability class described in the Apple documentation? If not, you should take a look at it. It will give you network status, including whether you are connected to the internet. It has a notification of network status change so you can put an observer in you app delegate or anywhere else you need it to accomplish your objective.
There is a lot of help already available on the web with examples on how to use Reachability, and this one may be something you can start with.
Update
Raachability change notifications can be used to inform your app when the connection is lost or restored. See the notification statement in the code below for the Reachability class;
static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info)
{
#pragma unused (target, flags)
NSCAssert(info != NULL, #"info was NULL in ReachabilityCallback");
NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], #"info was wrong class in ReachabilityCallback");
//We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively
// in case someon uses the Reachablity object in a different thread.
NSAutoreleasePool* myPool = [[NSAutoreleasePool alloc] init];
Reachability* noteObject = (Reachability*) info;
// Post a notification to notify the client that the network reachability changed.
[[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object: noteObject];
[myPool release];
}
For this to work you have to call startNotifier:
- (BOOL) startNotifier
{
BOOL retVal = NO;
SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
if(SCNetworkReachabilitySetCallback(reachabilityRef, ReachabilityCallback, &context))
{
if(SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode))
{
retVal = YES;
}
}
return retVal;
}

ActionScript / AIR - Determine Device Profile At Runtime?

i'm developing an application for both desktop and mobile devices and would like to use the same code base for each build.
i want to employ cacheAsBitmapMatrix on some of my display objects, but cacheAsBitmapMatrix throws an error if it's included in an AIR application with a device profile other than mobileDevice or extendedMobileDevice.
something like the following would be ideal:
if (cacheAsBitmapMatrix.isSupported)
myDisplayObject.cacheAsBitmapMatrix = new Matrix();
update using try/catch:
try {myDisplayObject.cacheAsBitmapMatrix = new Matrix();}
catch(error:Error) {}
finally {myDisplayObject.cacheAsBitmap = true;}
update:
except for television profiles, this should work as well to distinguish between mobile and desktop:
//Resoslve Profile
if (Capabilities.os.indexOf("Windows") > -1 || Capabilities.os.indexOf("Mac") > -1 || Capabilities.os.indexOf("Linux") > -1)
trace("Desktop Profile");
else
trace("Mobile Profile");
update 2:
it seems the easiest way, and perhaps the most common way to determine the profile at runtime is to call:
NativeWindow.isSupported;
from the flash.display.NativeWindow documentation:
AIR profile support: This feature is
supported on all desktop operating
systems, but is not supported on
mobile devices or AIR for TV devices.
You can test for support at run time
on desktop devices using the
NativeWindow.isSupported property. See
AIR Profile Support for more
information regarding API support
across multiple profiles.
update 3:
while testing this on the BlackBerry PlayBook simulator, NativeWindow was supported. i haven't tested this on the device to know if it's was just supported on the simulator or not. i've since started using the following to determine the difference between mobile and desktop profiles:
if (
(Capabilities.os.toLowerCase().indexOf("mac") == -1) &&
(Capabilities.os.toLowerCase().indexOf("windows") == -1) &&
(Capabilities.os.toLowerCase().indexOf("linux") == -1)
)
deviceIsMobile = true;
This document specifies device capabilities for different profiles. Since cacheAsBitmapMatrix has no availability getter listed, you'll need to check it yourself once. It must be easy to do with try/catch block.
Edit: I'll try to illustrate what I meant under "check once":
public class Capabilities2
{
private static var cacheAsBitmapMatrixChecked:Boolean;
private static var cacheAsBitmapMatrixStatus:Boolean;
public static function get cacheAsBitmapMatrixIsSupported():Boolean
{
if (cacheAsBitmapMatrixChecked) return cacheAsBitmapMatrixStatus;
var test:Sprite = new Sprite();
try
{
text.cacheAsBitmapMatrix = new Matrix();
cacheAsBitmapMatrixStatus = true;
}
catch (error:Error)
{
cacheAsBitmapMatrixStatus = false;
}
cacheAsBitmapMatrixChecked = true;
return cacheAsBitmapMatrixStatus;
}
}
Get current profile might be cleaner solution, but I don't know how to do it. Another 'idea': using document above, test capabilities and deduce profile from results, like in Einstein riddle :)
For runtime checking if your application is on mobile or on web you can also use "Capabilities.playerType"
if (Capabilities.playerType == "Desktop") {
trace ("running on mobile");
}
else {
trace ("running on web");
}