0

I am tryign to make a simple service. This is to learn how to create services. In my code when I click start button then it does show me the toast that says service started but when I click stop button then it does not show me toast which says service stopped. I am not getting any error in my logcat as well. Here is my code

package com.zafar.batterynotify;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class BatteryNotify extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button startButton = (Button) findViewById(R.id.start);
    Button stopButton = (Button) findViewById(R.id.stop);

    startButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            startService(new Intent(getBaseContext(), BatteryService.class));
        }
    });

    stopButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            stopService(new Intent(getBaseContext(), BatteryService.class));
        }
    });
}
}

service class

package com.zafar.batterynotify;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class BatteryService extends Service {

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    return START_STICKY;
}

public void onDestory() {
    super.onDestroy();
    Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}

}
Om3ga
  • 30,465
  • 43
  • 141
  • 221

2 Answers2

5
public void onDestory() { ...
                  ^^

You have a typo. Please see: When do you use Java's @Override annotation and why?, this is one of the reasons why you should use the @Override annotation.

Community
  • 1
  • 1
Mat
  • 202,337
  • 40
  • 393
  • 406
0

Try this:

1) Add the following line in manifest file:

<service  android:enabled="true"  android:name=".BatteryService " />

2) Clean your project

Bob
  • 22,810
  • 38
  • 143
  • 225