the environment is Xamarin.forms in android,
but there are no Information about this.
how can i get WifiConfiguration from callback.onstarted ?
OR can i WifiManager.LocalOnlyHotspotReservation get value from callback.onstarted ?
please check below code, the code is about to using wifi AP over oreo version
when java code, i refer this article
a link
private WifiManager wifiManager;
private WifiManager.LocalOnlyHotspotReservation reservation;
void SetHotSpot()
{
wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);
WifiManager.LocalOnlyHotspotCallback callback = new WifiManager.LocalOnlyHotspotCallback();
callback.OnStarted( reservation);
wifiManager.StartLocalOnlyHotspot(callback, new Handler());
}
void getConfiguration(object sender, System.EventArgs e)
{
if (reservation != null)
{
Log.Debug("config", reservation.WifiConfiguration.Ssid);
Log.Debug("config", reservation.WifiConfiguration.NetworkId.ToString());
Log.Debug("config", reservation.WifiConfiguration.PreSharedKey);
Log.Debug("config", reservation.WifiConfiguration.Bssid);
}
}
but when i click button, reservation is null. so Log Dose not output anything.
I converted the Java code here and came up with the following solution which seems to be working kindly take a look and let me know whether or not it works for you.
Add a Callback class that inherits from WifiManager.LocalOnlyHotspotCallback and pass the Activity in my case it is the MainActivity.
public class OreoWifiManagerCallback : WifiManager.LocalOnlyHotspotCallback
{
private const string TAG = nameof(OreoWifiManagerCallback);
private MainActivity mainActivity;
public OreoWifiManager(Activity _activity)
{
if (_activity.GetType() == typeof(MainActivity))
mainActivity = (MainActivity)_activity;
}
public override void OnStarted(WifiManager.LocalOnlyHotspotReservation reservation)
{
base.OnStarted(reservation);
Log.Debug(TAG, "Wifi Hotspot is on now");
mainActivity.mReservation = reservation;
}
public override void OnFailed([GeneratedEnum] LocalOnlyHotspotCallbackErrorCode reason)
{
base.OnFailed(reason);
Log.Debug(TAG, "onStopped: ");
}
public override void OnStopped()
{
base.OnStopped();
Log.Debug(TAG, "onFailed: ");
}
}
Then add a property in the MainActivity to keep track of the reservations
public WifiManager.LocalOnlyHotspotReservation mReservation { get; set; }
And then use these methods to turn on or off wifi in that Activity, also note that you can have a global field for wifi manager if needed.
private void TurnOnHotspot()
{
var WifiManager = (WifiManager)this.Application.GetSystemService(Android.Content.Context.WifiService);
WifiManager.StartLocalOnlyHotspot(new OreoWifiManagerCallback(this), new Handler());
}
private void TurnOffHotspot()
{
if (mReservation != null)
{
mReservation.Close();
}
}
Good luck
Feel free to revert at any time
Related
I am trying to create proof of concept to find nearby bluetooth low energy devices.
Here is my try:
public async void StartScan()
{
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
adapter.Enable();
await Task.Delay(TimeSpan.FromMinutes(1)); // rode that this my help but didn't
if (adapter == null) return;
BluetoothLeScanner scanner = adapter.BluetoothLeScanner;
scanner?.StartScan(_callback);
}
The callback class:
public class MyScanCallback : ScanCallback
{
public override void OnBatchScanResults(IList<ScanResult> results)
{
base.OnBatchScanResults(results);
}
public override void OnScanResult(ScanCallbackType callbackType, ScanResult result)
{
base.OnScanResult(callbackType, result);
}
public override void OnScanFailed(ScanFailure errorCode)
{
base.OnScanFailed(errorCode);
}
}
I`ve spent some time looking in Internet but each solutions gives me always the same error. Everytime the code is executed it goes into OnScanFailed method with enum paramter ApplicationRegistrationFailed.
Does anyone faces the same issue?
PS. I have added required premissions.
Can anybody please tell me? I am making a sample and want to detect miss call on a particular number. Suppose I opened the dialler with the number (0123456789) and when call on this number then detect missed call on this number. how can I do that. Please help ..
Check the flowing code ->
In your broadcast receiver check that if the call is received or not. Then you can find the call status.
public class CallBroadcast extends BroadcastReceiver {
private static boolean isMissedCall;
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
// Ringing
isMissedCall = true;
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
// Call Received
isMissedCall = false;
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
// Call Drop
// If don't receive call then it will be missed call
if(isMissedCall){
// do your code for missed call
}
}
}
}catch (Exception e){e.printStackTrace();}
}
}
I have seen plenty of examples of how to use Android TextToSpeak in an Activity, and have also managed to get this to work just fine. I've also managed to get it to work using a bound service in a plugin, but it seems overcomplicated for my purposes. Here is my VoiceService class:
public class VoiceService : IVoiceService, TextToSpeech.IOnInitListener
{
public event EventHandler FinishedSpeakingEventHandler;
private TextToSpeech _tts;
public void Init()
{
// Use a speech progress listener so we get notified when the service finishes speaking the prompt
var progressListener = new SpeechProgressListener();
progressListener.FinishedSpeakingEventHandler += OnUtteranceCompleted;
//_tts = new TextToSpeech(Application.Context, this);
_tts = new TextToSpeech(Mvx.Resolve<IMvxAndroidCurrentTopActivity>().Activity, this);
_tts.SetOnUtteranceProgressListener(progressListener);
}
public void OnInit(OperationResult status)
{
// THIS EVENT NEVER FIRES!
Console.WriteLine("VoiceService TextToSpeech Initialised. Status: " + status);
if (status == OperationResult.Success)
{
}
}
public void Speak(string prompt)
{
if (!string.IsNullOrEmpty(prompt))
{
var map = new Dictionary<string, string> { { TextToSpeech.Engine.KeyParamUtteranceId, new Guid().ToString() } };
_tts.Speak(prompt, QueueMode.Flush, map);
Console.WriteLine("tts_Speak: " + prompt);
}
else
{
Console.WriteLine("tts_Speak: PROMPT IS NULL OR EMPTY!");
}
}
/// <summary>
/// When we finish speaking, call the event handler
/// </summary>
public void OnUtteranceCompleted(object sender, EventArgs e)
{
if (FinishedSpeakingEventHandler != null)
{
FinishedSpeakingEventHandler(this, new EventArgs());
}
}
public void Dispose()
{
//throw new NotImplementedException();
}
public IntPtr Handle { get; private set; }
}
Note that the OnInit method never gets called.
In my viewmodel I'd like to do this:
_voiceService.Init();
_voiceService.FinishedSpeakingEventHandler += _voiceService_FinishedSpeakingEventHandler;
... and then later ...
_voiceService.Speak(prompt);
When I do this I get these messages in the output:
10-13 08:13:59.734 I/TextToSpeech( 2298): Sucessfully bound to com.google.android.tts
(happens when I create the new TTS object)
and
10-13 08:14:43.924 W/TextToSpeech( 2298): speak failed: not bound to TTS engine
(when I call tts.Speak(prompt))
If I was using an activity I would create an intent to get this to work, but I'm unsure how to do that in a plugin.
Thanks in advance,
David
Don't implement Handle yourself, instead derive from Java.Lang.Object
public class VoiceService : Java.Lang.Object, IVoiceService, TextToSpeech.IOnInitListener
and remove your Dispose() and Handle implementation
More info here: http://developer.xamarin.com/guides/android/advanced_topics/java_integration_overview/android_callable_wrappers/
Also, I suggest you take an async approach when implementing your service, which would make calling it from view-model something like
await MvxResolve<ITextToSpeechService>().SpeakAsync(text);
I am receiving a range of signals from onReceive using BroadcastReceiver in my iBeaconProject. What I would like to do is to only keep track of one of the beacons (which I specify) and it's distance from my phone to the beacon. Any ideas, guys? Please help me! I'm using http://www.radiusnetworks.com. I am getting a range of signals using the following onReceive function. How do I go about doing it? Thanks all in advance!
BroadcastReceiver bReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
int countBea = 0;
if (intent.getAction().equals(intentname) && intent.getExtras() != null && intent.getExtras().containsKey(intentname)) {
Collection<IBeacon> beaconsCol = (Collection<IBeacon>)intent.getExtras().getSerializable(intentname);
for (IBeacon bea : beaconsCol) {
Log.d("beac receive!","receive! "+bea.getProximityUuid()+" "+bea.getMajor()+" "+bea.getMinor()+" "+bea.getAccuracy()+" "+bea.getProximity()+" "+bea.getRssi()+" "+bea.getTxPower());
countBea++;
if(((mainActivity)getActivity()).UUIDValue.equalsIgnoreCase(bea.getProximityUuid())
&& ((mainActivity)getActivity()).MajorValue == bea.getMajor()
&& ((mainActivity)getActivity()).MinorValue == bea.getMinor()) {
update(bea.getProximityUuid(), +bea.getMajor(), bea.getMinor(), bea.getAccuracy());
} else if (((mainActivity)getActivity()).UUIDValue.equalsIgnoreCase(bea.getProximityUuid())
&& (((mainActivity)getActivity()).MajorValue == 0 ||
((mainActivity)getActivity()).MinorValue == 0)) {
updateNILMajorMinor();
} else {
updateMultipleBeaconsDetected();
}
}
System.out.println("COUNTBEAC " + countBea);
}
}
};
Good to see the for-each loop.
Inside it, you can identify the beacon that you want to keep track of,
for (IBeacon bea : beaconsCol) {
//in the following if, identify the specified beacon
// this will remain the same for every refresh
if(bea.getProximityUuid().equals("match it here") && bea.getMajor()==major
&& bea.getMinor()==minor){
//now display that beacon's proximity and accuracy
//the same code will update a textview or notification every time
// here you will have 1 beacon at a time, can add that to a global list
}
}
Can you give a precise idea for the implementation?
does your code enter onReceive periodically?
I have never seen anything mention using the Radius Networks SDK by listening for broadcasts. Instead they ask that you implement certain interfaces and register them with an IBeaconManager.
You may find their code samples useful. That page contains the following snippet, which you may recognize as equivalent to the code in your question.
public class RangingActivity extends Activity implements IBeaconConsumer, RangeNotifier {
private static final String TAG = RangingActivity.class.getName();
private IBeaconManager iBeaconManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
iBeaconManager = IBeaconManager.getInstanceForApplication(this);
iBeaconManager.bind(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
iBeaconManager.unBind(this);
}
#Override
public void onIBeaconServiceConnect() {
iBeaconManager.setRangeNotifier(this);
try {
// edit this to match the UUID of your beacon
// or leave null to detect everything
String uuid = null;
Region region = new Region("myRangingUniqueId", uuid, null, null);
iBeaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
Log.e(TAG, "problem while starting ranging", e);
}
}
#Override
public void didRangeBeaconsInRegion(Collection<IBeacon> iBeacons, Region region) {
if (!iBeacons.isEmpty()) {
double accuracy = iBeacons.iterator().next().getAccuracy();
Log.i(TAG, "The first iBeacon I see is about " + accuracy + " meters away.");
}
}
}
In one of my app i wanted to check the service state of the android phone
before sending sms. I have used the following code to do that
//check service
ServiceState pstate = new ServiceState();
if(pstate.getState() != ServiceState.STATE_IN_SERVICE)
{
Log.v(TAG,"service state" +pstate.getState());
Toast.makeText(Myactivity.this, "error string", 2000).show();
return;
}
But the code always returns with OUT_OF_SERVICE ( value of 1 in +pstate.getState)
Please let me know what is the reliable way to check whether the phone is in STATE_IN_SERVICE or not?
This code was checked in FROYO version.
Not a satisfactory answer really, but I've had he same problem and kept wasting time, but it would just not work on my FROYO version aswell.
But using the TelephonyManager and PhoneStateListener this worked perfectly fine. For your case I'd suggest using a wrapper instead of instantiating the ServiceState directly, ie
//declare current state
ServiceState myServiceState = new ServiceState();
PhoneStateListener listener = null; // not sure if this is needed really..
// nifty getter
public ServiceState getServiceState(){ return myServiceState; }
//setup listener (eg. in onCreate)
TelephonyManager tm = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
listener = new PhoneStateListener() {
#Override
public void onServiceStateChanged(ServiceState serviceState){
myServiceState = serviceState;
}
};
tm.listen(listener,PhoneStateListener.LISTEN_SERVICE_STATE);
// to be called when destroying your context
public void unregisterListener(){
// something like..
tm.listen(listener,PhoneStateListener.LISTEN_NONE);
}
//check service
ServiceState pstate = getServiceState();
if(pstate.getState() != ServiceState.STATE_IN_SERVICE)
{
Log.v(TAG,"service state" +pstate.getState());
Toast.makeText(Myactivity.this, "error string", 2000).show();
return;
}
A lazier solution would be moving the listener-setup into the getter and registering it only when actually called, if ever, and only saving if the service is available. ie
//declaration
boolean isAvailable = false;
PhoneStateListener listener = null;
// more nifty getter
public boolean isServiceAvailable(){
if (listener == null){
//setup listener if not yet done
TelephonyManager tm = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
listener = new PhoneStateListener() {
#Override
public void onServiceStateChanged(ServiceState serviceState){
isAvailable = serviceState.getState() == ServiceState.STATE_IN_SERVICE;
}
};
tm.listen(listener,PhoneStateListener.LISTEN_SERVICE_STATE);
}
return isAvailable;
}
// to be called when destroying your context
public void unregisterListener(){
// something like..
if (lister != null){
tm.listen(listener,PhoneStateListener.LISTEN_NONE);
}
}
//check service
if(! isServiceAvailable())
{
Log.v(TAG,"service state" +pstate.getState());
Toast.makeText(Myactivity.this, "error string", 2000).show();
return;
}
But be aware, that would require the listener to get called immediately upon registration, otherwise you'll end up with arbitrary results - so make sure to check that.