在机器人中停止服务

在这里我尝试了简单的服务程序。启动服务工作良好,并生成吐司,但停止服务不。这项简单服务的代码如下:

public class MailService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate(){
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
}
public void onDestroyed(){
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
}

调用此服务的活动代码如下:

public class ServiceTest extends Activity{
private Button start,stop;


public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_test);


start=(Button)findViewById(R.id.btnStart);
stop=(Button)findViewById(R.id.btnStop);


start.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(new Intent(ServiceTest.this,MailService.class));
}
});
stop.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(new Intent(ServiceTest.this,MailService.class));
}
});
}
}

帮助我使用 stop 按钮停止服务,该按钮在 onDestroy ()方法中生成烤面包片。我已经在这里看到了很多关于停车服务问题的帖子,但是并不令人满意,所以发布了新的问题。希望得到满意的答复。

204805 次浏览
onDestroyed()

is wrong name for

onDestroy()

Did you make a mistake only in this question or in your code too?

This code works for me: check this link
This is my code when i stop and start service in activity

case R.id.buttonStart:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
break;
}
}
}

And in service class:

  @Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");


player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}


@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}

HAPPY CODING!

To stop the service we must use the method stopService():

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
//startService(myService);
stopService(myService);

then the method onDestroy() in the service is called:

  @Override
public void onDestroy() {


Log.i(TAG, "onCreate() , service stopped...");
}

Here is a complete example including how to stop the service.