android aidl, cannot bind to service? - android

Are there anyone knows why?
Activity
private IExternalDeviceScannerService myService = null;
private ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
myService = IExternalDeviceScannerService.Stub.asInterface(arg1);
}
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
};
......
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(this, ExternalDeviceScannerService.class);
bindService(intent, serviceConnection,
Context.BIND_AUTO_CREATE);
....
Service
class ScannerServiceAIDL extends IExternalDeviceScannerService.Stub {
.......
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return new ScannerServiceAIDL();
}
My activity is never connected to the service, even I waited few seconds!

I tested your code and executed the code without any problem. I think you made any mistake anywhere in your project. My successfully executed code is below.
IExternalDeviceScannerService.aidl
package com.example.aidltest;
interface IExternalDeviceScannerService
{
int getIntValue();
}
Manifest.xml
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
>
<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=".ExternalDeviceScannerService"></service>
</application>
Activity
private IExternalDeviceScannerService myService = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, ExternalDeviceScannerService.class);
// Bind service here
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
protected void onDestroy() {
super.onDestroy();
unbindService(mConnection);
myService = null;
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
myService = IExternalDeviceScannerService.Stub.asInterface(service);
if (myService != null){
try {
Log.i("Value from AIDL", myService.getIntValue() + "");
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void onServiceDisconnected(ComponentName className) {
myService = null;
}
};
Service
public class ExternalDeviceScannerService extends Service {
private static final String LOG_TAG = "Service";
#Override
public void onCreate() {
super.onCreate();
Log.i(LOG_TAG, "Service Started.");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "Service Stopped.");
}
final class ScannerServiceAIDL extends IExternalDeviceScannerService.Stub {
public int getIntValue() throws RemoteException {
return 20;
}
}
#Override
public IBinder onBind(Intent intent) {
Log.i(LOG_TAG, "Service Bound.");
return new ScannerServiceAIDL();
}
}
Have fun with AIDL!!! Thanks

Related

remote service call PeripheralManager.getInstance

run time exception:
System.err:java.lang.RuntimeException: Stub!
at com.google.android.things.pio.PeripheralManager.getInstance(PeripheralManager.java:21)
at com.afollestad.remotedemo.RemoteService$1.testPeripheralManager(RemoteService.java:33)
at com.afollestad.remotedemo.IRemoteAIDL$Stub.onTransact(IRemoteAIDL.java:56)
at android.os.Binder.execTransact(Binder.java:697)
Remote service's Manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.afollestad.remotedemo">
<uses-permission android:name="com.google.android.things.permission.USE_PERIPHERAL_IO" />
<application>
<service
android:name=".RemoteService"
android:process=":remote">
<intent-filter>
<action android:name="service.remote" />
</intent-filter>
</service>
</application>
MainActivity:
public class MainActivity extends Activity {
private IRemoteAIDL mService;
private TextView result;
private Button connectRemote;
private Button disconnectRemote;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
Log.d("aidl", "onServiceConnected" + service + " className " + className);
mService = IRemoteAIDL.Stub.asInterface(service);
try {
mService.testPeripheralManager();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void onServiceDisconnected(ComponentName className) {
Log.d("aidl", "onServiceDisconnected");
mService = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
connectRemote = (Button) findViewById(R.id.connect_remote);
disconnectRemote = (Button) findViewById(R.id.disconnect_remote);
connectRemote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("aidl", "onClick new thread");
Intent intent = new Intent();
intent.setAction("service.remote");
intent.setPackage("com.afollestad.remotedemo");
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
});
disconnectRemote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("aidl", "onClick");
unbindService(mConnection);
}
});
}}
remote service:
public class RemoteService extends Service {
private I2cDevice mI2cDevice = null;
private static final String I2C_DEVICE_NAME = "I2C1";
private static final int I2C_ADDRESS = 0x5c;
public Context mContext;
private boolean flag;
#Override
public void onCreate() {
super.onCreate();
}
private final IRemoteAIDL.Stub remoteBinder = new IRemoteAIDL.Stub() {
#Override
public void testPeripheralManager(){
Log.d("aidl", "RemoteService PeripheralManager");
try {
PeripheralManager manager = PeripheralManager.getInstance();
Log.d("aidl", "PeripheralManager2");
mI2cDevice = manager.openI2cDevice(I2C_DEVICE_NAME, I2C_ADDRESS);
if (mI2cDevice != null) Log.i("aidl", "I2C device open successful!");
}catch(RuntimeException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
#Override
public IBinder onBind(Intent intent) {
Log.d("aidl", "onBind");
mContext = this;
return remoteBinder;
}
#Override
public boolean onUnbind(Intent intent) {
flag = true;
return super.onUnbind(intent);
}
I bulid remote service in android things module, call PeripheralManager.getInstance() in remote service.
If any solve this problem, Please help me.
You should have a uses-library as part of the Manifest declaration, that would prevent you from installing an apk that requires Android Things in a device that does not have it, which looks like is what is happening here.

Communication Between Two Services using BroadcastReceiver

I m new on android
I want to start two services and one service sendbroadcast another will catch this broadcast but it is not working even if I register another service in this broadcasting
here is my code am I doing something wrong ?
Thanks advice.
public class MainActivity extends Activity {
Intent i;
Intent i2;
static final String LOG_TAG = "ServiceActivity";
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(LOG_TAG, "onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//Start service
i = new Intent(this, com.example.user.sensorservicetest.SimpleService.class);
i2= new Intent(this,com.example.user.sensorservicetest.AnotherService.class);
Log.d(LOG_TAG, "onCreate/startService");
}
#Override
public void onResume() {
super.onResume();
Log.d(LOG_TAG, "onResume/registering receiver");
//Register BroadcastReceiver to receive accelerometer data from service
startService(i);
startService(i2);
}
}
#Override
public void onPause() {
super.onPause();
Log.d(LOG_TAG, "onPause/unregistering receiver");
stopService(i);
stopService(i2);
}
#Override
protected void onStop() {
super.onStop();
Log.d(LOG_TAG, "onStop");
stopService(i);
stopService(i2);
}
}
SimpleService
public class SimpleService extends Service implements SensorEventListener {
private String reading;
private SensorManager mgr;
private List<Sensor> sensorList;
static final String LOG_TAG = "SimpleService";
Intent intent = new Intent("com.practice.SimpleService.MY_ACTION");
final static String MY_ACTION = "com.practice.SimpleService.MY_ACTION";
#Override
//public void onStartCommand() {
public void onCreate() {
Log.d(LOG_TAG, "onStartCommand");
mgr = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorList = mgr.getSensorList(Sensor.TYPE_ACCELEROMETER);
for (Sensor sensor : sensorList) {
mgr.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent,flags,startId);
}
#Override
public void onDestroy() {
Log.d(LOG_TAG, "onDestroy");
mgr.unregisterListener(this);
super.onDestroy();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
Log.d(LOG_TAG, "onSensorChanged");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < event.values.length; i++) {
builder.append(" [");
builder.append(i);
builder.append("] = ");
builder.append(event.values[i]);
builder.append("\n");
}
reading = builder.toString();
//Send back reading to Activity
intent.putExtra("measurement", reading);
sendBroadcast(intent);
}
}
AnotherService
public class AnotherService extends Service {
static final String TAG = "AnotherService";
private AnotherServiceReceiver anotherServiceReceiver = new AnotherServiceReceiver();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG,"onStartCommand");
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.practice.SimpleService.MY_ACTION");
registerReceiver(anotherServiceReceiver, intentFilter);
return super.onStartCommand(intent,flags,startId);
}
#Override
public void onDestroy() {
if (anotherServiceReceiver != null)
unregisterReceiver(anotherServiceReceiver);
super.onDestroy();
}
public static class AnotherServiceReceiver extends BroadcastReceiver {
static final String receiverTag = "AnotherServiceReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(receiverTag, "onReceive");
String measurement = intent.getStringExtra("measurement");
Log.d(receiverTag, "measurement - 2 : " + measurement);
}
}
}
Manifest
<service android:name=".SimpleService" ></service>
<service android:name=".AnotherService"></service>
<receiver android:name=".AnotherService$AnotherServiceReceiver" android:enabled="true">
<intent-filter>
<action android:name="here is problem I think"
</intent-filter>
</receiver>
According #Evgeniy Mishustin answer (thanks to him)
Solution is adding service in manifest xml file now working each service communication
<service android:name=".SimpleService" ></service>
<service android:name=".AnotherService"></service>
<receiver android:name=".AnotherService$AnotherServiceReceiver" android:enabled="true">
<intent-filter>
<action android:name="com.practice.SimpleService.MY_ACTION"></action>
</intent-filter>
</receiver>
</application>

