Service学习之——第一篇
创建一个简单的Service
通过这一篇的学习,你应该知道怎么创建一个简单的Service,并学会了启动和停止它的一些方法。startService(Intent intent); stopService(Intent intent);
main.xml布局文件:
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/start"
android:text="开启服务"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/stop"
android:text="停止服务"
/>
</LinearLayout>
MyService类
packagecom.example.myservice;
importandroid.app.Service;
importandroid.content.Intent;
importandroid.os.IBinder;
importandroid.widget.Toast;
public classMyService extends Service{
public MyService() {
// TODOAuto-generated constructor stub
}
@Override
public IBinderonBind(Intent arg0) {
// TODOAuto-generated method stub
return null;
}
@Override
public intonStartCommand(Intent intent, int flags, int startId) {
// TODOAuto-generated method stub
//我们希望这个服务在被显示停止前一直运行,所以返回“粘性的”状态
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
// TODOAuto-generated method stub
super.onDestroy();
Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
}
}
MainActivity类
packagecom.example.myservice;
importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.view.Menu;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
public classMainActivity extends Activity {
private Button start;
private Button stop;
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button)findViewById(R.id.start);
stop = (Button)findViewById(R.id.stop);
start.setOnClickListener(newOnClickListener() {
@Override
public voidonClick(View v) {
//TODO Auto-generated method stub
Intentintent = new Intent(MainActivity.this,MyService.class);
startService(intent);
}
});
stop.setOnClickListener(newOnClickListener() {
@Override
public voidonClick(View v) {
//TODO Auto-generated method stub
stopService(newIntent(getBaseContext(),MyService.class));
}
});
}
@Override
public booleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu;this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main,menu);
return true;
}
}
在Manifest中配置Service
<service android:name="com.example.myservice.MyService"></service>