how to open application while receive call? - xamarin

In xamarin android application I have receive call using BroadcastReceiver
public override void OnReceive(Context context, Intent intent)
{
Toast.MakeText(context, "Received intent!", ToastLength.Short).Show();
DialerCallListener listener = new DialerCallListener();
SIPRegistration.call = SIPRegistration.sipManager.TakeAudioCall(intent, listener);
string str = SIPRegistration.call.PeerProfile.UriString;
}
From here I want to check my app is run in foreground/Background, and if it is background how can I bring my app to foreground and show incoming call receiving page? any help? it xamarin cross platform application.

Related

Flutter: Using path provider when app is in background

I am currently trying to implement FCM and local notifications into my Flutter app. I have successfully configured FCM and the Local notifications for normal notifications, But i also have a different type of notification that I would like to display with an Image, When my app is in the foreground the notification is displayed without error, However when I terminate the app / move it to background I get an exception when trying to save the image using path provider.
The exception:
MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)
I'm assuming this error is occurring because the path provider method channel is closed when the app is not in the foreground, Is there something I can do to fix this? Or if not the flutter_local_notifications plugin requires a filepath to a bitmap, Can I achieve saving the image and getting a path in a different way that will work in background (without path provider)?
(What I actually would like to display is an image from a link like this one: https://is1-ssl.mzstatic.com/image/thumb/WNUBiv2P6YSklHn9eA5nlg/1000x1000bb.jpeg)
Saving the image:
static Future<String> saveImage(Image image) {
final completer = Completer<String>();
image.image.resolve(ImageConfiguration()).addListener(ImageStreamListener((imageInfo,_) async {
final byteData = await imageInfo.image.toByteData(format: ImageByteFormat.png);
final pngBytes = byteData.buffer.asUint8List();
final fileName = pngBytes.hashCode;
final directory = await getApplicationDocumentsDirectory();
final filePath = '${directory.path}/$fileName';
final file = File(filePath);
await file.writeAsBytes(pngBytes);
completer.complete(filePath);
}));
return completer.future;
}
you need to register path provider in Application.java as well.
import io.flutter.plugins.pathprovider.PathProviderPlugin;
...
#Override
public void registerWith(PluginRegistry registry) {
PathProviderPlugin.registerWith(registry.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin"));
}
Now that flutter uses Kotlin as the default language for android side, here is the Kotlin code:
override fun registerWith(registry: PluginRegistry) {
io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
PathProviderPlugin.registerWith(registry.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin"))
}
This error occured because you did not registered flutter pluging in android MainAcitivity.
Your must change onCreate method of your MainActivity as below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this.getFlutterEngine());
}

How to check internet connection continuously in Xamarin.Android Native?

My application is completely based on internet and it does not work without it, when the internet is not available or it is slow my application is getting stopped unfortunately.
I tried to implement try, catch but it is not helping me out as it is not throwing any exception, then I thought that I have to check the internet connectivity continuously till the app is running and stop any activity from performing and set a popup to connect to the internet.
I am able to get the popup whenever I call a method which has the following code inside it,
ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
NetworkInfo networkInfo = connectivityManager.ActiveNetworkInfo;
if (networkInfo == null)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Network");
alert.SetMessage("Please turn of your Wifi or Mobile Data From Settings");
alert.SetPositiveButton("OK", (senderAlert, args) => {
Intent intent = new Intent(Android.Provider.Settings.ActionSettings);
StartActivity(intent);
});
alert.SetNegativeButton("Cancel", (senderAlert, args) => {
Toast.MakeText(this, "Cancelled!", ToastLength.Short).Show();
Finish();
});
Dialog dialog = alert.Create();
dialog.Show();
But I am unable to get the connection checked continuously, So Can some one Please help me to complete get this functionality in my application.
You need to use a BroadcastReceiver to monitor network changes.
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { "android.net.conn.CONNECTIVITY_CHANGE" })]
[Android.Runtime.Preserve(AllMembers = true)]
public class ConnectivityChangeBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
if (intent.Action != ConnectivityManager.ConnectivityAction)
return;
//Check if is connected and raise a custom event or store
//the current in a static global variable
}
}
}
In Android 7.0, you need to remove IntentFilter from the class and register the receiver.
var receiver = new ConnectivityChangeBroadcastReceiver();
Application.Context.RegisterReceiver(receiver, new IntentFilter(ConnectivityManager.ConnectivityAction));
Another option is to use the ConnectivityPlugin https://github.com/jamesmontemagno/ConnectivityPlugin , which is easier to use.
CrossConnectivity.Current.ConnectivityChanged += HandleConnectivityChanged;
void HandleConnectivityChanged (object sender, ConnectivityChangedEventArgs e)
{
// You can check the network status in
//e.IsConnected
}
Note that The ACCESS_NETWORK_STATE and ACCESS_WIFI_STATE permissions are required.

Create a Share button on Windows Phone 8, 8.1 and 10 (Mobile)

