标签:
package com.example.yabushan.hello3; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder;
//服务类 public class MyService extends Service { public MyService() { } @Override public IBinder onBind(Intent intent) { System.out.println("服务绑定"); return new Binder(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { new Thread(){ @Override public void run() { super.run(); while (true){ System.out.println("服务启动"); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); return super.onStartCommand(intent, flags, startId); } }
package com.example.yabushan.hello3; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.View; public class MainActivity extends Activity implements View.OnClickListener, ServiceConnection { Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_layout); intent=new Intent(MainActivity.this,MyService.class); findViewById(R.id.startService).setOnClickListener(this); findViewById(R.id.stopService).setOnClickListener(this); findViewById(R.id.bindService).setOnClickListener(this); findViewById(R.id.unbindService).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.startService: startService(intent);break; case R.id.stopService: stopService(intent);break; case R.id.bindService://绑定服务需要实现下面的两个方法 bindService(intent,this, Context.BIND_AUTO_CREATE); case R.id.unbindService: unbindService(this); } } @Override public void onServiceConnected(ComponentName name, IBinder service) { System.out.println("服务绑定成功"); } @Override public void onServiceDisconnected(ComponentName name) { } }
标签:
原文地址:http://www.cnblogs.com/yabushan/p/4983594.html