各位看官们大家好,上一回中咱们说的是Android中service的例子,这一回咱们继续说该例子。闲话休提,言归正转。让我们一起Talk Android吧!
看官们,我们在上一章回中介绍了如何使用Service,不过没有给出具体的代码,这一回中我们将通过文字结合代码的方式给大家演示如何使用Servie.详细步骤如下:
- 1.创建一个工程,工程中包含一个空的Activity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
}
}
- 2.在Activity的布局文件中添加两个Buttion,用来启动和停止服务;
<Button
android:id="@+id/id_start_service"
android:text="Start Service"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/id_stop_service"
android:text="Stop Service"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
protected void onCreate(Bundle savedInstanceState) {
mButtonStartService = (Button)findViewById(R.id.id_start_service);
mButtonStopService = (Button)findViewById(R.id.id_stop_service);
}
- 3.创建Service的子类ServiceA,并且重写四个回调方法;
public class ServiceA extends Service {
private static final String TAG = "ServiceA";
public ServiceA() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate: ThreadID: "+Thread.currentThread().toString());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy: ");
}
}
- 4.在Activity的onCreate方法中给Button添加事件监听器;
- 5.在Button的事件监听器中调用的startService和stopService方法;
final Intent intent = new Intent(this,ServiceA.class);
mButtonStartService.setOnClickListener(v -> startService(intent));
mButtonStopService.setOnClickListener(v -> stopService(intent));
下面是程序的运行结果请大家参考:
//按下Start Service Button按钮后打印出的log,从log中可以看到服务已经启动
I/ServiceA: onCreate: ThreadID: Thread[main,5,main]
I/ServiceA: onStartCommand:
//按下Stop Service Button按钮后打印出的log,从log中可以看到服务已经销毁
I/ServiceA: onDestroy:
各位看官,关于Android中Service的例子咱们就介绍到这里,欲知后面还有什么例子,且听下回分解!
本文详细介绍如何在Android应用中创建和使用Service。通过具体代码演示,包括创建工程、添加按钮、编写Service类及其回调方法,以及如何通过按钮启动和停止Service。

被折叠的 条评论
为什么被折叠?



