创建两个java类,第一个为主类,MainActivity.java
package com.example.service;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button firstButton = null;
private Button secondButton = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
firstButton = (Button) findViewById(R.id.fristButton);
firstButton.setText("开始");
firstButton.setOnClickListener(new firstButtonListener());
secondButton = (Button) findViewById(R.id.secondButton);
secondButton.setText("结束");
secondButton.setOnClickListener(new secondButtonListener());
}
class firstButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(MainActivity.this, FirstService.class);
startService(intent);
}
}
class secondButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(MainActivity.this, FirstService.class);
stopService(intent);
}
}
}
第二个为继承了Service的java类:FristActivity.java
package com.example.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class FirstService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
System.out.println("Service onCreate");
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
System.out.println("Service onDestory");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("flags--->" + flags);
System.out.println("startId--->" + startId);
System.out.println("Service onStartCommand");
return START_NOT_STICKY;
}
}
第三步,在androidMainifest.xml里添加:
<service android:name=".FirstService"></service>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.layout01"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.layout01.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=".FirstService"></service> </application>
</manifest>