1,service是用于后台运行的程序,service运行在主线程中,所以service中一般需要创建线程来处理事务,否则容易引起ANR。
2,service的启动过程是:onCreate-->onStartCommand
3,service销毁过程是:onDestroy
4,启动service时,需要在AndroidManifest.xml中添加服务名:
<!-- create service -->
<service android:name=".helloservice"></service>
创建service代码如下:
helloservice.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class helloservice extends Service {
String TAG = "SERVICE";
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.i(TAG, "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i(TAG, "onDestroy");
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
MainActivity.java
import java.security.PublicKey;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button but;
private Button butService;
private Button butServiceDestoryButton;
String TAG="SERVICE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
butService = (Button)this.findViewById(R.id.serviceCreate);
butServiceDestoryButton = (Button)this.findViewById(R.id.serviceDestory);
butService.setOnClickListener(this);
butServiceDestoryButton.setOnClickListener(this);
}
@Override
public void onClick(View src) {
// TODO Auto-generated method stub
switch(src.getId())
{
case R.id.serviceTest:
Log.i(TAG, "onClick: starting service");
startService(new Intent(MainActivity.this, helloservice.class)); //手动启动service
break;
case R.id.serviceDestory:
Log.i(TAG, "onClick: destory service");
stopService(new Intent(MainActivity.this, helloservice.class)); //手动销毁service
break;
default:
break;
}
}
}