How to find time of last reboot android?

I am attempting to find time of the last android reboot using service and broadcastreceiver. My "Broadcast" class should record the time immediately after the restart. In the "OnCreate" method a calculated time, but it does not work.
What am I doing wrong?
My "Server" class:
public class Server extends Service{
IBinder mBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
public Server getServerInstance() {
return Server.this;
}
} }
My "Client" class:
public class Client extends Activity {
boolean mBounded;
Server mServer;
TextView text;
Button button;
Broadcast bc = new Broadcast();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
Intent mIntent = new Intent(this, Server.class);
bindService(mIntent, mConnection, BIND_AUTO_CREATE);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
text.setText(String.valueOf(System.currentTimeMillis() - bc.t));
}
});
}
#Override
protected void onStart() {
super.onStart();
Intent mIntent = new Intent(this, Server.class);
bindService(mIntent, mConnection, BIND_AUTO_CREATE);
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(Client.this, "Service is disconnected", Toast.LENGTH_LONG).show();
mBounded = false;
mServer = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(Client.this, "Service is connected", Toast.LENGTH_LONG).show();
mBounded = true;
LocalBinder mLocalBinder = (LocalBinder)service;
mServer = mLocalBinder.getServerInstance();
}
};
#Override
protected void onStop() {
super.onStop();
if(mBounded) {
unbindService(mConnection);
mBounded = false;
}
}}
"Broadcast" class:
public class Broadcast extends BroadcastReceiver {
public long t;
#Override
public void onReceive(Context context, Intent intent) {
t = System.currentTimeMillis();
Intent serviceLauncher = new Intent(context, Server.class);
context.startService(serviceLauncher);
}}
Manifest:
<receiver android:name="com.example.serv.Broadcast" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:enabled="true" android:name=".Server"/>
What am I doing wrong?
Probably, not reading the docs enough?
There is a readily available API, SystemClock.uptimeMillis() which
Returns milliseconds since boot, not counting time spent in deep sleep.
You may also use SystemClock.elapsedRealtime() which
Returns milliseconds since boot, including time spent in sleep.

