在这里我试过简单的服务程序.启动服务工作正常并生成Toast但停止服务没有.这个简单服务的代码如下:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
调用此服务的Activity的代码如下:
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));
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
帮我停止服务,使用停止按钮在onDestroy()方法中生成吐司.我已经在这里看到很多关于停止服务问题的帖子,但不满意所以发布新问题.希望得到满意的答复.
kre*_*ker 46
onDestroyed()
Run Code Online (Sandbox Code Playgroud)
是错的名字
onDestroy()
Run Code Online (Sandbox Code Playgroud)
你是仅在这个问题或代码中犯了错误吗?
don*_*don 12
此代码适用于我:检查此链接
当我停止并在活动中启动服务时,这是我的代码
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在服务类:
@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();
}
Run Code Online (Sandbox Code Playgroud)
快乐的编码!
Jor*_*sys 11
要停止服务,我们必须使用以下方法stopService():
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
//startService(myService);
stopService(myService);
Run Code Online (Sandbox Code Playgroud)
然后onDestroy()调用服务中的方法:
@Override
public void onDestroy() {
Log.i(TAG, "onCreate() , service stopped...");
}
Run Code Online (Sandbox Code Playgroud)
这是一个完整的示例,包括如何停止服务.
| 归档时间: |
|
| 查看次数: |
171230 次 |
| 最近记录: |