How to stop JobService Scheduled to when app is removed from background? - java

Currently i am working with an application and my app has a feature that the user will be able to click on a Navigate button and my app will start the Google Map. Till now it's fine and i have done it. But the fact where i am stuck is that i want my app to perform some tasks. To achieve that i have used JobService and scheduled it to run after every 5 seconds even when the app is in background.
When the user presses the back button then inside onDestroy method i have cancelled the scheduler. But when the app is removed from the background by sliding or pressing the cross icon the JobService keeps running as the onDestroy method can be called or not by the os when it is removed from the background. How can i stop the scheduled job when the app is removed from the background?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="javarank.com.serviceinbackground">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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/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=".MyJobService" android:exported="true" android:permission="android.permission.BIND_JOB_SERVICE" />
</application>
</manifest>
MyJobService class
public class MyJobService extends JobService {
#Override
public boolean onStartJob(final JobParameters jobParameters) {
Toast.makeText(getApplicationContext(), "Doing job", Toast.LENGTH_SHORT).show();
jobFinished(jobParameters, true);
return false;
}
#Override
public boolean onStopJob(JobParameters jobParameters) {
return false;
}
}
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
private static final int JOB_ID = 1;
private JobInfo jobInfo;
private JobScheduler scheduler;
private Button navigateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ComponentName componentName = new ComponentName(this, MyJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, componentName);
builder.setPeriodic(5000);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
// if true this job exists even after a system reboot...
builder.setPersisted(false);
jobInfo = builder.build();
scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
scheduler.schedule(jobInfo);
navigateButton = (Button) findViewById(R.id.navigate_button);
navigateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StringBuffer url = new StringBuffer("https://www.google.com/maps/dir/?api=1");
url.append("&origin=23.755736,90.374627");
url.append("&destination=23.754047,90.371682");
url.append("&travelmode=driving");
Uri gmmIntentUri = Uri.parse(url.toString());
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
}
});
}
#Override
protected void onDestroy() {
Toast.makeText(getApplicationContext(), "Destroy called.", Toast.LENGTH_SHORT).show();
scheduler.cancel(JOB_ID);
super.onDestroy();
}
}

I think you need to override following onStop() method and put stopService() command to stop the JobService.
#Override
protected void onStop() {
// A service can be "started" and/or "bound". In this case, it's "started" by this Activity
// and "bound" to the JobScheduler (also called "Scheduled" by the JobScheduler). This call
// to stopService() won't prevent scheduled jobs to be processed. However, failing
// to call stopService() would keep it alive indefinitely.
stopService(new Intent(this, MyJobService.class));
super.onStop();
}

You can create a new service like
MyService.java
public class MyService extends Service {
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
//stop you jobservice from here
stopSelf();
}
}
and start it from MainActivity.java
startService(new Intent(MainActivity.this,MyService.class));

Android> 7 automatically saves battery power. You must turn on the application's battery saving stop feature.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent intent = new Intent();
String packageName = getPackageName();
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivity(intent);
}
}
add this to AndroidManifest.xml
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>

I faced this issue, but I found that after schedule job service, it can't be canceled (From view).
So I turned to stop it inside the job service by calling onStopJob(params)
and it worked.

Related

I created a service in Java but it doesn't run in the background

