在一个应用程序中,我们除了想要使MainActivity中的数据可以传到service中外,我们还可能需要监测service内部的数据的变化。那么我们就可以通过接口回调的方法来达到这个目的。我们先来看一下这个程序的框架,也就是framework.接下来我们来看一下MainActivity中的具体的内容。MainActivity程序中的内容如下:package com.example.myapplication; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /*主线程的UI不允许被其它的线程直接修改,可以通过handle来进行修改。注意这里还需要实现相关的接口ServiceConnection,bindService(new Intent(MainActivity.this, MyService.class), MainActivity.this, BIND_AUTO_CREATE);这是要注意的。还需要注意的一点是,如果我们需要改变主线程中UI中的内容,那么我们可以通过handler来做,否则很可能就会出现错误。*/public class MainActivity extends AppCompatActivity implements ServiceConnection { private TextView tv; private EditText et; private Button btn1; private Button btn2; private Button btn3; private Button btn4; private MyService.MyBinder binder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); setListener(); 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(); } }); } public void setListener() { btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyService.class); intent.putExtra("data", et.getText().toString()); startService(intent); } }); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopService(new Intent(MainActivity.this, MyService.class)); } }); btn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bindService(new Intent(MainActivity.this, MyService.class), MainActivity.this, BIND_AUTO_CREATE); } }); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { unbindService(MainActivity.this); } }); } public void init() { tv = (TextView) findViewById(R.id.tv); et = (EditText) findViewById(R.id.et); btn1 = (Button) findViewById(R.id.btn); btn2 = (Button) findViewById(R.id.btn2); btn3 = (Button) findViewById(R.id.btn3); btn4 = (Button) findViewById(R.id.btn4); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onServiceConnected(ComponentName name, IBinder service) { binder = (MyService.MyBinder) service; binder.setStr(et.getText().toString()); MyService myService = (MyService) binder.getService(); /*注意这里是setCallBack,而不是getCallBack*/ myService.setCallBack(new CallBack() { @Override public void onChangeData(String string) { Message message=new Message(); Bundle bundle = new Bundle(); bundle.putString("data", string); message.setData(bundle); handler.sendMessage(message); } }); } @Override public void onServiceDisconnected(ComponentName name) { } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { String str = msg.getData().getString("data"); tv.setText(str); } }; }接下来我们来看一个MyService中的内容:package com.example.myapplication; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; public class MyService extends Service { private CallBack callBack=null; boolean isRunning=false; private String str = "默认信息"; public MyService() { } public void setCallBack(CallBack callBack) { this.callBack = callBack; } public CallBack getCallBack() { return callBack; } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. return new MyBinder(); // throw new UnsupportedOperationException("Not yet implemented"); } /*如果是通过startservice来进行启动的话,那么这个方法中的intent参数就可以和mainActivity进行数据的交互了 * */ @Override public int onStartCommand(Intent intent, int flags, int startId) { str = intent.getStringExtra("data"); return super.onStartCommand(intent, flags, startId); } /*注意这里的线程的应用写错了,判断条件应该是在run里面的,否则的话,就会出错。*/ @Override public void onCreate() { super.onCreate(); isRunning=true; new Thread() { int i=0; @Override public void run() { while (isRunning) { i++; String s=i+str; Log.v("str-->", i + str); if (callBack!=null) { callBack.onChangeData(s); } try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } @Override public void onDestroy() { super.onDestroy(); isRunning=false; } //自定义一个Binder类的对象 class MyBinder extends Binder{ public void setStr(String s){ str=s; } public Service getService(){ return MyService.this; } } }最后我们还需要定义好一个接口:package com.example.myapplication; /** * Created by 李果 on 2016/7/9. */ public interface CallBack { void onChangeData(String string); }最后我们来看一下这个应用程序的界面如下:
在一个应用程序,如何监测一个service内部的数据的变化
最新推荐文章于 2022-10-07 08:27:26 发布