xamarin.forms android service run twice after restarting it - xamarin.android

I have this code that create an android service
[Service]
public abstract class LongRunningTaskService : Service
{
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Logs.Info("service started: " + this.GetType().ToString());
try
{
Tasks.RunTask(() =>
{
try
{
Task.run(() => SomeTaskFunction);
StopSelf();
Logs.Info("service ended successfully from main task");
}
catch (Android.OS.OperationCanceledException e)
{
Logs.Warning("Error in Tasks.RunTaskWithoutWaitForResult", e);
}
});
return StartCommandResult.NotSticky;
}
catch (Exception e)
{
Logs.Warning("error in OnStartCommand", e);
return StartCommandResult.NotSticky;
}
}
public override void OnDestroy()
{
try
{
Logs.Info("service destroyed: " + this.GetType().ToString());
base.OnDestroy();
}
catch (Exception e)
{
Logs.Warning("Error in service destroyed: " + this.GetType().ToString(), e);
}
}
}
when i create the service the first time it works ok, but when i destroy it from outside the service and recreate it with the same function to run there are 2 tasks running at the same time.
what am i doing wrong ?

Related

Close(kill) another app in my application by package name

I would like to close(kill) another app in my application by package name. I am trying something like this, but this code don't close any app. what am i doing wrong?
public void amKillProcess(string package_name)
{
ActivityManager am = (ActivityManager)this.GetSystemService(Context.ActivityService);
IList<RunningAppProcessInfo> runningProcesses = am.RunningAppProcesses;
foreach (RunningAppProcessInfo runningProcess in runningProcesses)
{
if (runningProcess.ProcessName.Contains(package_name))
{
Android.OS.Process.SendSignal(runningProcess.Pid, Signal.Kill);
am.KillBackgroundProcesses(runningProcess.ProcessName);
}
}
}
P.S I added android.permission.KILL_BACKGROUND_PROCESSES and by this code i can close only my own app
If you want to kill a background app , check the following code
public void amKillProcess(string package_name)
{
ActivityManager am = (ActivityManager)this.GetSystemService(Context.ActivityService);
var runningProcesses = am.RunningAppProcesses;
foreach (RunningAppProcessInfo runningProcess in runningProcesses)
{
if (runningProcess.ProcessName.Contains(package_name))
{
Android.OS.Process.KillProcess(runningProcess.Uid);
}
}
}
And if you want to kill a foreground app, you could use Adb
public class SuUtil
{
private static Java.Lang.Process process;
public static void kill(string packageName)
{
initProcess();
killProcess(packageName);
close();
}
private static void initProcess()
{
if (process == null)
try
{
process = Runtime.GetRuntime().Exec("su");
}
catch (IOException e)
{
}
}
private static void killProcess(string packageName)
{
System.IO.Stream output = process.OutputStream;
Java.Lang.String cmd = new Java.Lang.String("am force-stop " + packageName + " \n");
try
{
output.Write(cmd.GetBytes());
output.Flush();
}
catch (IOException e)
{
}
}
private static void close()
{
if (process != null)
try
{
process.OutputStream.Close();
process = null;
}
catch (IOException e)
{
}
}
}

how to connect TCP Socket server client with authentication in Dart

I have a java and .Net solution, but now i need to implement in Dart please help me out.
This is may java source
private Handler handler;
private int iCounter =1;
public StartQuickClient(int InstanceId)
{
try
{
handler = MarketData.GetInstance();
handler.setEventHandler(this);
handler.setAddress("122.184.137.44");
handler.setPort(9898);
handler.setUserCredentials("PREM", "xxxxx");
if (handler.connect())
{
System.out.println("Connect initiated "+ InstanceId);
}
else
{
System.out.println("Connect failed ");
}
}
catch (Exception e)
{
}
}
public static void main(String[] args) {
Random rnd = new Random();
int InstanceId = rnd.nextInt(9999);
StartQuickClient startQuickClient = new StartQuickClient(InstanceId);
}
This is the connect method:
public boolean connect()
{
try {
if (quickEvent == null) {
throw new Exception("No event handler is set, will not initiate the connection");
}
if (configuration.SERVER_ADDRESS == null) {
throw new Exception("Blank Server Address");
}
if (configuration.SERVER_PORT <= 0) {
throw new Exception("Blank Server Port");
}
tcpConnection = new TcpConnection(this, configuration);
if (isNewVersionAuthentication) {
tcpConnection.enableNewversionAuthentication();
}
tcpConnection.connect();
} catch (Exception e) {
e.printStackTrace();
mLog.error("No event handler is set and Blank Server Address,Port will not initiate the connection :" + e.getMessage());
return false;
}
return true;
}
please help me out if any one knows, i am new for dart,need any plug or how to do