I am trying to create a simple service in java that will run in the background. I want to play a song on the phone even though the app is closed. I read some articles and watched tutorials but my service still stops when I close the app.
1) I changed my manifest
<service
android:name="com.example.myapplication.ServiceSound"
android:exported="true"
android:enabled="true">
</service>
2) I returned START_STICKY
This is manifest
<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/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="com.example.myapplication.ServiceSound"
android:exported="true"
android:enabled="true">
</service>
</application>
This is the service
public class ServiceSound extends Service {
MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
player.stop();
}
}
And this is how I start the service in MainActivity.java
startService(new Intent(getBaseContext(),ServiceSound.class));
I think you need Broadcast Receiver.
So now
1- Create broadcast receiver class and call your Service class.
public class MyBroadcaseReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context,ServiceSound.class));
Log.e(TAG, "onReceive: BroadCast is started");
}
}
2- Your Service class define this
public static String str_receiver = "Your_Package_Name.receiver";
on startCommand start your broadcast class
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.start();
return START_STICKY;
Intent intent1 = new Intent(this,MyBroadcaseReceiver.class);
sendBroadcast(intent1);
return START_STICKY;
}
Now in your MainActivity class create an object for broadcast
private BroadcastReceiver broadcastReceiver;
inside onCreate() define the object
broadcastReceiver = new MyBroadcaseReceiver();
Finaly call onResume() and onPause() inside the MainActivity.
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(MyService.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
Don't forget to call broadcast reciever in your Manifest file
<receiver android:name=".MyBroadcaseReceiver"></receiver>

Unable to get intent from service with LocalBroadcastManager [duplicate]

I have my main activity that start a service (Location service) and I want that service to broadcast the new location each time a new location is found.
Thanks to the log I know the service is working and I have new locations every seconds or so, but I never get the broadcast.
MainActivity.java
public class MainActivity extends Activity {
private static final String TAG = "mainActivity";
private CMBroadcastReceiver mMessageReceiver = new CMBroadcastReceiver();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
// Start Service
startService(new Intent(this, LocationService.class));
super.onCreate(savedInstanceState);
}
#Override
public void onResume()
{
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(CMBroadcastReceiver.RECEIVE_LOCATION_UPDATE));
super.onResume();
}
#Override
public void onPause()
{
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
}
CMBroadcastReceiver.java
public class CMBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "CMBroadcastReceiver";
public static final String RECEIVE_LOCATION_UPDATE = "LOCATION_UPDATES";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Received broadcast");
String action = intent.getAction();
if (action.equals(RECEIVE_LOCATION_UPDATE))
{
Log.i(TAG, "Received location update from service!");
}
}
}
LocationService.java
/**
* Callback that fires when the location changes.
*/
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.i(TAG, "onLocationChanged " + location);
Intent intent = new Intent(CMBroadcastReceiver.RECEIVE_LOCATION_UPDATE);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Log.i(TAG, "Broadcast sent");
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cyclemapapp.gpstracker">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<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/title_activity_main"
android:theme="#style/AppTheme.NoActionBar">
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".LocationService" android:process=":location_service" />
</application>
I the log I can see that "Broadcast Sent" But I never get the "Broadcast Received"
Any help will would be greatly appreciated.
EDIT:
Edited how the intent was created in the location service as Shaishav suggested.
Still doesn't work.
LocalBroadcastManager does not work across processes. Your Service is running in a separate process.
You can either run your Service in the same process as the Activity - by removing the process attribute from the <service> element - or use some sort of IPC instead - e.g., by sending and receiving the broadcasts on a Context instead of LocalBroadcastManager.
In your LocationService, send local broadcast using:
Intent intent = new Intent(CMBroadcastReceiver.RECEIVE_LOCATION_UPDATE);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
<service android:name=".LocationService" android:process=":location_service" />
Your service is in a separate process from the activity. LocalBroadcastManager is only for use in one process. Either remove android:process from the <service>, or use some IPC mechanism (e.g., system broadcasts, properly secured).

Wrong activity displayed when implicit intent received from another app with Action.SEND

