实现步骤:
1、编写类继承 Service 或其子类
2、重写onStartCommand() onBind() onCreate() onDestroy() 方法
3、在mainfest 文件中声明服务 <service android:name = ".Service" /> (Service 替换为你的服务类名)
4、在程序中启动服务,关闭服务
mService.java
package com.lanbokaka;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class mService extends Service {
private static final String TAG = "mService";
@Override
public void onCreate() {
Log.i(TAG, "mService-->onCreate");
super.onCreate();
}
@Override
public void onDestroy() {
Log.i(TAG, "mService-->onDestroy");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "mService-->onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "mService-->onBind");
return null;
}
}
MainActivity.java
package com.lanbokaka;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mTextView;
private Button mButton1, mButton2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textView1);
mButton1 = (Button) findViewById(R.id.button1);
mButton2 = (Button) findViewById(R.id.button2);
/* 开始服务 */
mButton1.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, mService.class);
startService(intent);
mTextView.setText("服务启动");
}
});
/* 结束服务 */
mButton2.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, mService.class);
stopService(intent);
mTextView.setText("服务结束");
}
});
}
}
AndroidManifest.xml
<activity
android:name="com.lanbokaka.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".mService" >
</service>