Why my service can't be destroyed - android

Sorry for my English.
I have one Activity that call one service and i want to stop this service from that Activity.
I try to use stopService(getApplicationContext(), TempService.class) And it doesn't worked.
Here is my service code
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("Debug", "Service start");
mgr = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
temp = mgr.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
mgr.registerListener(this, temp, SensorManager.SENSOR_DELAY_FASTEST);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onDestroy() {
Log.d("DEBUG", "on destroy");
notificationManager.cancel(0);
super.onDestroy();
}
And in my Activity : boolean t always return false value.
I have no idea.
private void processStopService(final String tag) {
Intent intent = new Intent(getApplicationContext(), TempService.class);
intent.addCategory(tag);
boolean t = stopService(intent);
if (t)
{
Log.e("DEBUG", "TRUE");
}
else
Log.e("DEBUG", "FALSE");
}

Do not use categories with services. Delete the addCategory() call on your Intent.

Related

why restart the service

i have a problem in my service, the service is runnig from MainActivity (i am doing test) and extends of service.
i want to use the service from foreground and background (when the app is closed) and i already have my first problem:
my service(have a counter that is displayed by LOG) is restarting when i close the app.
also i want to be able to use the service with the open app and close app, in other words to use both the Service Started and Link Service
public class MyService extends Service {
private Thread backgroundThread;
private boolean isRunning;
public MyService() {
Log.e("MyService","constructor");
}
#Override
public void onCreate() {
super.onCreate();
isRunning = false;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Log.e("onStartCommand","Servicio Llamado");
if (!this.isRunning) {
Log.e("onStartCommand","hilo iniciandose");
this.backgroundThread = new Thread(myTask);
runTask();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("onDestroy","servicio destuido");
}
private void runTask(){
this.isRunning = true;
this.backgroundThread.start();
}
private Runnable myTask = new Runnable() {
public void run() {
Log.e("myTask","hilo iniciado");
int i = 0;
do{
pauseService();
Log.e("myTask","hilo contador: "+i);
//Toast.makeText(getApplicationContext(),"CONTADOR = "+j, Toast.LENGTH_SHORT).show(); //no working :(
i++;
}while (i<10);
/*
//linea de detencion del servicio
//stopSelf();
isRunning=false;
backgroundThread.interrupt();
//backgroundThread = new Thread(myTask);
*/
Log.e("myTask","hilo cerrado");
}
};
private void pauseService(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In main Activity
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("iteraciones",10);
startService(intent);
why because the service restarts when I close the application and how can I avoid it?

How to create notification with media controls for API 16 service

I have a service playing music, and I need it do display a notification with "play", "pause" and "stop" buttons. My service code is:
public class RadioService extends Service implements MediaPlayer.OnPreparedListener {
MediaPlayer radioPlayer;
String url = "radiourl";
String action;
public RadioService() {
}
#Override
public IBinder onBind(Intent intent) {
Log.e("Service", "Bind");
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Service", "onStart");
action = intent.getAction();
Log.e("ServiceAction", action);
switch (action) {
case "play":
radioPlayer = new MediaPlayer();
radioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
radioPlayer.setDataSource(url);
} catch (IOException e) {
Log.e("setDataSource", e.toString());
}
radioPlayer.prepareAsync();
radioPlayer.setOnPreparedListener(this);
}
return START_STICKY;
}
#Override
public void onPrepared(MediaPlayer radioPlayer) {
Log.e("Service", "onPrepared");
radioPlayer.start();
}
#Override
public void onDestroy() {
Log.e("Service", "onDestroy");
if(radioPlayer != null && radioPlayer.isPlaying()) {
radioPlayer.stop();
radioPlayer.reset();
radioPlayer.release();
}
super.onDestroy();
}
}
My notification has to be compatible with API 16 and higher. I want notification buttons to send an action to my service, that will execute a proper case in my switch instruction. Is this even possibe? How should my service look like?

How to pass object from service to a calling activity

I am working on a Chat messenger.I have used socket.io-client library.I have created a service that will instantiate Socket class.
SocketService.java
public class SocketService extends Service {
public static Socket mSocket;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String data = intent.getStringExtra("Socket");
Log.e("intent data", data);
Log.e("Service", "Called");
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
super.onCreate();
Log.e("Service", "created");
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
Log.e("ValueSocket", String.valueOf(mSocket));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
I am starting the service in SplashActivity.java.I have to pass Socket instance i.e. mSocket to Activity SplashActivity.java .How can i achieve this in android?Please help .

Android service does not re-started after application is force closed.

I started my service properly, its working well. I write condition that if service is already running then it don't start service again. condition returns true values which shows that service is running. But whenever I force stop my application, or if any exception occurred, my service stops loading data at background and till showing that service is running. That's why service is not re-started.
Intent that I used to start service from activity :
this.startService(new Intent(MainMenu1.this, MovieService.class));
And My service class is :
public class MovieService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TBD
Log.i("Movie Service : "," Created2");
new MovieDownloaderTask().execute();
return Service.START_FLAG_REDELIVERY;
//return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Log.i("Movie Service : "," Created");
}
#Override
public void onDestroy() {
Log.d("Movie Service","onDestroy was Called!");
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startid) {
Log.i("Movie Service : "," Started");
}
public class MovieDownloaderTask extends AsyncTask<Void, Void, Integer>
{
#Override
protected Integer doInBackground(Void... params) {
Log.i("Movie Service"," : Started2");
//Moviejson.createDB();
try
{
Moviejson.insert_Movie_Data();
}
catch(Exception e)
{
Log.e("Exception > ", "i m in doInBackground. Trying to stop Movie service.");
MovieService.this.stopSelf();
e.printStackTrace();
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
if(MainMenu1.Movies_new_time==null)
{
MainMenu1.Movies_new_time=MainMenu1.sp.getMovies_Old_Date();
}
else
{
MainMenu1.sp.setMovies_Current_Date(MainMenu1.Movies_new_time);
}
MainMenu1.sp.setMovies_Current_Date(MainMenu1.Movies_new_time);
Log.i("Movie Date:", " : "+MainMenu1.Movies_new_time);
MovieService.this.stopSelf();
Log.i("Movie Service"," : Stoped");
super.onPostExecute(result);
}
}
}
}
In your onStartCommand(), replace
return Service.START_FLAG_REDELIVERY;
with
return Service.START_REDELIVER_INTENT

How to create widget for start and stop voice recording

In my project I have created a widget class, a service and a remote service, however I'm not able to
call the methods for starting or stopping it. I've sample codes here
For widget
Intent intent = new Intent(context, med_service.class);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
Toast.makeText(context, pi.toString() + intent.toString(), Toast.LENGTH_SHORT).show();
views.setOnClickPendingIntent(R.id.button1, pi);
Toast.makeText(context, pi.toString() + intent.toString(), Toast.LENGTH_SHORT).show();
for remote service
public class service extends Service implements IBinder{
public IBinder onBind(Intent intent) {
Log.i("RemoteService", "onBind() called");
return new RemoteServiceImpl();
}
/**
* The IRemoteInterface is defined through IDL
*/
public class RemoteServiceImpl extends IRemoteService.Stub {
#Override
public void start() throws RemoteException {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "inside start method", Toast.LENGTH_SHORT).show();
}
#Override
public void stop() throws RemoteException {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "inside stop method", Toast.LENGTH_SHORT).show();
}
}
for service
public class med_service extends Service{
IRemoteService mService;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i("RemoteService", "onBind() called");
Toast.makeText(getApplicationContext(), "service not bind to connection", Toast.LENGTH_SHORT).show();
return new service();
}
class RemoteServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName className, IBinder service ) {
mService = IRemoteService.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
try{
RemoteServiceConnection mConnection = new RemoteServiceConnection();
getApplicationContext().bindService(new Intent(IRemoteService.class.getName()), mConnection, Context.BIND_AUTO_CREATE);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "service not bind to connection", Toast.LENGTH_SHORT).show();
}
try {
mService.start();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 1;
}
any kind of help is appreciated
Thank You in advance
use getService instead of getActivity

Categories

Resources