Bluetooth Connectivity of Android Device with Arduino - bluetooth

I am working Android base Attendance door lock application. Currently the application works when card is tap, Attendance is marked. Now i have join it with arduino based door lock. Arduino is connected through Bluetooth with Android Application. when android device goes to sleep mode connection of Bluetooth is disconnected. Is there any way that when device goes to sleep mode connection will not be disconnected.

You can set it programmatically like bottom.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
Or you can set it from AndroidManifest.xml.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true">
...
</RelativeLayout>
More info: Android Developer

Related

bluetoothAdapter.startDiscovery() returns False always

This is the code I'm using to try to start Bluetooth discovery. However, I always end up with the "Unable to start discovery" message (see below the code).
Device: Pixel 3 running Android 10 API 29
from grade file:
minSdkVersion 16
targetSdkVersion 30
from manifest file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.bluetooth" />
from java:
if (bluetoothAdapter==null)
Log.i("BT", "First must enable BT");
else
{
if(bluetoothAdapter.getState()==bluetoothAdapter.STATE_ON)
{
Log.i("BT", "BT State on");
if (bluetoothAdapter.isDiscovering()) {
Log.i("BT", "was already discovering");
bluetoothAdapter.cancelDiscovery();
}
if(bluetoothAdapter.startDiscovery())
Log.i("BT", "starting discovery");
else
Log.i("BT", "Unable to start discovery");
}
else
Log.i("BT", "BT State NOT on");
}
Thanks!
So despite all permissions from the manifest, the app was declined Location servces by the system and my app wasn't even listed when I was going to the Location settings in the phone menu. I had to go to the drop down menu and enable "Show system" and then a bunch of other apps with weird names appeared, among them my app. I enabled "alwasys allow" and now BT is discovering nearby devices.
How can I request this permission at runtime then so I make sure I have permission without having to go to the Settings Menu?

Android Things Rasperry PI GPS and Bluetooth Error

I am getting an error once I load my app in Android Things on Rasperry PI, it shows a message about "Bluetooth has stopped".
This happens just after registering the GPS Driver. it does not affect the functionality and it is only at the first time.
It has already some permissions in the xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.google.android.things.permission.MANAGE_GNSS_DRIVERS" />
<uses-permission android:name="com.google.android.things.permission.USE_PERIPHERAL_IO" />
Looks like it requires to switch the port to GPS or unregister Bluetooth first... By the way I am not using bluetooth feature in the app. any idea?
thanks
if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.e(TAG, "No permission");
return;
}
try {
// Register the GPS driver
mGpsDriver = new NmeaGpsDriver(context, "UART0", UART_BAUD, ACCURACY);
mGpsDriver.register();
This is a known limitation of the Raspberry Pi, as per the pinout documentation:
The Raspberry Pi has pins that are multiplexed between various board functions. Some board functions cannot be used simultaneously (for example, enabling Bluetooth and using the UART0 port for peripheral I/O).
So there may be a process running in the background which is still using Bluetooth and causing the driver to crash.

Launch FCM services on boot without the activity

I've followed the Firebase Quickstart Messaging Tutorial, and I've a problem.
I'd like to launch the two services (MyFirebaseMessagingService and MyFirebaseInstanceIDService) on the boot of the system.
For that, I've added the RECEIVE_BOOT_COMPLETED permission to my AndroidManifest.xml.
I've also added this to the Manifest :
<receiver android:name=".AutoStart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
In my AutoStart class, there is this :
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MyFirebaseInstanceIDService.class));
context.startService(new Intent(context, MyFirebaseMessagingService.class));
}
The two services are nearly the same as on the links I've provided above. And my MainActivity only contains a few Views.
But it doesn't work : as soon as the services are launched, the services are automatically killed and I get a message like this in the logcat :
I/ActivityManager﹕ Killing 3100:com.company.E/u0a85 (adj 15): empty #17
I've searched for solutions about this "killing problem", and I think I've found something interesting here (about WakefulBroadcastReceiver).
If this part of the solution, I met another problem with this answer...
The onHandleIntent() override method he talks about is part of IntentService where my two services are Service.
If this is not part of the solution, I don't know how to prevent my app to be killed...

Why isn't the constructor of my WPF page control being called?

I am trying to create a Windows Store app for Desktop/tablet and Phone with a Universal App in Visual Studio 2013 Express. I am having some difficulty understanding what is happening in WPF, as my prior Windows 8 development experience has been with HTML/JS apps.
I ask VS to create a New Project->Visual C#->Store Apps->Universal Apps->Blank App. I open MainPage.xaml.cs and put a breakpoint on the first line in the constructor function, which happens to be this.InitializeComponent(). I hit F5, the app compiles and I am switched to the familiar full-screen Modern app view, but none of my breakpoints are ever hit.
I add a TextBlock to MainPage.xaml just so that there's something in there, but still no breakpoints are hit. What am I missing? Below is (some) the code the is generated by Visual Studio. I am probably missing something very fundamental about how WPF apps work and are structured, but all my google-fu has come to naught.
MainPage.xaml:
<Page
x:Class="SoloCoach.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SoloCoach"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
</Grid>
</Page>
MainPage.xaml.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace SoloCoach
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
}
}
When you create a Universal App it creates both a Windows 8.1 and a Windows Phone 8.1 app. The code you're showing is the default page constructor for the Phone version so you're probably in the wrong project which is not the Windows Modern App that you're running.

Cannot inject dependencies to Azure WorkerRole object using Spring.NET

