自定义service:
package com.example.services;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service{
public static String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
Log.w(TAG, "--myservice onbind--");
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w(TAG, "--myservice onStartCommand--");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
Log.w(TAG, "--myservice oncreate--");
super.onCreate();
}
@Override
public void onDestroy() {
Log.w(TAG, "-- myservice ondestroy--");
super.onDestroy();
}
}
启动service的activity:
package com.example.servicedemo;
import com.example.services.MyService;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;
public class MainActivity extends Activity {
public static String TAG = "MyService";
private Button startBtn;
private Button endBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
setListener();
}
private void initView(){
startBtn = (Button) findViewById(R.id.service_start_btn);
endBtn = (Button) findViewById(R.id.service_end_btn);
}
private void setListener(){
startBtn.setOnClickListener(startServiceListener);
endBtn.setOnClickListener(endServiceListener);
}
OnClickListener startServiceListener = new OnClickListener() {
@Override
public void onClick(View v) {
Log.w(TAG, "-- serviceStartBtn clicked-- ");
Intent intent = new Intent();
intent.setClass(MainActivity.this, MyService.class);
startService(intent);
}
};
OnClickListener endServiceListener = new OnClickListener() {
@Override
public void onClick(View v) {
Log.w(TAG, "-- serviceEndBtn clicked-- ");
Intent intent = new Intent(MainActivity.this,MyService.class);
stopService(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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
这里用intent启动service的方式会调用service里的onStartCommand方法。