首页 > 代码库 > android service
android service
service开发的步骤:
1.继承Service类
2.在AndroidManifest.xml文件中的<application>节点里对服务进行配置:<service android:name=".SMSService" />
3.服务不能自己运行,需要通过调用Context.startService()或Context.bindService()方法启动服务
public class MainActivity extends Activity implements OnClickListener, ServiceConnection { private Button btnstartservice,btnstopservice,btnbindservice,btnunbindservice; private Intent intentservice; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intentservice=new Intent(this,MyService.class); btnstartservice=(Button) findViewById(R.id.btnstartservice); btnstopservice=(Button) findViewById(R.id.btnstopservice); btnbindservice=(Button) findViewById(R.id.btnbindservice); btnunbindservice=(Button) findViewById(R.id.btnunbindservice); btnstartservice.setOnClickListener(this); btnstopservice.setOnClickListener(this); btnbindservice.setOnClickListener(this); btnunbindservice.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnstartservice: startService(intentservice); break; case R.id.btnstopservice: stopService(intentservice); break; case R.id.btnbindservice: bindService(intentservice, this,Context.BIND_AUTO_CREATE); break; case R.id.btnunbindservice: unbindService(this); break; } } @Override public void onServiceConnected(ComponentName arg0, IBinder arg1) { System.out.println("onserviceconnected"); } @Override public void onServiceDisconnected(ComponentName arg0) { System.out.println("onservicedisconnected"); } }
public class MyService extends Service { /* * startservice退出是服务还在后台进行 * bindservice退出时服务停止 * bindservice作用是进行通信 * */ public IBinder onBind(Intent intent) { System.out.println("onBind..."); //return null; return echoserviceBind; } public class serviceBind extends Binder { } private serviceBind echoserviceBind=new serviceBind(); public void onCreate() { System.out.println("onCreate.."); super.onCreate(); } public void onDestroy() { System.out.println("onDestroy.."); super.onDestroy(); }}
android service
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。