AIDL, bind and unbind IExtendedNetworkService Service

I use AIDL interface IExtendedNetworkService to get USSD code. But application only work after reboot device. I tried bindservice after install app but it didn't work. So my problem is how way to bind service without reboot device . This is my code:
interface:
package com.android.internal.telephony;
interface IExtendedNetworkService {
void setMmiString(String number);
CharSequence getMmiRunningText();
CharSequence getUserMessage(CharSequence text);
void clearMmiString();
}
Service
public class CDUSSDService extends Service {
private String TAG = "THANG-NGUYEN";
private boolean mActive = false;
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_INSERT)) {
// activity wishes to listen to USSD returns, so activate this
mActive = true;
Log.d(TAG, "activate ussd listener");
} else if (intent.getAction().equals(Intent.ACTION_DELETE)) {
mActive = false;
Log.d(TAG, "deactivate ussd listener");
}
}
};
private final IExtendedNetworkService.Stub mBinder = new IExtendedNetworkService.Stub() {
public void clearMmiString() throws RemoteException {
Log.d(TAG, "called clear");
}
public void setMmiString(String number) throws RemoteException {
Log.d(TAG, "setMmiString:" + number);
}
public CharSequence getMmiRunningText() throws RemoteException {
if (mActive == true) {
return null;
}
return "USSD Running";
}
public CharSequence getUserMessage(CharSequence text)
throws RemoteException {
Log.d(TAG, "get user message " + text);
if (mActive == false) {
// listener is still inactive, so return whatever we got
Log.d(TAG, "inactive " + text);
return text;
}
// listener is active, so broadcast data and suppress it from
// default behavior
// build data to send with intent for activity, format URI as per
// RFC 2396
Uri ussdDataUri = new Uri.Builder()
.scheme(getBaseContext().getString(R.string.uri_scheme))
.authority(
getBaseContext().getString(R.string.uri_authority))
.path(getBaseContext().getString(R.string.uri_path))
.appendQueryParameter(
getBaseContext().getString(R.string.uri_param_name),
text.toString()).build();
sendBroadcast(new Intent(Intent.ACTION_GET_CONTENT, ussdDataUri));
mActive = false;
return null;
}
};
public void onCreate() {
Log.i(TAG, "called onCreate");
};
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "called onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "called onbind");
// the insert/delete intents will be fired by activity to
// activate/deactivate listener since service cannot be stopped
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_INSERT);
filter.addAction(Intent.ACTION_DELETE);
filter.addDataScheme(getBaseContext().getString(R.string.uri_scheme));
filter.addDataAuthority(
getBaseContext().getString(R.string.uri_authority), null);
filter.addDataPath(getBaseContext().getString(R.string.uri_path),
PatternMatcher.PATTERN_LITERAL);
registerReceiver(receiver, filter);
return mBinder;
}
}
MainActivity:
public class MainActivity extends Activity {
private Button btnCheckUSSD;
private Context mContext;
private IExtendedNetworkService mService;
private EditText inputUSSD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_main);
btnCheckUSSD = (Button) findViewById(R.id.btn_check);
inputUSSD = (EditText) findViewById(R.id.input_ussd);
btnCheckUSSD.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!inputUSSD.getText().toString().isEmpty()) {
Intent service = new Intent(
"com.android.ussd.IExtendedNetworkService");
bindService(service, mConnecton, Context.BIND_AUTO_CREATE);
startActivity(new Intent("android.intent.action.CALL", Uri
.parse("tel:" + inputUSSD.getText().toString()
+ Uri.encode("#"))));
}
}
});
}
ServiceConnection mConnecton = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
mService = IExtendedNetworkService.Stub
.asInterface((IBinder) iBinder);
}
};
protected void onDestroy() {
super.onDestroy();
Log.d("THANG-NGUYEN", "onDestroy");
unbindService(mConnecton);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.example.checkussdcode"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="info.example.checkussdcode.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="info.example.checkussdcode.service.UssdCodeService"
android:process=":remote" >
<intent-filter>
<action android:name="com.android.ussd.IExtendedNetworkService" >
</action>
</intent-filter>
</service>
<receiver android:name="info.example.checkussdcode.RebootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>

Start a service from a referenced library in Android

I have an Android project that starts a Service. Then i turned that into an Android library and added it to another Android Project.
Now i am trying to automatically start that service from my Main Android project but i am lost.
This is my code from manifest(i have added all my classed from library):
<service
android:name="com.test.mqttclientserver.MQTTService"
android:enabled="true"
android:exported="false"
android:label="Service" >
<intent-filter>
<action android:name="com.test.mqttclientserver.MQTTService" />
</intent-filter>
</service>
<activity
android:name="com.test.mqttclientserver.MQTTClient"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.test.mqttclientserver.MQTTNotifier"
android:label="#string/app_name" >
</activity>
In an Activity of the main project:
private boolean mBounded;
private MQTTService mService;
private MQTTConnectionStatus connectionStatus = MQTTConnectionStatus.INITIAL; ..... public IBinder onBind(Intent intent) {
return mBinder;
}
public MQTTConnectionStatus getConnectionStatus() {
return connectionStatus;
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(SplashScreen.this, "Service is disconnected", 1000)
.show();
mBounded = false;
mService = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(SplashScreen.this, "Service is connected", 1000).show();
mBounded = true;
LocalBinder mLocalBinder = (LocalBinder) service;
mService = (MQTTService) mLocalBinder.getService();
}
};
public void onStart(final Intent intent, final int startId) {
System.out.println("onStart loading...");
Intent mIntent = new Intent(this, MQTTService.class);
bindService(mIntent, mConnection, BIND_AUTO_CREATE);
System.out.println("onStart ending...");
}
protected void onStop() {
super.onStop();
if (mBounded) {
unbindService(mConnection);
mBounded = false;
}
}
Isn't this enough? Just a hint would suffice. Thank you for your time.

Categories

Resources