block incoming call in blackberry - blackberry

I am developing an app which blocks incoming calls. Currently, when an incoming call arrives on the device, it is blocked. But after returning from the blocked call, the screen turns to the dial call screen, and shows a dialog to alert that you have a missed call.
I want to block the incoming call, then when hung up, the screen is the home screen. How do I make this happen?
My second question: what is the permission in blocking incoming call? How do I add it to my app? I added "ApplicationPermissions.PERMISSION_IDLE_TIMER" but it's not useful.
Edit1:
this is my code in my application.
private void blockincomingcall(){
int master_volume= net.rim.device.api.system.Alert.getVolume(); //net.rim.device.api.notification.NotificationsManag er.getMasterNotificationVolume();
System.out.println("Master Volume "+master_volume);
net.rim.device.api.system.Alert.setVolume(0);
int alert_volume = Alert.getVolume();
Main.log("Master Volume after setting "+alert_volume);
int notifi_volume = NotificationsManager.getMasterNotificationVolume();
Main.log("Master Volume 1 after setting "+notifi_volume);
EventInjector.KeyCodeEvent ev1 = new EventInjector.KeyCodeEvent(EventInjector.KeyCodeEvent.KEY_DOWN, ((char) Keypad.KEY_END), KeypadListener.STATUS_ALT, 100);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
EventInjector.invokeEvent(ev1);
EventInjector.invokeEvent(ev1);
net.rim.device.api.system.Alert.setVolume(master_volume);
//System.out.println("Master volume 2 "+master_volume);
requestBackground();
}
when, it runs on os5.0 it can block calls. but the screen will turn to the dial screen,and show a notify dialog that a new incoming call. and the volume set is no effect. it runs ok on os 7.0 and 6.0 but no effect on volume set. what should i do ,thank you

Thats a good piece of malware, but anyway:
Detect incoming call
Terminate it.
Put your app on foreground again.
For #1 You need to detect active calls (use PhoneListener class). #2 is the most difficult step and you are going to need key injection to accomplish it. It is a bit hackish:
EventInjector.KeyCodeEvent ev = new EventInjector.KeyCodeEvent(EventInjector.KeyCodeEvent.KEY_DOWN, ((char)Keypad.KEY_END), KeypadListener.STATUS_ALT);
EventInjector.invokeEvent(ev);
The #3 point can be done in two different ways:
3.1: Pass a reference to your app to the PhoneListener implementation and then call <YourUiApplication>.requestForeground()
3.2: Given that code in PhoneListener runs inside the phone app (this should answer your second question), call:
UiApplication.getUiApplication().requestBackground();

Related

Distinct Stream in Dart

I'm writing a flutter app which sends commands via BlueTooth (FlutterBlue) to a device. The device controlls some LEDs.
The communication is working in general quite well but:
On the UI I have a slider controlling the light intensity. When I pull the slider there are more values generated than the bluetooth backend can handle.
In my first implementation I was sending the data directly to the bluetooth characteristic, resulting in exceptions from the bluetooth backend and some values get lost. It's hard to fade light down to zero.
In my second approach I'm using a stream and an await for loop to send the data. Now all values are send without any exceptions but it takes several seconds after releasing the slider until all values are send. Since I want direct visual feedback on the LEDs, this is not an option.
Since there are multiple commands of the same type to be send, I can skip all commands of the same type which were added while the bluetooth send routine was processing a write event.
I saw that there is a Stream.Distinct method but: It returns a new stream. So I have to exit my await for loop and handle the new stream.
Is there a way of removing undesired events from an existing stream without creating a new stream where I have to listen to?
Here is what I'm doing:
class MyBlueToothDevice {
BluetoothDevice _device;
List<BluetoothCharacteristic> _characteristics =
List<BluetoothCharacteristic>();
final _sendStream = StreamController<Tuple2<SendCommands, List<int>>>();
MyBlueToothDevice(this._device) {
_writeNext();
}
Future<void> write(SendCommands command, List<int> value) async {
if (isConnected) {
_sendStream.add(Tuple2<SendCommands, List<int>>(command, value));
// await _characteristics[command.index].write(value).catchError((value) {
// print("Characteristics.write error: $value");
// });
}
}
Future<void> _writeNext() async {
await for (var tuple in _sendStream.stream) {
await _characteristics[tuple.item1.index]
.write(tuple.item2)
.catchError((value) {
print("Characteristics.write error: $value");
});
}
}
}
The best solution is to use application state management to receive all the events from your slider. The state manager will then rate-limit the messages to the device to something it can handle, and also ensure that the most recent message is not lost.
A very basic solution would receive the slider value and update the value in the state manager. A periodic timer with a suitable rate could then update that value to the device; possibly only if the value actually changed since the last time it was sent.

How to test if Xamarin Android app closes

