Why MediaPlayer keeps playing when app is closed by the user? - android

I've built a radio app which plays live music from a stream with the help of MediaPlayer.
The problem started when I created a service which job is to execute a block of code when app is closed by the user(Its job is to delete the notification). In this service I am using startForeground() method in order to make it as a foreground service and therefore keep it alive as long as the app runs (because if I don't, the OS will kill it in 1 minute).
But the problem now is that when the user closes the app the MediaPlayer keeps playing. My app didn't have this behavior before adding the startForeground() method in the service.
I don't know if this would be helpful but if I add a System.exit(0) in the onTaskRemoved() method when app is closed by the user music stops and I get a notification from OS which says that my app is consuming battery.
Does anyone know why my application has this peculiar behavior? Why the application process isn't killed??
public class OnClearFromRecentService extends Service {
private static final String TAG = "onClearFromRecentServic";
private NotificationManagerCompat mNotificationManagerCompat;
#Override
public void onCreate() {
super.onCreate();
mNotificationManagerCompat = NotificationManagerCompat.from(getApplicationContext());
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Service Started");
startForeground(2001, new NotificationCompat.Builder(getApplicationContext(), CHANNELID)
.setContentTitle("title").setContentText("contentText").build());
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Service Destroyed");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
//Put code here which will be executed when app is closed from user.
Log.d(TAG, "onTaskRemoved was executed ");
mNotificationManagerCompat.cancelAll();
stopSelf();
}
}
Manifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nikolouts.kwnstantinos.plutoradio">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:name=".App"
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.AppCompat.Light.NoActionBar">
<activity
android:name=".MainActivity"
android:screenOrientation="portrait"></activity>
<activity
android:name=".AboutActivity"
android:screenOrientation="portrait" />
<activity
android:name=".SplashScreenActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
<receiver android:name=".MainActivity$NotificationReceiver" />
<activity android:name=".ChatActivity"/>
<service android:name=".OnClearFromRecentService" android:stopWithTask="false" />
</application>
</manifest>

You have in your manifest 'stopWithTask="false"'. This tells Android not to stop your Service when the user swipes the app from the list of recent tasks. Set this to "true"

Related

Service not get called in android

I'm building a simple reminder application that will remind you of your events.
I've just used "Alarm Manager" with "Broadcast Receiver " to trigger my service at a certain time in the future. The purpose of the service is to vibrate the device when the notification arrives. Notification is working fine but, the Service isn't working as expected. I know that I can simply put the code for vibration inside the "Broadcast Receiver" but NEED TO KNOW ABOUT THE SERVICE. Don't know what's wrong with my code help me out guys, THANKS in advance.
Broadcast Receiver as follows:
public class NotificationSetter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("AlarmTriggered", "Alarm is triggered to start background service");
Intent serviceVibes = new Intent(context,BackgroundService.class);
context.startService(serviceVibes);
Toast.makeText(context, String.valueOf(Build.VERSION.SDK_INT), Toast.LENGTH_SHORT).show();
//creating the Notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "Notify");
builder.setSmallIcon(R.drawable.reminder);
builder.setContentTitle("Reminding of your event");
builder.setContentText("Time to play Cricket");
builder.setAutoCancel(true);
NotificationManagerCompat compat = NotificationManagerCompat.from(context);
compat.notify(3000, builder.build());
}
}
My service class:
public class BackgroundService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("ServiceStarted", "Service is started using NotificationSetter");
Vibrator vibes = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
vibes.vibrate(VibrationEffect.createOneShot(2000,200));
}else {
vibes.vibrate(2000);
}
Toast.makeText(getApplicationContext(), String.valueOf(Build.VERSION.SDK_INT), Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
The Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.remindme">
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:name="com.example.remindme.MyContext"
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=".StopAlarm"></activity>
<activity android:name=".GetEvent" />
<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.remindme.BackgroundService"
android:enabled="true"
android:exported="true">
</service>
<receiver android:name=".NotificationSetter"
android:enabled="true"
android:exported="true"/>
</application>
</manifest>
According to documentation, since Android 8.0 afterwards, an app cannot start a foreground service unless in a few conditions:
https://developer.android.com/about/versions/oreo/background
Check if your service is triggered when you have your app in foreground, meaning that your app has a visible Activity to user. If it works in this condition, then it means your problem lies in background execution limits introduced in Android 8.0. So to make your service work, you can start it as a foreground service by calling this line of code:
ContextCompat.startForegroundService(context, new Intent(context, YourBackgroundService.class));
A foreground service needs a notification to be shown at status bar. You can either grab an instance of your alarm notification and use it as the foreground service notification or create a new notification.

why Broadcast Receiver Don't work for service application android?

I have a project which is only a service and it has no activity and user interface. I want to start my application background service when phone boot completely. but I never receive the "BOOT_COMPLETED" Message from OS. these are my code:
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.droid.arghaman.location_tracker">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name=".BootBroadcastReceiver"
android:enabled="true"
android:exported="false"
android:label="StartServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</receiver>
</application>
<service android:name=".mySevice"></service>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
</manifest>
Broadcast Receiver:
public class BootBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("boot Received", intent.getAction());
Intent serviceLuncher = new Intent(context, myService.class);
context.startService(serviceLuncher);
}
}
myService:
public class LocationNotifierService extends Service {
Timer timer ;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate(){
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Toast.makeText(getBaseContext(),"Location",Toast.LENGTH_SHORT).show();
}
},3000);
}
#Override
public void onDestroy(){
}
#Override
public int onStartCommand(Intent intent, int flagId, int startId){
return START_STICKY;
}
}
but I never get "boot Received" log.
is there any mistake and is there any way to debug my program?
I Recommend that my project must have only this Service and it cannot have any UI.
I never receive the "BOOT_COMPLETED" Message from OS
Partly, that is because you do not have a <receiver> set up to receive android.intent.action.BOOT_COMPLETED broadcasts.
Partly, that is because your app will not receive broadcasts until something on the device uses an explicit Intent to start one of your components. The way your app is set up — without an activity that the user can run — it is unlikely that any app will do this, and so your code will never run.
Also, please bear in mind that Android O has changes designed specifically to prevent background services from running for very long and to limit your ability to get background location updates (which your location_tracker name suggests that you want to add in the future). You may wish to reconsider whether writing this app the way that you are is a wise course.
try this in your manifest
<receiver android:name=".BootBroadcastReceiver"
android:enabled="true"
android:exported="false"
android:label="StartServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