I have an app with two activities: MainActivity, which contains a URL entry field where the user can enter a YouTube video URL and press a submit button, to start the second activity, VideoActivity, which displays some information about this video (fetched from another web server).
The app also has a feature to receive intent via the Youtube application. When user presses the share button within the Youtube app, my app appears in the share list. Upon pressing share from the Youtube app, MainActivity should be brought to the front, and the URL should be posted within the MainActivity's URL field.
However, this only happens correctly on the first share. If the app is in the background when user shares from Youtube app, they are taken to whatever the last visible activity was, whether it is MainActivity or VideoActivity, (and even if it is MainActivity, the URL is not posted into the URL field, but the field is left in whatever state it was in when the app was last visible).
Here is my current AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.youcmt.youdmcapp">
<uses-permission android:name="android.permission.INTERNET"/>
<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/AppTheme">
<activity android:name=".MainActivity"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
<activity
android:name=".VideoActivity"
android:parentActivityName=".MainActivity"/>
<service
android:name=".FetchVideoService"
android:exported="false"/>
</application>
</manifest>
Here is my MainActivity.java code:
public class MainActivity extends AppCompatActivity {
private ResponseReceiver mReceiver;
private EditText mUrlEditText;
private Button mSearchButton;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
mUrlEditText = findViewById(R.id.url_search_et);
Intent intent = getIntent();
if (intent.getType()!=null &&
intent.getType().equals("text/plain")) {
Bundle extras = getIntent().getExtras();
String value = extras.getString(Intent.EXTRA_TEXT);
if(value!=null)
{
mUrlEditText.setText(value);
}
}
mProgressBar = findViewById(R.id.progress_bar);
mSearchButton = findViewById(R.id.search_button);
mSearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
askForVideo(mUrlEditText.getText().toString());
mSearchButton.setVisibility(View.INVISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
} catch (Exception e) {
mUrlEditText.setText("");
mUrlEditText.setHint(e.getMessage());
e.printStackTrace();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
//register the ResponseReceiver
mReceiver = new ResponseReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(FETCH_VIDEO_INFO);
registerReceiver(mReceiver, intentFilter);
}
private void askForVideo (String url) throws Exception {
try {
Intent intent = FetchVideoService.newIntent(this, url);
startService(intent);
} catch (Exception e) {
mUrlEditText.setText(e.getMessage());
}
}
public class ResponseReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(EXTRA_VIDEO_STATUS, FAIL);
mProgressBar.setVisibility(View.INVISIBLE);
mSearchButton.setVisibility(View.VISIBLE);
if(status==FAIL)
{
mUrlEditText.setText("");
mUrlEditText.setHint("Error retrieving video!");
}
else if(status==SUCCESS) {
Video video = intent.getParcelableExtra(EXTRA_VIDEO);
Intent videoActivityIntent =
VideoActivity.newIntent(getApplicationContext(), video);
startActivity(videoActivityIntent);
}
}
}
#Override
protected void onPause() {
unregisterReceiver(mReceiver);
super.onPause();
}
}
I do not think any of the other files will be useful in understanding the problem. Although this seems like something many app creators should have to deal with, I can find no answers to this problem. Please comment if you feel I should add any additional information and thank you in advance for any help!
Update: testing demonstrates that after the first use of "Share" from YouTube (and considering app remains in the background), the MainActivity no longer receives any new intent on further shares. However, my app is still brought to the foreground somehow. This is very confusing to me.
When you share from another app, your MainActivity is brought to the front and onNewIntent() is called on it. You don't override onNewIntent() so you never see the share Intent.

NotificationListenerService sendBroadcast not working?

