Service即服务,没有UI,在手机中常见的运用是音乐播放器,音乐播放器能够在后台播放音乐,用的就是Service来实现的。
java文件:
运行结果:
参考网上的资料,做了一个玩玩。(也可以说是照搬了一个。)
请结合Service的生命周期来理解。
使用service需要在AndroidManifest.xml的application标签中加入 <service android:enabled="true" android:name="com.ccav.Service"/>(name后面的参数请根据实际情况修改)
首先是XML布局文件
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical" android:id="@+id/layout">
<Button android:id="@+id/button1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="StartServer"
android:onClick="onClick" />
<Button android:text="Stop Server" android:id="@+id/button2"
android:layout_width="match_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>
java文件:
Hello_worldActivity.java
package com.ccav;
import com.fjep.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Hello_worldActivity extends Activity implements OnClickListener {
private Intent intent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 发现控件并设置监听事件
Button startServer = (Button) findViewById(R.id.button1);
Button stopServer = (Button) findViewById(R.id.button2);
startServer.setOnClickListener(this);
stopServer.setOnClickListener(this);
// intent设置需要启动的class,这里指定的是service这个class
intent = new Intent(Hello_worldActivity.this, Service.class);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
// 启动服务的方法
startService(intent);
break;
case R.id.button2:
// 停止服务的方法
stopService(intent);
break;
default:
break;
}
}
}
Service.java
package com.ccav;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class Service extends android.app.Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Log.i("Fover", "Service onCreate");
super.onCreate();
}
@Override
public void onDestroy() {
Log.i("Fover", "Service onDestroy");
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
Log.i("Fover", "Service onStart");
super.onStart(intent, startId);
}
}
运行结果:
主界面:
后台:
查看调试信息: