Android AIDL Service not executing - java

I use Android Automotive 11 environment, The below code actually also does not run under Regular Android 11 environemnt.
I Use the emulator that I've built from source Android 11 r35.
When I try to open the AIDL service I get the following error:
PermissionMonitor: NameNotFoundException
BroadcastQueue: Background execution not allowed
Here is the code:
public class MySimpService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return new SimpServiceImp();
}
}
SimpServiceImp Class:
public class SimpServiceImp extends ISimp.Stub {
#Override
public int add(int a, int b) throws RemoteException {
return a+b;
}
#Override
public int sub(int a, int b) throws RemoteException {
return a-b;
}
}
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AIDLService" >
<service android:name=".MySimpService">
<intent-filter>
<action android:name="com.example.aidlservice.MySimpService"/>
</intent-filter>
</service>
</application>

There were a lot of basic Android issues which made this not work.
Part of it is Service had to have Notification to keep alive.
https://github.com/NewstHet/AndroidAidlClient
https://github.com/NewstHet/AndroidAIDLService
Github links contains working AIDL service using Android 11 API 30.

Related

Service gets killed when app closes

I have a main service which should always be running in the background in my Android application for handling a bluetooth device connection and feeding data to it.
According to these questions, it is a normal behavior if my service live in my app process to get killed when app closes,
Android Background Service is restarting when application is killed
Service restarted on Application Close - START_STICKY
keeping background service alive after user exit app
But I even tried running my service in a separate process using this tag android:process=":service" inside my manifest but it also get killed and restarted when my app get killed!
More info:
I start my service in my application onCreate method, and for binding to my service in my activity I use BIND_AUTO_CREATE, which generally I am not sure is it correct or not.
update:
I also have another service which bind inside my current service, I am not sure if it might be source of issue!
more update:
I am using dagger for DI, is it possible by mistake I am using application context for creating some objects inside my service!! could this be the cause of this issue?
some more update
I separate dagger components for my service and now application and service got no common objects, but problem still remains.
update with a sample code which got the same issue
Here is the Application class:
class MyApplication:Application() {
override fun onCreate() {
super.onCreate()
startService(Intent(this, MyService::class.java))
}
}
Here is the Service class:
class MyService : Service() {
private val mBinder = MyBinder()
inner class MyBinder : Binder() {
internal val service: MyService
get() = this#MyService
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.i(TAG, "onStartCommand")
return START_STICKY
}
override fun onCreate() {
super.onCreate()
Log.i(TAG, "onCreate")
}
override fun onBind(intent: Intent): IBinder? {
Log.i(TAG, "onBind")
return mBinder
}
override fun onUnbind(intent: Intent): Boolean {
Log.i(TAG, "onUnbind")
return super.onUnbind(intent)
}
override fun onDestroy() {
Log.i(TAG, "onDestroy")
super.onDestroy()
}
companion object {
val TAG = "MyService"
}
}
This is the Activity:
class MainActivity : AppCompatActivity() {
lateinit var context: Context
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.i(TAG, "onCreate")
context = this
}
//connect to the service
val myServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
Log.i(TAG, "onServiceConnected")
val binder = service as? MyService.MyBinder
// ...
}
override fun onServiceDisconnected(name: ComponentName?) {
Log.i(TAG, "onServiceDisconnected")
}
}
override fun onResume() {
super.onResume()
Log.i(TAG, "onResume")
val intent = Intent(context, MyService::class.java)
bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);
}
override fun onPause() {
super.onPause()
Log.i(TAG, "onPause")
unbindService(myServiceConnection)
}
companion object {
val TAG = "MainActivity"
}
}
Last but not least, the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mirhoseini.stickyservice">
<application
android:name=".MyApplication"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
android:process=":service" />
</application>
</manifest>
It is a normal behavior for a service to stop when the application main thread stops.
Personally, I don't agree with using an internal service in a separate process for the regular development and functionality sharing between modules. A worker or IntentService is the more appropriate candidate most of the times.
To keep your service alive after user exits the app, try one of the scheduled threading mechanism that suits your needs, best :
1- TimerTask ( not really recommended !)
2- Executors.newScheduledThreadExecutor
3- AlarmManager
4- JobScheduler

How to load a dictionary on android app start and use it from different activities

I have a dictionary like below:
Map<String, String> fontDic = new HashMap<String, String>();
fontDic.put("1", "0x0627");
fontDic.put("2", "0x0628");
fontDic.put("3", "0x062A");
fontDic.put("4", "0x062B”);
I want to load this array once while starting the app. Further i want to use this dictionary from different activities without loading again like `String value = fontDic.get(fontNo);
So what is the best way or places to load this array list once and use from different places?
create application class and write this code in application class
public class MyApplictaion extends Application {
private static MyApplication myApplication = null;
public Map<String, String> fontDic;
#Override
public void onCreate() {
super.onCreate();
fontDic = new HashMap<String, String>();
fontDic.put("1", "0x0627");
fontDic.put("2", "0x0628");
fontDic.put("3", "0x062A");
fontDic.put("4", "0x062B");
}
public static MyApplication getInstance() {
if (myApplication == null) {
myApplication = new MyApplication();
}
return myApplication;
}
}
application class entry in manifest file
<application
android:name="com.example.app.MyApplication"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="#style/AppTheme">
to use in activity
Map<String, String> fontDic= MyApplication.getInstance().fontDic;

Service Intent not found Android plugin for Unity

I'm a bit new to developing for android, but I feel like I've scoured quite a few forums and tried everything I can find, to no avail.
At any rate, I'm trying to build an Android plugin for my Unity project, and essentially I'd like to start an Android service from Unity. It seems as though I have all my ducks in a row, but when it goes to start the service, I get the following error message on the Android Monitor LogCat:
Unable to start service Intent{ cmd=com.activetime.androidplugin/.services.StepsService } U=0; not found
My suspicion is that the "/" between "androidplugin" and ".services" isn't suppose to be there, which is why it can't find the service, but I can't for the life of me figure out why it's there. I've seen other similar issues out there but none of the solutions seem to work; perhaps there's some issue with merging manifests?
In any case, here's the Java class from Android Studio:
private static DBReader instance;
public DBReader(){
this.instance = this;
}
public static DBReader instance(){
if(instance == null){
instance = new DBReader();
}
return instance;
}
public void startStepsService(Activity unityActivity){
unityActivity.startService(new Intent(unityActivity, StepsService.class));
}
}
And then the C# in Unity:
void Start(){
#if UNITY_ANDROID
using(AndroidJavaClass activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
activityContext = activityClass.GetStatic<AndroidJavaObject>("currentActivity");
}
using(AndroidJavaClass pluginClass = new AndroidJavaClass("com.activetime.androidplugin.DBReader")) {
if(pluginClass != null) {
databaseplugin = pluginClass.CallStatic<AndroidJavaObject>("instance");
databaseplugin.Call("startStepsService", activityContext);
}
}
#endif
}
And finally my Android Studio XML manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.activetime.androidplugin">
<application android:allowBackup="true" android:label="#string/app_name"
android:supportsRtl="true">
<service
android:name="com.activetime.androidplugin.services.StepsService">
</service>
</application>

Getting java.lang.ClassCastException: android.os.BinderProxy every time i declare and run two services

I am encountering following binder.proxy exception every time i declare and run two services. One service runs in different Process(Private to app) and another service runs in same process as My Application is running in(Default App Process) with a Binder Implementation.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.service.check"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:name="com.service.check.MainApplication"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.service.check.SecondService"
android:exported="false"/>
<service
android:name="com.service.check.FirstService"
android:process=":newProcess" >
</service>
</application>
</manifest>
I am launching my first service in MainActivity on Button click as:
MainActivity.java
public class MainActivity extends ActionBarActivity implements OnClickListener {
private Button mLanchServiceBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLanchServiceBtn=(Button) findViewById(R.id.launch_btn);
mLanchServiceBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//Starting first service
Intent launch=new Intent(this,FirstService.class);
startService(launch);
}
}
And second service in MainApplication class as.
MainApplication.java
public class MainApplication extends Application {
private SecondService.LocalBinder mBinder;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
mBinder = (LocalBinder) service;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
#Override
public void onCreate() {
super.onCreate();
//starting second service
Intent launch=new Intent(this,SecondService.class);
startService(launch);
//Binding to it
bindService(launch, mConnection, BIND_AUTO_CREATE);
}
}
FirstService.java
public class FirstService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
SecondService.java
public class SecondService extends Service{
//Service Containing Local Binder
private LocalBinder mBinder=new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
class LocalBinder extends Binder{
public LocalBinder() {
}
}
}
StackTrace:
02-05 10:32:25.035: E/AndroidRuntime(1424): Process:
com.service.check:newProcess, PID: 1424 02-05 10:32:25.035:
E/AndroidRuntime(1424): java.lang.ClassCastException:
android.os.BinderProxy cannot be cast to
com.service.check.SecondService$LocalBinder 02-05 10:32:25.035:
E/AndroidRuntime(1424): at
com.service.check.MainApplication$1.onServiceConnected(MainApplication.java:23)
02-05 10:32:25.035: E/AndroidRuntime(1424): at
android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1101)
I have referred the following links to sort out the issue which says,
if my activity and service are in separate processes then we should not bind the way I have done.
Android service android.os.BinderProxy error
java.lang.ClassCastException: android.os.BinderProxy cannot be cast to LocalBinder
But in my case:
I am binding to SecondService from MainApplication and both are running in same Process(i.e Default Application Process). Still I am facing binderProxy exception in SecondService , And my FirstService runs in separate process which I am not even binding to.
Please help me out with this situation and, Suggest me a best possible way so that I can implement same scenario without any crash.
Ran into this issue (local service returning a BinderProxy), wanted to post what I'd found since I found this page while trying to debug. The short version as a run on sentence: starting a remote service creates a second instance of your Application class in a new process which then tries to bind to the local service that was started by the original Application instance as if it was a local service but since the service is running in the original process it's binding across processes and you get a BinderProxy instead of your expected Binder class.
There's a few things to keep in mind about Android services. Every service has an assigned process it will run in. If you don't assign a process in your Android Manifest it will run in the default process (the process where the Application, Activities, etc are run). Not giving a process name doesn't mean that it will run the service in the same process that you're binding to/starting the service from.
Let's say I have a MyApplication class which attempts to bind to two services on start up: one service running in the default process (we'll call this the LocalService), one running in a separate process (the RemoteService).
The user launches my app which creates a MyApplication instance in the default process. This instance then tries to bind to the LocalService. Android creates the LocalService in the default process and returns the LocalService's Binder class to the app (mBinder = (LocalBinder) service;). That's all good, we've successfully bound to the LocalService.
Next the app tries to bind to the RemoteService. Android creates a new process with the name you've supplied in the Android Manifest. However, before it can create the RemoteService it needs to create an Application for the service to run in. It creates a new MyApplication instance in the remote process and starts that up.
However, that new MyApplication instance running in a separate process tries to bind to the LocalService during start up. Because the LocalService is running in the default process this is a cross process binding but MyApplication expects this to be an in process binding. Android returns a BinderProxy, the second MyApplication instance tries to cast it to a LocalBinder and crashes. The fun part is that it crashes in a different process so your app and activity can actually continue running. You'll just never be able to bind to the remote service.
If you want to bind to a local service with an Application context and also use a remote service you'll need to handle the fact that Android will create another Application in the remote process when starting the remote service. I haven't bothered to try this (I just made my remote service a local service), but you could probably check the process name during the application's on create and not bind if it's not the default process.
Found an answer after doing some research and debugging,
If we create and bind any service to a MainApplication class(then service gets binded to whole ApplicationContext or BaseContext) and if same application contains other services which are binded to Activity specific Context(s),
//Declared in MainApplication
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
mBinder = (LocalBinder) service;
}
In OnServiceConnected() We will get binder object for both the Services( SecondService Started in MainApplication(registered with BaseContext will get local binderObject) class and FirstService started MainActivity(will get android.os.binderProxyObject hence causing ClassCastException).
So, to fix this issue one has to start all the application
services from any Activity Context rather than using any Global
Application Context. Also this issue is independent of the
Processes
Hence, I moved both SecondService and FirstService into MainActivity
Context which fixed the issue.
MainActivity.java
private Button mLanchServiceBtn;
private SecondService.LocalBinder mBinder;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
mBinder = (LocalBinder) service;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLanchServiceBtn=(Button) findViewById(R.id.launch_btn);
mLanchServiceBtn.setOnClickListener(this);
//starting second service in activity
Intent launch=new Intent(this,SecondService.class);
startService(launch);
//Binding to it
bindService(launch, mConnection, BIND_AUTO_CREATE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
//Starting FirstService also from MainActivity
Intent launch=new Intent(this,FirstService.class);
startService(launch);
}
}
You can't call directly any methods of your remote services (or cast) because they live in different process so you can't get a reference to it's instance. But Android has specific interfaces to handle this interprocess communications (IPC). The easiest way is using android.os.Messenger (another is AIDL, more complex).
On your Service, your implementation of Service#onBind() will be a little bit different:
override fun onBind(intent: Intent): IBinder? {
mMessenger = Messenger(YourServiceHandler())
return mMessenger.binder
}
And on your Activity implementation of ServiceConnection#onServiceConnected(serviceBinder: IBinder) you will not get a directly reference to your remote service instance, but instead create a Messenger that have a send(message: Message) interface so you can remotelly call the service functions:
override fun onServiceConnected(className: ComponentName, service: IBinder) {
mServiceMessenger = Messenger(service)
}
override fun onCreate(){
doStuff1Button.setOnClickListener{
val msg = Message.obtain(null, YourRemoteService.MESSAGE_DO_STUFF_1, 0, 0)
mServiceMessenger.send(msg)
}
doStuff1Button.setOnClickListener{
val msg = Message.obtain(null, YourRemoteService.MESSAGE_DO_STUFF_2, 0, 0)
mServiceMessenger.send(msg)
}
}
Note that in the message is going a argument do stuff 1 or 2. You will get this back on your service handler Handler#onHandleMessage(message: Message) with the attribute what:
override fun handleMessage(message: Message) {
when (message.what) {
MESSAGE_DO_STUFF_1 -> doStuff1()
MESSAGE_DO_STUFF_2 -> doStuff2()
}
}
Complete guide can be found in this official documentation
I tried above all solutions but none of those worked. If anyone was stuck same as myself try this based on #Coeffect answer. In my scenario service clients doesn't belong to my current application(process)
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
mBinder = LocalBinder.Stub.asInterface(service);
}

Android BroadcastReceiver: Unable to instantiate receiver - no empty constructor

I have a problem with a BroadcastReceiver. If I declare the action in the manifest in this way:
<receiver android:name="com.app.activity.observer.DataEntryObserver" >
<intent-filter>
<action android:name= "#string/action_db_updated" />
</intent-filter>
</receiver>
where in the strings.xml I have:
<string name="action_db_updated">com.app.DB_UPDATED</string>
everything works well. But if I change it to:
<receiver android:name="com.app.activity.observer.DataEntryObserver" >
<intent-filter>
<action android:name= "com.app.DB_UPDATED" />
</intent-filter>
</receiver>
I have this exception as the receiver is called:
java.lang.RuntimeException: Unable to instantiate receiver com.app.activity.observer.DataEntryObserver: java.lang.InstantiationException: can't instantiate class com.app.activity.observer.DataEntryObserver; no empty constructor
I would keep the working version but the Play store doesn't allow me to publish the app because it expects a string value and not a variable #string/..
my receiver is an outerclass and is defined as:
public class DataEntryObserver extends BroadcastReceiver{
private AppUsageLoader dLoader;
public DataEntryObserver(AppUsageLoader dLoader) {
this.dLoader = dLoader;
IntentFilter filter = new IntentFilter(
ReaLifeApplication.ACTION_DB_UPDATED);
dLoader.getContext().registerReceiver(this, filter);
}
#Override
public void onReceive(Context arg0, Intent arg1) {
// Tell the loader about the change.
dLoader.onContentChanged();
}
}
Make the class a static class, otherwise it's "seen" as part of the original containing class instance.
thus:
public static class DataEntryObserver extends BroadcastReceiver{
public DeviceAdminSampleReceiver() {
super();
}
...
https://stackoverflow.com/a/10305338/1285325
You need an empty constructor like this:
public class DataEntryObserver extends BroadcastReceiver{
private AppUsageLoader dLoader;
// Empty constructor
public DataEntryObserver() { }
public DataEntryObserver(AppUsageLoader dLoader) {
this.dLoader = dLoader;
IntentFilter filter = new IntentFilter(
ReaLifeApplication.ACTION_DB_UPDATED);
dLoader.getContext().registerReceiver(this, filter);
}
#Override
public void onReceive(Context arg0, Intent arg1) {
// Tell the loader about the change.
dLoader.onContentChanged();
}
}
Although I'm not sure if keeping the non-empty constructor will generate the same error. If it does, you will have to remove it.
need to empty constructor
public DataEntryObserver() {
this.dLoader = null;
}

Categories