Service的使用
核心代码:
在Manifest.xml中注册组件:
<service android:name="mars.service1.FirstService"></service>
组件:
public class FirstService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
System.out.println("Service onBind");
return null;
}
//当创建一个Servcie对象之后,会首先调用这个函数
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
System.out.println("Service onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stubo
System.out.println("Service onDestory");
super.onDestroy();
}
}
组件调用:
Intent intent = new Intent();
intent.setClass(TestActivity.this, FirstService.class);
startService(intent);
stopService(intent);
控件图例:
具体应用:
组件:
package mars.service1;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class FirstService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
System.out.println("Service onBind");
return null;
}
//当创建一个Servcie对象之后,会首先调用这个函数
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
System.out.println("Service onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
System.out.println("flags--->" + flags);
System.out.println("startId--->" + startId);
System.out.println("Service onStartCommand");
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stubo
System.out.println("Service onDestory");
super.onDestroy();
}
}
组件调用:
package mars.service1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class TestActivity extends Activity {
/** Called when the activity is first created. */
private Button startServiceButton = null;
private Button stopServiceButton = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startServiceButton = (Button) findViewById(R.id.startService);
startServiceButton.setOnClickListener(new StartServiceListener());
stopServiceButton = (Button) findViewById(R.id.stopService);
stopServiceButton.setOnClickListener(new StopServiceListener());
System.out.println("Activity onCreate");
}
class StartServiceListener implements OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(TestActivity.this, FirstService.class);
startService(intent);
}
}
class StopServiceListener implements OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(TestActivity.this, FirstService.class);
stopService(intent);
}
}
}