How can I create a Share button (that share a defined mesage to another player contact) as the below image on Windows Phone 8, 8.1 and 10 (Mobile):
To create this script to share on Android Device I use the following code:
public class ShareScript : MonoBehaviour {
string subject = "Subject";
string body = "Body";
public void OnAndroidTextSharingClick()
{
StartCoroutine(ShareAndroidText());
}
IEnumerator ShareAndroidText()
{
yield return new WaitForEndOfFrame();
//execute the below lines if being run on a Android device
#if UNITY_ANDROID
//Reference of AndroidJavaClass class for intent
AndroidJavaClass intentClass = new AndroidJavaClass ("android.content.Intent");
//Reference of AndroidJavaObject class for intent
AndroidJavaObject intentObject = new AndroidJavaObject ("android.content.Intent");
//call setAction method of the Intent object created
intentObject.Call<AndroidJavaObject>("setAction", intentClass.GetStatic<string>("ACTION_SEND"));
//set the type of sharing that is happening
intentObject.Call<AndroidJavaObject>("setType", "text/plain");
//add data to be passed to the other activity i.e., the data to be sent
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_SUBJECT"), subject);
//intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TITLE"), "Text Sharing ");
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TEXT"), body);
//get the current activity
AndroidJavaClass unity = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");
//start the activity by sending the intent data
AndroidJavaObject jChooser = intentClass.CallStatic<AndroidJavaObject>("createChooser", intentObject, "Share Via");
currentActivity.Call("startActivity", jChooser);
#endif
}
}
Call DataTransferManager.ShowShareUI to show the sharing pane.
Handle the DataTransferManager.DataRequested event to provide the data when the user choses to share.
private void DataRequested(DataTransferManager sender, DataRequestedEventArgs e)
{
DataRequest request = e.Request;
request.Data.Properties.Title = "Share Text Example";
request.Data.Properties.Description = "An example of how to share text.";
request.Data.SetText("Hello World!");
}
See the Share data docs on MSDN for more info.
In Unity you can call these in an #if NETFX_CORE block so it runs only when using the Windows Runtime and not Mono. See Windows Store Apps: WinRT API in C# scripts. If you target Windows 10 then there are plug-ins at https://github.com/microsoft/unityplugins which include sharing. For earlier targets there are commercial plugins.

Trying to run websocket server from my local PC

I am trying to develop a web-socket server app for my UWP Windows 10 App.
This is my code:
class Server
{
public async void Start()
{
MessageWebSocket webSock = new MessageWebSocket();
//In this case we will be sending/receiving a string so we need to set the MessageType to Utf8.
webSock.Control.MessageType = SocketMessageType.Utf8;
//Add the MessageReceived event handler.
webSock.MessageReceived += WebSock_MessageReceived;
//Add the Closed event handler.
webSock.Closed += WebSock_Closed;
Uri serverUri = new Uri("ws://127.0.0.1/motion");
try
{
//Connect to the server.
await webSock.ConnectAsync(serverUri);
//Send a message to the server.
await WebSock_SendMessage(webSock, "Hello, world!");
}
catch (Exception ex)
{
//Add code here to handle any exceptions
}
}
//The MessageReceived event handler.
private void WebSock_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
{
DataReader messageReader = args.GetDataReader();
messageReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
string messageString = messageReader.ReadString(messageReader.UnconsumedBufferLength);
//Add code here to do something with the string that is received.
}
//The Closed event handler
private void WebSock_Closed(IWebSocket sender, WebSocketClosedEventArgs args)
{
//Add code here to do something when the connection is closed locally or by the server
}
//Send a message to the server.
private async Task WebSock_SendMessage(MessageWebSocket webSock, string message)
{
DataWriter messageWriter = new DataWriter(webSock.OutputStream);
messageWriter.WriteString(message);
await messageWriter.StoreAsync();
}
}
It errors here:
await webSock.ConnectAsync(serverUri);
with this error:
Not found (404). (Exception from HRESULT: 0x80190194)
I don't have any personal experience with it, but you might want to give IotWeb HTTP Server a try. It seems to be a portable embedded HTTP and web socket server that also supports UWP and can be run inside Windows Store and Windows 10 IoT Core applications.
Judging from its repository, it's rather new and not exactly mature, nor does it have a lot of documentations or samples available. There's a NuGet package available, though.
Unfortunately I didn't manage to find any other alternative yet.
The code
await webSock.ConnectAsync(serverUri);
Is try to connect to existing server at ws://127.0.0.1/motion, Not to deploy a server on this address.
You can look for ways to build a c# WebSocket server at the follwing links:
https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_server
http://www.codeproject.com/Articles/57060/Web-Socket-Server

Launch Cordova Windows App with Parameters

Am finding hard to launch Cordova Windows App, from another native Windows App.
Using Protocol invocation, I am passing few parameters to Cordova Windows App, to see if the Cordova app identifies those parameters from the Windows Native App.
Is there anyway to pass Parameters from native Windows App to Cordova App, so that Cordova App identifies the parameters as arguments?
In native windows 8 store app I am using app protocol association to send parameters one app to another app. like
in sender app:
mainpage.xaml.cs on button click
var url = "apptest:?" + name;
Uri uri = new Uri(url);
await Launcher.LaunchUriAsync(uri);
in received app
Package.appxmanifest:
Declarations --> available declarations add --> protocol --> name = apptest
app.xaml.cs
protected override void OnActivated(IActivatedEventArgs args)
{
if (args.Kind == ActivationKind.Protocol)
{
ProtocolActivatedEventArgs protocolArgs = args as ProtocolActivatedEventArgs;
var rootFrame = new Frame();
rootFrame.Navigate(typeof(MainPage), protocolArgs);
Window.Current.Content = rootFrame;
}
Window.Current.Activate();
}
mainpage.xaml.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ProtocolActivatedEventArgs pa = e.Parameter as ProtocolActivatedEventArgs;
if(pa != null)enter code here
{
string qS = pa.Uri.Query;
if (!string.IsNullOrEmpty(qS))
{
Txt_name.Text = qS;
}
}
}
in this way i will take the data from sender app.
Same like is there any way to receive data from windows 10 native app to cordova app. it is very hard to find the solution. not able to find the exact piece of code.

Resources