This question already has answers here:
Press home button to stop service
(3 answers)
Closed 6 years ago.
I am implementing following service to play sound. This sound stop when someone press on any menu button. But If I press home key of device sound still playing. I am adding this code
#Override
protected void onPause() {
super.onPause();
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
}
in my activity class. But still sound not stop. why onPause method is not working?
Service code-
public class PlayAudio extends Service{
private static final String LOGCAT = null;
MediaPlayer objPlayer;
public void onCreate(){
super.onCreate();
Log.d(LOGCAT, "Service Started!");
objPlayer = MediaPlayer.create(this, R.raw.test);
}
public int onStartCommand(Intent intent, int flags, int startId){
objPlayer.start();
Log.d(LOGCAT, "Media Player started!");
if(objPlayer.isLooping() != true){
Log.d(LOGCAT, "Problem in Playing Audio");
}
return 1;
}
public void onStop(){
objPlayer.stop();
objPlayer.release();
}
public void onPause(){
objPlayer.stop();
objPlayer.release();
}
public void onDestroy(){
objPlayer.stop();
objPlayer.release();
}
#Override
public IBinder onBind(Intent objIndent) {
return null;
}
}
you can stop service on home key press..try this
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_HOME)
{
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
}
});
write one Thread in Service which continuosly checks for running tasks and stop the Service if top task's top activity package name is equal to the package name of launcher app...
new Thread() {
public void run() {
final List<ResolveInfo> activities = getPackageManager().queryIntentActivities(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);
final ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
while(true) {
String packageName = activityManager.getRunningTasks(5).get(0).topActivity.getPackageName();
if(activities.contains(packageName)) {
break;
}
try {
Thread.sleep(500); // wait for half second
} catch (InterruptedException e) {
}
}
stopSelf();
};
}.start();
Related
I've been reading a while and all about services, I'm not all in dev, I'm new to this stuff and wanna learn, as a test I'm trying to make an online radio stream app. I already made it and it works perfect, my only problem is I can't seem to find the way to make the services work or how to do so, I know most of you all are great devs on android and all but just looking for a teacher or someone willing to show me how
this is my code:
public class MainActivity extends AppCompatActivity
{
Button b_play1;
MediaPlayer mediaPlayer;
boolean prepared;
String stream = "http://73.160.214.181:8000/stream";
private boolean started;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, mServices.class));
b_play1 = (Button) findViewById(R.id.play1);
b_play1.setEnabled(false);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
b_play1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
if (started) {
started = false;
mediaPlayer.pause();
b_play1.setBackground(getDrawable(play));
} else {
started = true;
mediaPlayer.start();
b_play1.setBackground(getDrawable(pause));
}
}
});
}
#Override
protected void onPause()
{
super.onPause();
if(started){
mediaPlayer.pause();
}
}
#Override
protected void onResume()
{
super.onResume();
if(started){
mediaPlayer.start();
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if(prepared){
mediaPlayer.release();
}
}
class PlayerTask extends AsyncTask<String, Void, Boolean>
{
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
b_play1.setEnabled(true);
}
}}
I wrote an Android audio chapter in my book, and in it I present an app that plays music using a background service.
So here I am going to summarize it and slightly adapt it using your code to show how you should be able to stream from background service. Instead of using the Async task in your Activity, your are going to have a mainActivity that binds to a Service that does the streaming.
First, you need to define the service in your manifest: (obviously use your package name, not mine shown below)
<application
<service
android:name="com.wickham.android.musicservice.MusicService"
android:label="Music Service"
android:enabled="true">
</service>
Then, you need to bind your Activity to the service. The Activity can be used to control the service, such as starting and stopping the stream: (the following code block go in your Main Activity, that is where you have everything now)
// Bind the Service
bindService(new Intent(this,MusicService.class), Scon,Context.BIND_AUTO_CREATE);
// Connect to Service
public void onServiceConnected(ComponentName name, IBinder binder) {
mServ = ((MusicService.ServiceBinder)binder).getServiceInstance();}
// Start the service
Intent music = new Intent();
music.setClass(this,MusicService.class);
startService(music);
// Controlling the service
mServ.resumeMusic();
mServ.pauseMusic();
Then, in your service class that will be doing the actual streaming, you can implement it like this: (I did not include the two methods called resumeMusic() and pauseMusic(), but those go in the service and do basically what you had already in your activity.
public class MusicService extends Service implements MediaPlayer.OnErrorListener{
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
public MusicService() { }
public class ServiceBinder extends Binder {
public MusicService getServiceInstance() {
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0){return mBinder;}
#Override
public void onCreate () {
super.onCreate();
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setOnErrorListener(this);
mPlayer.setLooping(false);
mPlayer.setVolume(100,100);
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
onError(mPlayer, what, extra);
return true;
}
});
}
}
Hope this can help a little bit.
create a service class like
public class MyService extends Service {
MediaPlayer mPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
mPlayer = MediaPlayer.create(this, R.raw.laila);
mPlayer.setLooping(false); // Set looping
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
mPlayer.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
mPlayer.stop();
}
}
Add below line in your Manifest.xml file
<service android:name=".service.MyService" android:enabled="true"/>
You can start service by calling
startService(new Intent(this, MyService.class));
and stop service
stopService(new Intent(this, MyService.class));
This is the basic flow how to start and stop a service. You can read more here Service
I'm using a background service to run a background music for my app in all of it's activities! The issue is that when the app run, it works fine but when I close it it keeps on playing the music until I uninstall it from the device!
What do you think the problem here?
Here is The code In my Background service:
/**
* Created by Naira on 12/5/2016.
*/
public class Background_music extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.music);
player.setLooping(true); // Set looping
player.setVolume(50,50);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return START_STICKY;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
player = null;
}
#Override
public void onLowMemory() {
}
}
An here the code in my first activity to run it as an Intent:
Intent svc=new Intent(this, Background_music.class);
startService(svc);
And, of course I did declare it in my manifest =)
Thanks in advance!
In the onDestroy() method of your MainActivity you have to stop the service.
#Override
protected void onDestroy() {
super.onDestroy();
if(isMyServiceRunning(Background_music.class))
{
stopService(new Intent(this, Background_music.class));
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
Hope this helps you.
I have background service in my android app,i start service from MainActivity onResume() method and it is work correctly.But how can i stop service when user press home button.Because currently when user press home button then application move to background and then user open some other app then after some time my service method is called and app force stop.Below is my code for start service -
Intent msgIntent = new Intent(mContext, MyBackgroundService.class);
startService(msgIntent);
Thanks in Advance.
EDITED
In My Service i use below code -
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
callWebservice();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
timer.schedule(doAsynchronousTask, START_DELAY, DELAY);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
callAsynchronousTask();
return Service.START_NOT_STICKY;
}
#Override
public void onCreate() {
mContext = this;
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
if(timer!=null){
timer.cancel();
}
stopSelf();
}
in my activity i use below code for stop service -
#Override
protected void onStop() {
try{
stopService(new Intent(this, MyBackgroundService.class));
isServiceRunning = false;
}
catch(Exception e){
e.printStackTrace();
}
super.onStop();
}
#Override
protected void onPause() {
try{
stopService(new Intent(this, MyBackgroundService.class));
isServiceRunning = false;
}
catch(Exception e){
e.printStackTrace();
}
super.onPause();
}
but my service is run while i use some other app and it force stop app.From background service i call some webservice and then store response of service in database.
Stop the service in onPause() and onStop()
mContext.stopService(new Intent(mContext,
MyBackgroundService.class))
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_HOME){
Log.e("home key pressed", "****");
// write your code here to stop the activity
enter code here
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onPause() {
Log.e("home key pressed on pause", "****");
// write your code here to stop your service
super.onPause();
}
the above code will keep check if user have pressed the home button or not.
when we open the other applications then our application(which was in background) gets cleared from the memory However the whole application does not removed but the some unwanted data and activities get finished.
In your case the activity which is to be updated gets cleared from the memory and your running background service when try to update the UI then it gets crashed by throwing NullPointerException.
So please saved the Reference of the activty(whose UI is to be updated) in onCreate() and set the reference to null in finish() method then check this reference in the background service if it is not null then update the UI otherwise no updation.
// Global Class for saving the reference
class GlobalReference{
public static <name_of_your_activity> activityRef;
}
in your activity
onCreate(){
GlobalReference.activityRef = this;
}
finish(){
GlobalReference.activityRef = null;
}
In your background service
if( GlobalReference.activityRef != null){
// update the UI of your activity
}
Hope this code will solve your issue.
Happy Coding...
press Home Button cause OnPause() function. Override onPause() and call stopService:
mContext.stopService(new Intent(mContext,
MyBackgroundService.class))
I need to have background music in all my activities. It should stop when the application is not foreground. As I'm developing for 2.3 I can't use the ActivityLifeCycleCallBacks class. I implemented the solution at Checking if an Android application is running in the background and then decided to make the mediaplayer a singleton and use it in a service.
Everything works fine and if I press home, select quit from the menu or I make the application go background any way the sound stops but... after some random time when I'm doing something else or even when the screen is turned off the music will start again out of the blue. Even if I kill the application from task manager the will start again later again.
This is my first singleton and my first time playing with service so I guess I'm missing something really basic. I think I'm closing the service but apparently I'm not.
Here is the code:
PlayAudio.java
import ...
public class PlayAudio extends Service{
private static final Intent Intent = null;
MediaPlayer objPlayer;
private int length = 0;
boolean mIsPlayerRelease = true;
private static PlayAudio uniqueIstance; //the singleton
static PlayAudio mService;
static boolean mBound = false; // boolean to check if the service containing this singleton is binded to some activity
public static boolean activityVisible; // boolean to check if the activity using the player is foreground or not
//My attempt to make a singleton
public static PlayAudio getUniqueIstance(){
if (uniqueIstance == null) {
uniqueIstance = new PlayAudio();
}
return uniqueIstance;
}
public static boolean isActivityVisible() {
return activityVisible;
}
public static void activityResumed() {
activityVisible = true;
}
public static void activityPaused() {
activityVisible = false;
}
static public ServiceConnection mConnection = new ServiceConnection() {// helper for the activity
public void onServiceConnected(ComponentName className,
IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
public static Intent createIntent (Context context) { //helper for the activity using the player
Intent intent = new Intent(context, PlayAudio.class);
return intent;
}
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
PlayAudio getService() {
// Return this instance so clients can call public methods
return PlayAudio.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void onCreate(){
super.onCreate();
Log.d(LOGCAT, "Service Started!");
objPlayer = MediaPlayer.create(this,R.raw.kickstarterreduced);
objPlayer.setLooping(true);
mIsPlayerRelease = false;
}
public int onStartCommand(Intent intent, int flags, int startId){
objPlayer.start();
Log.d(LOGCAT, "Media Player started!");
if(objPlayer.isLooping() != true){
Log.d(LOGCAT, "Problem in Playing Audio");
}
return 1;
}
public void onStop(){
objPlayer.setLooping(false);
objPlayer.stop();
objPlayer.release();
mIsPlayerRelease = true;
}
public void onPause(){
if(objPlayer.isPlaying())
{
objPlayer.pause();
length=objPlayer.getCurrentPosition(); // save the position in order to be able to resume from here
}
}
public void resumeMusic() // if length is 0 the player just start from zero
{ if (mIsPlayerRelease == true) {
objPlayer = MediaPlayer.create(this,R.raw.kickstarterreduced);
mIsPlayerRelease = false;
}
if(objPlayer.isPlaying()==false )
{
if (length != 0) objPlayer.seekTo(length);
objPlayer.start();
}
}
}
And this are the methods I have implemented in every activity's class
SharedPreferences sharedPrefs;
PlayAudio playerIstanced;
public static boolean activityVisible;
#Override
public void onStart() {
super.onStart();
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
public void onResume() {
super.onResume();
playerIstanced= PlayAudio.getUniqueIstance(); //call singleton
bindService(PlayAudio.createIntent(this), playerIstanced.mConnection, Context.BIND_AUTO_CREATE); // create the service
if (sharedPrefs.getBoolean("sound", true) == true) {// if sound is enabled in option it will start the service
startService(PlayAudio.createIntent(this));
playerIstanced.mService.activityResumed();
if (playerIstanced.mBound == true) {
playerIstanced.mService.resumeMusic();
}
}
}
#Override
public void onPause() {
super.onPause();
playerIstanced.mService.activityPaused();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//If the phone lags when changing activity (between onPause() and the other activity onResume() the music won't stop. If after 500ms onResume() is not called it means the activity went background...Am I messing with service here?
if (playerIstanced.mService.isActivityVisible() != true) {
playerIstanced.mService.onPause();
}
}
}, 500);
}
#Override
public void onStop(){
super.onStop();
// Unbind from the service
if (playerIstanced.mService.mBound) {
playerIstanced.mService.mBound = false;
unbindService(playerIstanced.mService.mConnection);
}
}
}
Stop music automatically when user exit from app
This part has to be in EVERY activity's onPause:
public void onPause(){
super.onPause();
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
StopPlayer();
Toast.makeText(xYourClassNamex.this, "YOU LEFT YOUR APP. MUSIC STOP", Toast.LENGTH_SHORT).show();
}
}
}
This part has to be in EVERY activity's onResume:
Play music automatically when user resume the app
Public void onResume()
{
super.onResume();
StartPlayer();
}
Hope it helps!!
You can check my answer according to this topic may it will sove your issue.
You need to manually stop the service using Context.stopService() or stopSelf(). See the Service Lifecycle section of http://developer.android.com/reference/android/app/Service.html.
Service Lifecycle
There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.
I believe you can simply put playerIstanced.stopSelf() in the onStop() call of each activity.
My understanding is that the service continues to run quietly after your application stops. After a while the system kills the service to free up resources, and then after a while more when resources are available it restarts the service. When the service restarts its onResume() is called and the music begins playing.
it helped me stop the mediaplayer.
Use Handler(getMainLooper()) to start and stop MediaPlayer.
final Handler handler = new Handler(getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
mediaPlayer.start();
}
});
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
, 30 * 1000);
I have an app that runs a webview as a service so the audio can contiune to play while the screen is locked. The app works great with audio streams such as podcasts. But I also wanted it to work with flash video. I am able to load the flash video stream in the webview and have it play smooth and steady but once the screen goes off or is locked the audio becomes choppy. The behavior is the same on 3g and WiFi. I tried to use this posts suggestion of using a wake lock with:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Tag");
wl.acquire();
//do what you need to do
wl.release();
However this has no effect. I'm not sure where exactly in my code to put it but I've placed it in the oncreate for the service, which had no effect, and I placed it in the oncreate for my main activity with the same results.
However later in the post the person asking the question said that WIFI_MODE_FULL_HIGH_PERF was able to fix the problem. But as I said I tested it on 3g and the audio stuttered when the screen was turned off.
Any ideas how I can stop this behavior?
Also I know this is a CPU intensive and a battery hog app but I'm just developing it for personal use.
This is my full code for the service:
public class MyService extends Service {
private NotificationManager nm;
private static boolean isRunning = false;
ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
int mValue = 0; // Holds last value set by a client.
static final int MSG_REGISTER_CLIENT = 1;
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_SET_INT_VALUE = 3;
static final int MSG_SET_STRING_VALUE = 4;
PowerManager.WakeLock wl;
#Override
public IBinder onBind(Intent intent) {
wl.acquire();
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.i("MyService", "Service Started.");
showNotification();
isRunning = true;
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Tag");
}
private void showNotification() {
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.ic_launcher, text, System.currentTimeMillis());
notification.flags = Notification.FLAG_ONGOING_EVENT;
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
nm.notify(R.string.service_started, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("MyService", "Received start id " + startId + ": " + intent);
return START_STICKY; // run until explicitly stopped.
}
public static boolean isRunning()
{
return isRunning;
}
#Override
public void onDestroy() {
super.onDestroy();
nm.cancelAll();
wl.release();
nm.cancel(R.string.service_started); // Cancel the persistent notification.
Log.i("MyService", "Service Stopped.");
isRunning = false;
}
}
My main code:
public class MainActivity extends Activity {
Button btnStart, btnStop, btnBind, btnUnbind, btnUpby1, btnUpby10;
Messenger mService = null;
boolean mIsBound;
WebView mWebView;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
try {
Message msg = Message.obtain(null, MyService.MSG_REGISTER_CLIENT);
mService.send(msg);
} catch (RemoteException e) {
// In this case the service has crashed before we could even do anything with it
}
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been unexpectedly disconnected - process crashed.
mService = null;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnStart = (Button)findViewById(R.id.btnStart);
btnStop = (Button)findViewById(R.id.btnStop);
btnBind = (Button)findViewById(R.id.btnBind);
btnUnbind = (Button)findViewById(R.id.btnUnbind);
btnStart.setOnClickListener(btnStartListener);
btnStop.setOnClickListener(btnStopListener);
btnBind.setOnClickListener(btnBindListener);
CheckIfServiceIsRunning();
//webview
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.loadUrl(url);
mWebView.setWebViewClient(new HelloWebViewClient());
}
private void CheckIfServiceIsRunning() {
//If the service is running when the activity starts, we want to automatically bind to it.
if (MyService.isRunning()) {
doBindService();
}
}
private OnClickListener btnStartListener = new OnClickListener() {
public void onClick(View v){
startService(new Intent(MainActivity.this, MyService.class));
}
};
private OnClickListener btnStopListener = new OnClickListener() {
public void onClick(View v){
doUnbindService();
stopService(new Intent(MainActivity.this, MyService.class));
}
};
private OnClickListener btnBindListener = new OnClickListener() {
public void onClick(View v){
doBindService();
}
};
private OnClickListener btnUnbindListener = new OnClickListener() {
public void onClick(View v){
doUnbindService();
}
};
void doBindService() {
bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
// If we have received the service, and hence registered with it, then now is the time to unregister.
if (mService != null) {
try {
Message msg = Message.obtain(null, MyService.MSG_UNREGISTER_CLIENT);
mService.send(msg);
} catch (RemoteException e) {
// There is nothing special we need to do if the service has crashed.
}
}
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
doUnbindService();
} catch (Throwable t) {
Log.e("MainActivity", "Failed to unbind from the service", t);
}
}
#Override
protected void onResume() {
super.onResume();
}
}
From your description it sounds like you are releasing the WakeLock too soon.
If you are just putting that block of code in the onCreate for the Service then you really aren't getting a WakeLock while your streaming code is running. You must have the lock acquired for the duration of the background work.
The pattern I've used for a service like this is:
Create the WakeLock in onCreate (but do not acquire it)
In onDestroy if the WakeLock is held release it. (mostly for safety)
When starting the actual background work, either in onBind or onStartCommand, acquire the lock.
When done with the background work, release the wake lock.
The problem may be specifically with the way a WebView works. That said since this isn't production code, you could try simply 'leaking' the wake lock by removing the release just to see if that helps. Just create and acquire the lock at the start of your activity and not bother with the Service.
The Service isn't really giving you much. The way your code is currently structured you are still going to have problems. Your Activity can be still deleted when in the background even if you have a Service, simply having a service won't stop this. Further because the WebView is a View it really requires an Activity and view hierarchy.