service(服务),后台运行,无界面,只有逻辑代码。
用处非常大,可以执行后台的一些数据操作,比如:更新、读取消息、或者最新动态等等。
要实现service肯定得有一个class,有2种方法创建本地服务,一种就是startService另外一种就是bindService。这两种的区别就是前者不能与Activity通信,而后者可以;这样当然是选择bindService啦。
startService:
它的生命周期是:onCreate()->onStartCommand()->onDestroy()
bindService:
生命周期:onCreate()->onBind()->onUnbind()->onDestroy()
startService的启动与停止方法就是 :startService、stopService;
bindService的启动与停止方法是 :bindService(intent,conn, Service.BIND_AUTO_CREATE); unbindService(conn);//解除
其中conn是ServiceConnection对象,并且要实现对象中的onServiceConnected、onServiceDisconnected两种方法,其中onServiceConnected可获得服务内置的业务对象数据。
以下是Activity.class类的源代码:
public class MainActivity extends AppCompatActivity { private static final String TAG = "SERVICELOG"; ServiceOne.newBinder binder;//服务类的newBinder对象,用于处理业务 //实现ServiceConnection对象中的onServiceConnected、onServiceDisconnected两种方法 private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i(TAG,"onServiceConnected"); binder = (ServiceOne.newBinder)service;//获得业务对象 } @Override public void onServiceDisconnected(ComponentName name) { Log.i(TAG,"onServiceDisconnected"); } };
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); init(this); } public void init(Context mContext){ final Intent intent = new Intent(); intent.setAction("com.test.servicetest.TEST_SERVICE"); Button start,stop; start = (Button)findViewById(R.id.start); stop = (Button)findViewById(R.id.stop); start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //startService(intent); bindService(intent,conn, Service.BIND_AUTO_CREATE);//绑定服务 //实例化一个时钟 Timer timer = new Timer(); //每10秒从binder对象读取数据一次 timer.schedule(new TimerTask() { @Override public void run() { Log.i(TAG, binder.getCon() + ""); } },5000,10000); } }); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // stopService(intent); unbindService(conn); Log.i("TAG","stop"); } }); }
//服务类ServiceOne.class源代码
package com.test.servicetest; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Timer; import java.util.TimerTask; /** * Created by Alan on 2016/05/24 0024. */ public class ServiceOne extends Service { private static final String TAG = "Service"; private boolean quit = false; public void onCreate() { super.onCreate(); Log.i(TAG, "OnCreate"); new Thread(new Runnable() { @Override public void run() { while (!quit){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } count++; Log.i(TAG,""+count); } } }).start(); } public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "onStartCommand"); Timer timer = new Timer(); timer.schedule(new getMsg(getApplicationContext(), new getMsg.Callback() { @Override public void onResquest(String res) { Log.i(TAG, res); } }), 5000, 10000); return START_STICKY; } public void onDestroy() { super.onDestroy(); this.quit = true; Log.i(TAG, "onDestroy"); } @Nullable @Override public IBinder onBind(Intent intent) { Log.i(TAG, "onBind"); return new newBinder(); } public boolean onUnBind(Intent intent) { Log.i(TAG, "onUnBind"); return true; } private int count = 0; //业务处理对象 public class newBinder extends Binder{ public int getCon(){ return count++; } public String getString(){return count+"";} } } class getMsg extends TimerTask{ private Context mContext; private Callback callback; public getMsg(Context ctx,Callback cb){ mContext = ctx; callback = cb; } interface Callback{ void onResquest(String res); } @Override public void run() { try { URL url = new URL("http://192.168.1.205/1.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStreamReader isr = new InputStreamReader(conn.getInputStream()); BufferedReader reader = new BufferedReader(isr); String str,str2 = ""; while ((str = reader.readLine()) != null){ str2 += str+"\t\n"; } isr.close(); reader.close(); conn.disconnect(); Log.i("RUN", str2); //回调数据 callback.onResquest(str2); } catch (Exception e) { e.printStackTrace(); } } }
源代码下载链接:http://pan.baidu.com/s/1nuFoXcd 密码:0k2j