I have moderate experience in developing web applications using spring.net 4.0 , nhibernate 3.0 for ASP.net based web applications. Recently I ran into a situation where I needed to use spring.net to inject my service dependencies which belong to the WorkerRole class. I created the app.config file as I normally did with the web.config files on for spring. Here it is for clarity. (I have excluded the root nodes)
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web" requirePermission="false" />
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" requirePermission="false" />
<section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<spring>
<context>
<!-- Application services and data access that has been previously developed and tested-->
<resource uri="assembly://DataAccess/data-access-config.xml" />
<resource uri="assembly://Services/service-config.xml" />
<resource uri="AOP.xml" />
<resource uri="DI.xml"/>
</context>
<parsers>
<parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data" />
<parser type="Spring.Transaction.Config.TxNamespaceParser, Spring.Data" />
<parser type="Spring.Aop.Config.AopNamespaceParser, Spring.Aop" />
</parsers>
</spring>
Similarly Here's the AOP.xml
<object id="FilterServiceProxy" type="Spring.Aop.Framework.ProxyFactoryObject, Spring.Aop">
<property name="proxyInterfaces" value="Domain.IFilterService"/>
<property name="target" ref="FilterService"/>
<property name="interceptorNames">
<list>
<value>UnhandledExceptionThrowsAdvice</value>
<value>PerformanceLoggingAroundAdvice</value>
</list>
</property>
</object>
</objects>
and the DI.xml
<object type="FilterMt.WorkerRole, FilterMt" >
<property name="FilterMtService1" ref="FilterServiceProxy"/>
</object>
However, I was unable to inject any dependencies into the worker role. Can someone please let me know what I am doing wrong here ? Is there a different way to configure Spring.net DI for windows azure applications ?
I don't get any configuration errors but I see that the dependencies have not been injected because the property object to which I've tried injection, remains null.
Based on my experience, you cannot inject anything into your WorkerRole class (the class that implements RoleEntryPoint). What I do, so far with Unity (I also built my own helper for Unity to help me inject Azure settings), is that I have my own infrastructure that runs and is built by Unity, but I create it in the code for the worker role.
For example, I initialize the dependency container in my OnStart() method of RoleEntry point, where I resolve anything I need. Then in my Run() method I call a method on my resolved dependency.
Here is a quick, stripped off version of my RoleEntryPoint's implementation:
public class WorkerRole : RoleEntryPoint
{
private UnityServiceHost _serviceHost;
private UnityContainer _container;
public override void Run()
{
// This is a sample worker implementation. Replace with your logic.
Trace.WriteLine("FIB.Worker entry point called", "Information");
using (this._container = new UnityContainer())
{
this._container.LoadConfiguration();
IWorker someWorker = this._container.Resolve<IWorker>();
someWorker.Start();
IWorker otherWorker = this._container.Resolve<IWorker>("otherWorker");
otherWorker.Start();
while (true)
{
// sleep 30 minutes. we don't really need to do anything here.
Thread.Sleep(1800000);
Trace.WriteLine("Working", "Information");
}
}
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
this.CreateServiceHost();
return base.OnStart();
}
public override void OnStop()
{
this._serviceHost.Close(TimeSpan.FromSeconds(30));
base.OnStop();
}
private void CreateServiceHost()
{
this._serviceHost = new UnityServiceHost(typeof(MyService));
var binding = new NetTcpBinding(SecurityMode.None);
RoleInstanceEndpoint externalEndPoint =
RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["ServiceEndpoint"];
string endpoint = String.Format(
"net.tcp://{0}/MyService", externalEndPoint.IPEndpoint);
this._serviceHost.AddServiceEndpoint(typeof(IMyService), binding, endpoint);
this._serviceHost.Open();
}
As you can see, my own logic is IWorker interface and I can have as many implementations as I want, and I instiate them in my Run() method. What I do more is to have a WCF Service, again entirely configured via DI with Unity. Here is my IWorker interface:
public interface IWorker : IDisposable
{
void Start();
void Stop();
void DoWork();
}
And that's it. I don't have any "hard" dependencies in my WorkerRole, just the Unity Container. And I have very complex DIs in my two workers, everything works pretty well.
The reason why you can't interfere directly with your WorkerRole.cs class, is that it is being instantiated by the Windows Azure infrastructure, and not by your own infrastructure. You have to accept that, and built your infrastructure within the WorkerRole appropriate methods. And do not forget that you must never quit/break/return/exit the Run() method. Doing so will flag Windows Azure infrastructure that there is something wrong with your code and will trigger role recycling.
Hope this helps.
I know this is an old question, but I'm going through the same learning curve and would like to share my findings for someone who struggles to understand the mechanics.
The reason you can't access DI in your worker role class is because this is run in a separate process in the OS, outside of IIS. Think of your WebRole class as being run in a Windows Service.
I've made a little experiment with my MVC web-site and WebRole class:
public class WebRole : RoleEntryPoint
{
public override void Run()
{
while (true)
{
Thread.Sleep(10000);
WriteToLogFile("Web Role Run: run, Forest, RUN!");
}
}
private static void WriteToLogFile(string text)
{
var file = new System.IO.StreamWriter("D:\\tmp\\webRole.txt", true); // might want to change the filename
var message = string.Format("{0} | {1}", DateTime.UtcNow, text);
file.WriteLine(message);
file.Close();
}
}
This would write to a file a new string every 10 seconds (or so). Now start your Azure site in debugging mode, make sure the site deployed to Azure emulator and the debugger in VS has started. Check that the site is running and check that WebRole is writing to the file in question.
Now stop the IIS Express (or IIS if you are running it in full blown installation) without stopping the VS debugger. All operations in your web-site are stopped now. But if you check your temp file, the process is still running and you still get new lines added every 10 seconds. Until you stop the debugger.
So whatever you have loaded in memory of web-application is inside of the IIS and not available inside of Worker Role. And you need to re-configure your DI and other services from the scratch.
Hope this helps someone to better understand the basics.

Resources