MQTT subscribe not working in Android

I am trying to get a message from the MQTT Broker using the Android service, but it does not work.
The library used is the Paho MQTT library, and the source code is as follows.
final MqttConnectOptions hIoTConnectionOptions = new MqttConnectOptions();
hIoTConnectionOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
hIoTConnectionOptions.setAutomaticReconnect(true);
hIoTConnectionOptions.setCleanSession(false);`
try {
hIoTAndroid = new MqttClient(ip_addr, clientID, new MemoryPersistence());
IMqttToken conToken = hIoTAndroid.connectWithResult(hIoTConnectionOptions);
hIoTAndroid.setCallback(MqttMessagingService.this);
conToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(TAG, "onSuccess");
hIoTAndroid.setCallback(MqttMessagingService.this);
try {
IMqttToken subToken = hIoTAndroid.subscribeWithResponse(subtopic, 1);
subToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.i(TAG, "Successfully subscribe to: " + subtopic);
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "Couldn't subscribe to: " + subtopic);
}
});
} catch (MqttException | NullPointerException ex) {
ex.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "Failed Connection");
}
});
} catch (MqttException ex) {
Log.d(getClass().getCanonicalName(), "Connection attempt failed with reason code = " + ex.getReasonCode() + ":" + ex.getCause());
}
#Override
public void connectComplete(boolean reconnect, String serverURI) {
Log.d(TAG, "Connection is established....");
}
#Override
public void connectionLost(Throwable cause) {
Log.d(TAG, "The Connection was lost,,");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i(TAG, new String(message.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.d(TAG, "Sent Message !");
}
The publish and deliveryComplete functions work fine, but the subscribe function and messagArrived do not work. Why?

Check SerialPort Exist Modem?

In C# 2005, I used the Nokia E63, I want to check SerialPort Exist Modem, While it run does not get run COM port, you see my code
private void btnGetPort_Click(object sender, EventArgs e)
{
cmbPort.Items.Clear();
foreach (string portName in SerialPort.GetPortNames())
{
try
{
using (SerialPort sp = new SerialPort(portName, 9600))
{
if (!(sp.IsOpen)) sp.Open();
sp.DiscardInBuffer();
sp.DiscardOutBuffer();
sp.Write("AT\r\n");
System.Threading.Thread.Sleep(100);
string response = sp.ReadExisting();
if (response == "OK")
{
cmbPort.Items.Add(portName);
}
}
}
catch (Exception ex)
{
continue;
}
}
}

Blackberry - send sms timeout

I have simple code to send sms. It works fine. Just little problem. How can I figure out that sms can not be send? Some timeout for Connection or other way? Let's say if there is no network, no sim card or no credit. Thanks
Here is code:
public static void sendSMS(String content, String number) {
MessageConnection mc = null;
TextMessage msg;
try {
mc = (MessageConnection) Connector.open("sms://" + number,Connector.WRITE,true);
msg = (TextMessage) mc.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setPayloadText(content);
mc.send(msg);
} catch (final Exception e) {
e.printStackTrace();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(e.getMessage());
}
});
} finally {
try {
if (mc != null) {
mc.close();
}
} catch (IOException e) {
}
}
}
private void sendSMS(final String no, final String msg) {
try {
new Thread() {
public void run() {
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Message Sent Successfully : Datagram");
Dialog.alert("Message Sent Successfully");
} catch (Exception e) {
System.out.println("Exception **1 : " + e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector.open("sms://" + no);
//generate a new text message
TextMessage tmsg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
//set the message text and the address
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
//finally send our message
conn.send(tmsg);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Message Sent Successfully : TextMessage");
Dialog.alert("Message Sent Successfully : TextMessage");
} catch (Exception e) {
System.out.println("Exception **1 : " + e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
}
}.start();
} catch (Exception e) {
System.out.println("Exception 5 : " + e.toString());
e.printStackTrace();
}

Resources