Service是一种在后台运行,没有界面的组件,由其他组件调用开始。
工程图片
HelloServer
package com.server;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class HelloServer extends Service{
@Override
public IBinder onBind(Intent intent) {
// TODO 自动生成的方法存根
return null;
}
@Override
public void onCreate(){
super.onCreate();
}
@Override
public void onDestroy(){
super.onDestroy();
}
@Override
public void onStart(Intent intent,int startId){
super.onStart(intent, startId);
System.out.println("start service,and sleep 10 s");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
HelloIntentService
package com.server;
import android.app.IntentService;
import android.content.Intent;
public class HelloIntentService extends IntentService{
public HelloIntentService( ) {
super("HelloIntentService");
// TODO 自动生成的构造函数存根
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO 自动生成的方法存根
System.out.println("rest for 8 minite");
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
public void onDestroy(){
System.out.println("Exist over.........");
super.onDestroy();
}
}
MainActivity
package com.server;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO 自动生成的方法存根
Intent intent = new Intent(MainActivity.this,
HelloIntentService.class);
startService(intent);
}
});
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO 自动生成的方法存根
Intent intent = new Intent(MainActivity.this,
HelloIntentService.class);
stopService(intent);
}
});
Button button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO 自动生成的方法存根
Intent intent = new Intent(MainActivity.this,
HelloServer.class);
startService(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}