android组件启动,Android四大组件之Service --- 如何启动和停止Service?

启动和停止方法主要是通过Intent来实现

以上一篇中的ServiceTest项目为例来启动和停止MyService这个服务

首先修改activity_main.xml中的代码,如下所示:

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="match_parent">

//添加两个按钮分别用来启动和停止服务

android:id="@+id/start_service"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Start Service" />

android:id="@+id/stop_service"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Stop Service" />

然后修改MainActivity中的代码,如下所示:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button startService = (Button) findViewById(R.id.start_service);

Button stopService = (Button) findViewById(R.id.stop_service);

startService.setOnClickListener(this);

stopService.setOnClickListener(this);

}

@Override

public void onClick(View v) {

switch (v.getId()) {

case R.id.start_service:

Intent startIntent = new Intent(this, MyService.class);

startService(startIntent); // 启动服务

break;

case R.id.stop_service:

Intent stopIntent = new Intent(this, MyService.class);

stopService(stopIntent); // 停止服务

break;

default:

break;

}

}

}

注意,startService() 和 stopService()都是定义在Context类中的,所以我们在活动中可以直接调用它们。

在上面这个例子中,只要没有点击stop service按钮,Service会一直处于运行状态。那么服务器可以自己停下来吗?

答案是肯定的,只要在MyService的任何一个位置调用stopSelf()方法即可。

优化: 如何证实服务已经成功启动/停止了呢?

最简单的方法是在MyService的几个方法中加入打印日志:

public class MyService extends Service {

...

@Override

public void onCreate() {

super.onCreate();

Log.d("MyService", "onCreate executed");

}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

Log.d("MyService", "onStartCommand executed");

return super.onStartCommand(intent, flags, startId);

}

@Override

public void onDestroy() {

super.onDestroy();

Log.d("MyService", "onDestroy executed");

}

}

来源:https://www.cnblogs.com/pinkstrawberry/p/8320684.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值