I am writing my first Android app, using Xamarin. I have an Exit button that, when clicked, closes the app. I want a test in Xamarin UITest that verifies clicking the button closes the app. I messed around with it for a while and finally found something that allows the test to pass.
In the app:
exitButton.Click += (o, e) =>
{
int pid = Android.OS.Process.MyPid();
Android.OS.Process.KillProcess(pid);
};
In UITest:
[Test]
public void ExitButtonClosesTheScreen()
{
try
{
app.Tap(c => c.Button("exitButton"));
Assert.Fail("App remains open.");
}
catch (System.Exception e)
{
Assert.AreEqual("The underlying connection was closed: The connection was closed unexpectedly.", e.InnerException.InnerException.InnerException.Message);
}
}
The test now passes so I guess I'm happy. My question is, is this really the best way to do this? Or is there a better way that I wasn't able to find?
Edit: Unfortunately, this is not the answer. This method allows the test to pass in VS but fails when I run it in App Center. Is there another way to run this test? Or is this something that is simply not testable with UITest? Thank you.
First of all the right code for closing the Application as per me is using finish affinity
In an Activity:
this.FinishAffinity();
In a Fragment:
this.Activity.FinishAffinity();
After doing this AppCenter should be able to figure that your app is closed.
I did a brief read up on this the other day for something similar and I am certain that the ActivityManager class would be the best way to go about this.
https://developer.xamarin.com/api/type/Android.App.ActivityManager/
There is a method within this class called RunningAppProcesses which returns a list of application processes that are running on the device - and from there I guess you can assert if your app process is on the list or not.
Hope this helps
After almost 4 years, i've encountered with the same issue.
I will do it this way in your case:
[Test]
public void ExitButtonClosesTheScreen()
{
app.Tap(c => c.Marked("exitButton"));
/** I asume exitButton click action will just exit,
no popups or alerts appear before exiting. **/
app.WaitForNoElement(q => q.Marked("exitButton"),
"Timeout waiting for element exitButton",
new TimeSpan(0, 0, 30));
AppResult[] result = app.Query();
Assert.IsTrue(result.Length == 0);
}
app.Query() returns all views visible by default, unless a query is especified by a lambda expression, as you should alredy know.
If the Application is gone, the Views visible will be 0, and as such, app.query() will return and array lenght of 0.
For WaitForNoElement's timeout I use a TimeSpan of 30 seconds, but you can use whatever timeout you prefer for this operation, i just considered 30 seconds will be ok.

How is the synchronization mode in a IoT application handled?

I am doing an IoT project. A typical scenario is:
I need to control the device to move to a coordinate (x, y)
Then I need to get the current coordinate to decide what to do next.
I use MQTT to communicate with devices. So in my code, I express the operations like this in Blockly:
//javascript
robot.move(x, y);
if(robot.x > 100) {
// do something...
}
Obviously, move(..) method is an asynchronous one, it just publishes the command and does not wait for the completion.
Due to the messaging pattern, even I make move(..) as an async function and apply await. I still don't think it works, because I only get the callback about the message is delivered to the robot by the message broker, rather than the robot DOES actually move to the specified location.
So how should I do for this kind of scenario?
Did you try using callbacks and promises? Usually an asynchronous function either provides some callback:
robot.move(x, y, function(err, res) { // do something })
or returns a promise:
robot.move(x, y).then(function(res) { // do something }).catch(function(err) { // error })
To be clear, there is no end to end delivery notification in MQTT, the callback is only that the message has been delivered to the broker, not onward to the robot. The only way to know it's been acted on by the robot is to have it publish a separate message to confirm it has completed an action

Settings alarms while app is closed

How can I set local notifications with out forcing user to open app.
I need my app set a local notification for sunrise and sunset, but I don't want to ask people open app.
I know I can have up to 64 notifications via scheduleLocalNotification, but I need to set it for a year so I should be able to run app in background and set alarms for future sunrises and sunsets in background.
The simple answer is you can't. Your app can't run whenever it wants in the background; it can't schedule a timer to wake itself up to post more notifications when they are due.
The only way you could come close to something like this is by having a server which send a background push notification to your app as a wake-up call when a new batch of 64 notifications are coming close to needed to be posted.
However this would be relying on the fact the user doesn't terminate your app. If the user does then you'd have to send a non-background push notification to the user and hope they click on it to launch your app.
Android Awareness API has recently announced new features that provide a simple solution for your use-case (that avoids you having to explicitly manage location request or computing sunrise times). The way to achieve what you're trying to do is to create and register a TimeFence specified relative to sunrise/sunset.
For example:
// Create TimeFence
AwarenessFence sunriseFence =
TimeFence.aroundTimeInstant(TimeFence.TIME_INSTANT_SUNRISE,
0, 5 * ONE_MINUTE_MILLIS);
// Register fence with Awareness.
Awareness.FenceApi.updateFences(
mGoogleApiClient,
new FenceUpdateRequest.Builder()
.addFence("fenceKey", sunriseFence, myPendingIntent)
.build())
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Fence was successfully registered.");
} else {
Log.e(TAG, "Fence could not be registered: " + status);
}
}
});
You will get callbacks when the fence evaluates to TRUE at sunrise, and when it evaluates back to FALSE at 5-min after sunrise.
Please check Fence API code snippets docs for how to add your custom app logic.

Stream function calls are async in Google Dart?

Why dart calls my function "aFunction" after Step2? If I execute this code this text below in console:
Step2
Step1
My code:
void main()
{
...
stream.listen(aFunction);
print("Step2");
...
}
void aFunction()
{
print("Step1");
}
Thanks for help.
One of the few promises that a Dart Stream makes is that it generates no events in response to a listen call.
The events may come at a later time, but the code calling 'listen' is allowed to continue, and complete, before the first event is fired.
We originally allowed streams to fire immediately on a listen, but when we tried to program with that, it was completely impossible to control in practice.
The same is true for listening on a future, for example with 'then'. The callback will never come immediately.
Events should generally act as if they were fired by the top-level event loop, so the event handler doesn't have to worry if other code is running - other code that might not be reentrant.
That is not always the case in practice. One event handler may trigger other events through a synchronous stream controller, effectively turning one event into anoter. That requires the event handler to know what it is doing. Synchronous controllers are intended for internal use inside, e.g., a stream transformer, and using a synchronous stream controller isn't recommended in general.
So, no, you can't have the listen call immediately trigger the callback.
You can listen to a stream synchronously if you created a StreamController with the sync option enabled. Here is an example to get what you describe:
var controller = new StreamController<String>(sync: true);
var stream = controller.stream.asBroadcastStream();
stream.listen((text) => print(text));
controller.add("Step1");
print("Step2");

Resources