Why does a simple Service use more memory after a while?

I created a simple service example. When I start the service it uses 6.6MB or more. Some time later it increases automatically. I checked this link but found no solution. How can I confirm how much the RAM usage increased?
Service class
public class MyTestService extends Service {
public MyTestService() {
}
#Override
public void onCreate() {
super.onCreate();
Log.e("MyTestService", "onCreate");
}
#Override
public void onLowMemory() {
super.onLowMemory();
Log.e("MyTestService", "onLowMemory");
}
#Override
public IBinder onBind(Intent intent) {
Log.e("MyTestService", "onBind");
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("MyTestService", "onStartCommand");
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("MyTestService", "onDestroy");
}
}
Activity class where i only start & stop service
1. OnStartService
startService(new Intent(this, MyTestService.class));
2. OnStopService
stopService(new Intent(this, MyTestService.class));
Manifiest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sample.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=".ServiceCheckActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyTestService"
android:enabled="true"
android:exported="true"></service>
</application>
Memory usage usually increases because of lingering objects, which is not garbage collected yet, causing sawtooth - like plot in ddms. Android manages Service's lifecycle, so if it is empty, maybe you should not worry about it. For avoiding that consider using 'Flyweight' design pattern, if you need to create a lot of temporary objects.

Android Auto app never calls onGetRoot