I'm trying for well over 10 hours now and I can't seem to think about anyhting else. I tried every possible example on the internet, but to no avail.
I have NotificationMonitor class extending NotificationListenerService and I wanted to send message from this service to main activity(and possible other activities and services in the future) using Intent mechanism. I post code below:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.testpackage.test">
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".NotificationMonitor"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
</application>
</manifest>
MainActivity.java
public class MainActivity extends Activity {
private TextView txtView;
private NotificationReceiver nReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtView = (TextView) findViewById(R.id.textView);
//create receiver
nReceiver = new NotificationReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.testpackage.test.NOTIFICATION_MONITOR");
registerReceiver(nReceiver,filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(nReceiver);
}
public void buttonClicked(View v){
if(v.getId() == R.id.btnTestBroadcast){
//send test intent without category
Log.d("ActivityMain","Button clicked");
Intent i = new Intent("com.testpackage.test.NOTIFICATION_MONITOR");
sendBroadcast(i);
}
}
class NotificationReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Log.d("ActivityMain","Intent received: "+intent.getAction()+" has extra: "+intent.hasExtra("info"));
if (intent.hasCategory("com.testpackage.test.TEST_CATEGORY")) {
if (intent.hasExtra("info")) {
txtView.setText(intent.getStringExtra("info"));
}
}
}
}
}
NotificationMonitor.java
public class NotificationMonitor extends NotificationListenerService {
private NotificationMonitorReceiver receiver;
#Override
public void onCreate() {
super.onCreate();
receiver = new NotificationMonitorReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.testpackage.test.NOTIFICATION_MONITOR");
registerReceiver(receiver,filter);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
//do something
sendInfo("notification posted");
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
//do something
sendInfo("notification removed");
}
#Override
public void onListenerConnected() {
//service created and listener connected
Log.d("NM","Listener connected!");
sendInfo("listener connected");
}
private void sendInfo(String info) {
Log.d("NM", "sendInfo called!");
Intent i = new Intent("com.testpackage.test.NOTIFICATION_MONITOR");
i.addCategory("com.testpackage.test.TEST_CATEGORY");
i.putExtra("info", info);
sendBroadcast(i);
}
class NotificationMonitorReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
//no categories intents get replied
Log.d("NM","Intent received: "+intent.getAction()+" has categories: "+(intent.getCategories()!=null));
if (intent.getCategories() == null) {
Intent i = new Intent("com.testpackage.test.NOTIFICATION_MONITOR");
i.addCategory("com.testpackage.test.TEST_CATEGORY");
sendBroadcast(i);
}
}
}
}
After running this app in debug mode of course I need to re-enable notification permissions, so when I do I see in logcat:
10-10 16:22:46.428 7330-7381/com.testpackage.test D/NM: Listener connected!
10-10 16:22:46.428 7330-7381/com.testpackage.test D/NM: sendInfo called!
well, I should receive broadcast in my application, shouldn't I?
After I click button:
10-10 16:22:57.607 7330-7330/com.testpackage.test D/ActivityMain: Button clicked
10-10 16:22:57.612 7330-7330/com.testpackage.test D/ActivityMain: Intent received: com.testpackage.test.NOTIFICATION_MONITOR has extra: false
10-10 16:22:57.619 7330-7330/com.testpackage.test D/NM: Intent received: com.testpackage.test.NOTIFICATION_MONITOR has categories: false
so the Intent is properly created and send from main activity, received back by the same activity and NotificationListenerService, has no categories so should get replied but nothing happens like when sendInfo method is called.
Please help, I have no other ideas about what might be wrong.
edit: I tested with regular services and of course Broadcasts are working just fine. Is there by chance any possibility that you just can't sendBroadcast from this particular extended service class?
Oficially, I'm a moron. Answer is: I didn't set up Category filter in IntentFilter and this is why I received zero properly sent intents from my class. So, long story short, to "fix" this mistake all one needs to do is add:
filter.addCategory("com.testpackage.test.TEST_CATEGORY");
and that's it. Thank you for your attention.

Android bindService() returns false when using AIDL?

