Start a service from a referenced library in Android - 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.

Related

Android Service donot get Bound

Hi I am new to android and exploring the services part.I could not bind the service using bind method.I could not figure out whether it is problem with bind method or on service connected.Someone please help me with it.Thanks in advance
Activity code:
public class MainActivity extends AppCompatActivity {
MyService pavan ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent i = new Intent(this,MyService.class);
this.startService(i);
System.err.println("before binding**************************");
this.bindService(i, con, Context.BIND_AUTO_CREATE);
this.unbindService(con);this.stopService(i);
}
public ServiceConnection con = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
pavan = ((MyService.localbinder)service).getservice();
System.err.println("here service gets binded");
Toast.makeText(getBaseContext(),"Service connected",Toast.LENGTH_LONG);
}
#Override
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(getBaseContext(),"oops this is moment of Service disconnected",Toast.LENGTH_LONG);
}
};
}
Service code:
public class MyService extends Service {
public MyService() {
}
public class localbinder extends Binder{
public MyService getservice(){
return MyService.this;
}
}
IBinder ibinder = new localbinder();;
#Override
public IBinder onBind(Intent intent) {
return ibinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
}
manifest code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.coolguy.pract">
<uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<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"></service>
</application>
</manifest>
Finally I got the problem in my code.Context.BIND_AUTO_CREATE automatically invokes startService().So here when I invoked bind method since service is already running it goes to on onStartCommand.So just do not use startservice with Context.BIND_AUTO_CREATE flag.

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>

android aidl, cannot bind to service?

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

Binding to service always returns false

I am trying to bind to a service, but the bind service method always returns false. I believe the problem is in my connection. When I import the location of the LocalBinder class (in the service) I dont get any compile errors but the bindService call is still false.
Service information:
//binder for client
private final IBinder mBinder = new LocalBinder();
//client class binder
public class LocalBinder extends Binder {
ServiceA getService() {
// Return this instance of LocalService so clients can call public methods
return ServiceA.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
//called when service is created
public void onCreate(){
super.onCreate();
Toast.makeText(this,"ServiceA is started",Toast.LENGTH_SHORT).show();
}
Connection:
private ServiceConnection connect2A = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder newBinder = (LocalBinder) service;
mainService = newBinder.getService();
bound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
}
};
Initial calls:
#Override
protected void onStart(){
super.onStart();
Intent intent = new Intent(this, ServiceA.class);
startService(intent);
boolean check = bindService(intent,connect2A,0);
Toast.makeText(this, "Return from check is: " + check, Toast.LENGTH_LONG).show();
//program does get to this point, but binding fails
}
the AndroidManifest.XML file:
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".ServiceTest2Activity"
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:enabled="true" android:name=".serviceA" />
</application>
Some ideas:
-What class is the onStart() method in? I bind to my services in onCreate().
-Do you perhaps need to pass Context.BIND_AUTO_CREATE to the bindService call? e.g.
boolean check = bindService(intent, connect2A, Context.BIND_AUTO_CREATE);
-As the other commenter suggests, you should post the relevant snippets from your AndroidManifest.xml.
-You should put some trace/toast in the onServiceConnected method so you know if it is getting called.

Categories

Resources