I'm developing an audio streaming application for Android and integrating Android Auto. I've been following these two tutorials.
Android Developer Training
PTR Android Blog
Using the Desktop Head Unit, I'm able to select my media app from the media app list, but from there a ProgressBar stays instead of giving way to the "To play something, open the menu at the top left." message seen in the Universal Music Player.
On inspection, it seems that the MediaBrowserServiceCompat's onGetRoot()is never invoked and thus never populating my MediaItemCompat into the Auto app's list.
My manifest contains the following.
<manifest package="com.app.audio"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:name="com.app.audio.AudioApp"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.app.audio.presentation.home.HomeActivity"
android:label="#string/app_name"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name="com.app.audio.presentation.weather.WeatherActivity"
android:screenOrientation="userPortrait"/>
<activity android:name="com.app.audio.presentation.settings.SettingsActivity"/>
<activity android:name="com.app.audio.presentation.alarm.AlarmActivity"/>
<activity android:name="com.app.audio.presentation.sleep.SleepActivity"/>
<receiver android:name="com.app.audio.audio.AudioIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON"/>
<action android:name="android.media.AUDIO_BECOMING_NOISY"/>
</intent-filter>
</receiver>
<receiver android:name="com.app.audio.presentation.alarm.AlarmReceiver"></receiver>
<receiver android:name="com.app.audio.presentation.sleep.SleepReceiver"></receiver>
<service
android:name="com.app.audio.data.service.media.MediaService"
android:exported="true">
<intent-filter>
<action android:name="android.media.browse.MediaBrowserService"/>
</intent-filter>
</service>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<meta-data
android:name="com.google.android.gms.car.application"
android:resource="#xml/automotive_app_desc"/>
<meta-data
android:name="com.google.android.gms.car.notification.SmallIcon"
android:resource="#drawable/ic_launcher"/>
</application>
My automotive_app_desc.xml is very simple, only declaring Media.
<?xml version="1.0" encoding="utf-8"?>
<automotiveApp>
<uses name="media"/>
</automotiveApp>
My MediaService extends MediaBrowserServiceCompat. In the onCreate() I create and set my MediaSessionCompat.
#Override
public void onCreate() {
super.onCreate();
//...
mediaSession = new MediaSessionCompat(
this,
SESSION_TAG,
mediaIntentReceiver,
null
);
mediaSession.setFlags(
MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mediaSession.setCallback(new MediaSessionCompat.Callback() {
#Override
public void onPlay() {
super.onPlay();
play(selectedStream);
}
#Override
public void onPause() {
super.onPause();
pause();
}
#Override
public void onStop() {
super.onStop();
stop();
}
#Override
public void onSkipToNext() {
super.onSkipToNext();
playNextStation();
}
#Override
public void onSkipToPrevious() {
super.onSkipToPrevious();
playPreviousStation();
}
});
mediaSession.setActive(true);
setSessionToken(mediaSession.getSessionToken());
updatePlaybackState(ACTION_STOP);
}
Finally, the two overridden methods from MediaBrowserServiceCompat, of which neither is ever called.
#Nullable
#Override
public BrowserRoot onGetRoot(#NonNull String clientPackageName, int clientUid, #Nullable Bundle rootHints) {
return new BrowserRoot(ROOT_ID, null);
}
#Override
public void onLoadChildren(#NonNull String parentId, #NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
List<MediaBrowserCompat.MediaItem> items = getMediaItemsById(parentId);
if (items != null) {
result.sendResult(items);
}
}
As far as I can tell, that's everything required to get an Android Auto started, yet when I open the app on my desktop head unit, there is only a ProgressBar greeting me, and when I open the off-screen nav drawer, there's another one. I haven't heard of that state in any material I've read. Is there something I missed?
Ultimately, the issue didn't have anything to do with what I described. The aforementioned MediaService also does other tasks that require a custom Binder. This custom Binder didn't call the onGetRoot() needed for the Head Unit. As a solution, I check the Intent action and return super.onBind() when it's from the MediaBrowserServiceCompat.
#Override
public IBinder onBind(Intent intent) {
if (SERVICE_INTERFACE.equals(intent.getAction())) {
return super.onBind(intent);
}
return new MediaBinder();
}
The SERVICE_INTERFACE is a constant in MediaBrowserServiceCompat.
I'm developing an Android auto but I have some problems in this part of my code, in Onbind method of the service:
public IBinder onBind(Intent arg0) {
Log.i("TAG", "OnBind");
// TODO Auto-generated method stub
if (SERVICE_INTERFACE.equals(arg0.getAction())) {
Log.i("TAG", "SERVICE_INTERFACE");
registerReceiver(receiver, filter);
return super.onBind(arg0);
} else {
Log.i("Musica Service", "musicBind");
return musicBind;}
}
I have other activities bound with my service through a musicBind IBinder, but on the other hand I have set all things to connect my app in Android auto interface but after close my app after disconnect the device from the android auto I can't stop my mediabrowserservice compat. I think it's due to this SERVICE_INTERFACE keeps binded the service. How can I stop or destroy this from the same servicemediabrowserservicecompat?

Unable to start service Intent: not found

I've the same issue described here but i can't understand whats wrong.
My issue is: Unable to start service Intent { act=.connections.MoodyService } U=0: not found
EDIT
I've changed my package from connections to service in the source code, sorry for the confusion
My manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.moody"
android:installLocation="auto"
android:versionCode="0"
android:versionName="0.6.7 alpha" >
<uses-sdk
android:maxSdkVersion="18"
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:allowClearUserData="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="activities.MainActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name="activities.Menu_esq"
android:label="#string/title_activity_menu_esq" >
</activity>
<activity
android:name="activities.BaseActivity"
android:label="#string/title_activity_base" >
</activity>
<activity
android:name="activities.MainView"
android:label="#string/title_activity_main_view" >
</activity>
<activity
android:name="activities.LoginActivity"
android:label="#string/app_name"
android:noHistory="true"
android:windowSoftInputMode="adjustResize|stateVisible" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.moody.LeftActivity"
android:label="#string/title_activity_left" >
</activity>
<activity
android:name="com.example.moody.RightActivity"
android:label="#string/title_activity_right" >
</activity>
<activity
android:name="activities.UserDetailsActivity"
android:label="#string/title_activity_user_details" >
</activity>
<activity
android:name="fragments.TopicsPreview"
android:label="#string/title_activity_copy_of_topics_preview" >
</activity>
<activity android:name="activities.Loading" >
</activity>
<service
android:name=".service.MoodyService"
android:icon="#drawable/ic_launcher"
android:label="#string/moody_service" >
</service>
</application>
service is the package and MoodyService is the class name
My service class
public class MoodyService extends Service {
public MoodyService() {
// TODO Auto-generated constructor stub
}
private boolean isRunning = false;
Object getContent;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// Announcement about starting
Toast.makeText(this, "Starting the Demo Service", Toast.LENGTH_SHORT)
.show();
// Start a Background thread
isRunning = true;
Thread backgroundThread = new Thread(new BackgroundThread());
backgroundThread.start();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Background thread
isRunning = false;
// Announcement about stopping
Toast.makeText(this, "Stopping the Demo Service", Toast.LENGTH_SHORT)
.show();
}
private class BackgroundThread implements Runnable {
int counter = 0;
public void run() {
try {
counter = 0;
while (isRunning) {
System.out.println("" + counter++);
new Contents().getAll(getResources(),
getApplicationContext());
Thread.currentThread().sleep(5000);
}
System.out.println("Background Thread is finished.........");
} catch (Exception e) {
e.printStackTrace();
}
}
}
And in my main Intent.
Intent start = new Intent(".service.MoodyService");
this.startService(start);
and also tried
Intent intent = new Intent(this, MoodyService.class);
this.startService(intent);
and tried with the full path
<service
android:name="com.example.moody.service.MoodyService"
android:icon="#drawable/ic_launcher"
android:label="#string/moody_service" >
Solved
I deleted the period in the beginning of the package name in the manifest and it worked, in another words:
This doesn't work:
.yourPackage.YourClass
But this does work:
yourPackage.YourClass
And in the main:
Intent intent = new Intent(this, MoodyService.class);
this.startService(intent);
But it goes against what is written in the documentation:
android:name The name of the Service subclass that implements the service. This should be a fully qualified class name (such as,
"com.example.project.RoomService"). However, as a shorthand, if the
first character of the name is a period (for example, ".RoomService"),
it is appended to the package name specified in the
element. Once you publish your application, you should not change this
name (unless you've set android:exported="false").
There is no default. The name must be specified.
The service must be also be included in the Manifest:
<service android:name="com.x.x.serviceclass"></service>
Make sure you have declared your service in the manifest file.
<service
android:name=".MyService"
android:enabled="true" >
</service>
and try writing getApplicationContext() instead of "this" keyword
startService(new Intent(getApplicationContext(), MoodyService.class));
I don't know why you are using that package-like name for your service name, but why don't you use class name for starting the service?
Intent intent = new Intent(context, YourService.class);
context.startService(intent);
I think in manifest package name for service is wrong as you said your package name is connections so it should be like this
android:name ="connections.MoodyService"
or
android:name="com.example.moody.connections.MoodyService"
to invoke service do
Intent intent = new Intent(this, MoodyService.class);
this.startService(intent);
my service is in "service" package and my manifest service enrty like this;
<service
android:name="service.TimerService"
android:exported="false" >
</service>
Did you create an empty constructor in the service?
If not, try that.
Also uncertain if you can use the Intent like that. You could try the 'new Inten(this, MoodyService.class)' construction.
Did you try to use the android:name that you specified in the Manifest?
Android Manifest:
<service
android:enabled="true"
android:name="UploadService" />
The call would be sth like this:
Intent intent = new Intent("UploadService");

Categories

Resources