For some reason I cannot bind to my service? I need the onServiceConnected() method to run so that I can use my AIDL interface. What am I doing wrong?
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
Log.d("BindingService", "Service trying to bind!");
sendService = ISendMessageService.Stub.asInterface((IBinder) service);
boundToService = true;
pendingFragment.bindToService();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
sendService = null;
boundToService = false;
pendingFragment.unbindService();
}
};
The main activity methods:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
schedulerFragment = new SchedulerFragment();
pendingFragment = new PendingFragment();
fm = getFragmentManager();
titleBar = getActionBar();
titleBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
scheduleTab = titleBar.newTab();
pendingTab = titleBar.newTab();
scheduleTab.setText("Schedule");
pendingTab.setText("Pending");
scheduleTab.setTabListener(new MyTabListener(schedulerFragment));
pendingTab.setTabListener(new MyTabListener(pendingFragment));
titleBar.addTab(scheduleTab);
titleBar.addTab(pendingTab);
titleBar.selectTab(scheduleTab);
Boolean success = getApplicationContext().bindService(new Intent(SendMessageService.class.getName()),
serviceConnection, Context.BIND_AUTO_CREATE);
Log.d("ServiceConnection", success.toString());
}
#Override
public void onStop() {
super.onStop();
if (boundToService) {
unbindService(serviceConnection);
}
}
#Override
public void onPause() {
super.onPause();
if (boundToService) {
unbindService(serviceConnection);
}
}
This is the service's onBind() function:
#Override
public IBinder onBind(Intent intent) {
mBinder = new ISendMessageService.Stub(){
#Override
public void deleteMessage(int index) throws RemoteException {
TimedMessage m = schedule.get(index);
schedule.get(index).alarm.cancel(m.intent);
schedule.remove(m);
}
#Override
public void cancelAllMessages() throws RemoteException {
for(TimedMessage m : schedule){
m.alarm.cancel(m.intent);
}
schedule.clear();
}
};
return mBinder;
The manifest:
<service
android:name="com.pearhill.messagesender.SendMessageService"
android:enabled="true"
android:exported="true"
android:process=":remote" >
<intent-filter>
<action android:name="com.pearhill.messagesender.ISendMessageService.aidl" />
</intent-filter>
</service>
Here are the links for full description:
https://developer.android.com/guide/components/bound-services.html
https://developer.android.com/guide/components/aidl.html#Calling
As a key point make sure your aidl is copied over to your application properly. Clean the project and remove aidl.
Then copy the aidl over to your application in aidl folder, but package name same of remote aidl. Rebuild. You need not to mention service in your androidManifest of calling application; it will be taken care by aidl interface that you copied over.
Make sure service is also an app and not a library (jar type). At least we couldn't make it work with service in jar file. You may choose "No activity" in the new app wizard, if you are not planning to create local activity. In that case you can create apk using "Build->Build Apk" menu in Android studio for service based app. Make sure to install the service apk before running BindService from remote app. You need not to run service as BindService will also start the service, but you need to install apk, so that it is available in system. You can use adb install path/myapkname.apk.
Action name is not must, but this is how we did bind the service, where "com.example.RemoteService.BIND" was action name for service:
String pkg = IRemoteService.class.getPackage().getName();
//get the class name from the interface package
String interfaceName = IRemoteService.class.getName();
String clsName = interfaceName.replace("IRemoteService", "RemoteService");
Intent it = new Intent("com.example.RemoteService.BIND");
it.setClassName(pkg, clsName);
boolean bRet = getApplicationContext().bindService(it, mConnection, Service.BIND_AUTO_CREATE);
Log.d("IRemote", "IRemoteService Service.BIND_AUTO_CREATE return: " + bRet);
This is what was used in eclipse and worked, but failed in Android studio because of explicit intent:
Intent it = new Intent( );
it.setClassName("com.example.aidlservice",
"com.example.aidlservice.MyService");
//optional
it.setAction("com.example.RemoteService.BIND");
//binding to remote service
boolean bRet = bindService(it, mServiceConnection, Service.BIND_AUTO_CREATE);
Log.d("IRemote", "Service.BIND_AUTO_CREATE");
Here is manifest of service app. You may want to add permissions for security reasons:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testaidl">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service android:name=".RemoteService" android:process=":remote" android:exported="true">
<intent-filter>
<action android:name="com.example.RemoteService.BIND" />
</intent-filter>
</service>
</application>
</manifest>

Categories

Resources