Activity与service 之间的通信

来源:互联网 发布:http json 接口规范 编辑:程序博客网 时间:2024/04/29 14:50

三种方式

  • 通过Binder对象
在Activity中的代码

<pre name="code" class="html"><pre name="code" class="java">public class MainActivity extends Activity {private Mybinder mybinderService;        private ServiceConnection conn=new ServiceConnection() {//监视Service的对象/**一般是service所在进程被kill了,连接失去以后会执行此方法*/@Overridepublic void onServiceDisconnected(ComponentName name) {   Log.i("TAG", "onServiceDisconnected"+name);}/**当绑定OK会自动执行此方法*/@Overridepublic void onServiceConnected( ComponentName name, IBinder service) {mybinderService=(MyBinder)service;   Log.i("TAG", "onServiceConnected");}};<span style="font-family: 'Times New Roman'; font-size: 14px; line-height: 26px;"></span><pre name="code" class="html">        @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}/**绑定service*/public void onBindService(View v){                    Intent intent=new Intent(this,MyService.class);                    bindService(intent,conn,BIND_AUTO_CREATE);}/**解除绑定*/public void onUnBindService(View v){                   unbindService(conn);}//计算public void onServiceCall(View v){        if(mybinderService==null)        return;     int num=mybinderService.doComputer();    Toast.makeText(this,"num="+num, 1).show(); }@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}


Service中的代码

 public class MyService extends Service {public MyService() {}@Overridepublic void onCreate() {Log.i("TAG", "onCreate()");}@Overridepublic IBinder onBind(Intent intent) {Log.i("TAG", "onBind()");return new MyBinder();//官方提供}@Overridepublic boolean onUnbind(Intent intent) {Log.i("TAG", "onUnbind");return true;}class MyBinder extends Binder {public int doComputer() {return 100;}}}


通过Broacast(广播)的形式

Activity中的代码
public class MainActivity extends Activity {      private ProgressBar mProgressBar;      private Intent mIntent;      private MsgReceiver msgReceiver;              @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);                    //动态注册广播接收器          msgReceiver = new MsgReceiver();          IntentFilter intentFilter = new IntentFilter();          intentFilter.addAction("com.example.communication.RECEIVER");          registerReceiver(msgReceiver, intentFilter);                              mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);          Button mButton = (Button) findViewById(R.id.button1);          mButton.setOnClickListener(new OnClickListener() {                            @Override              public void onClick(View v) {                  //启动服务                  mIntent = new Intent("com.example.communication.MSG_ACTION");                  startService(mIntent);              }          });                }              @Override      protected void onDestroy() {          //停止服务          stopService(mIntent);          //注销广播          unregisterReceiver(msgReceiver);          super.onDestroy();      }          /**      * 广播接收器      * @author len      *      */      public class MsgReceiver extends BroadcastReceiver{            @Override          public void onReceive(Context context, Intent intent) {              //拿到进度,更新UI              int progress = intent.getIntExtra("progress", 0);              mProgressBar.setProgress(progress);          }                }    }  


Service中的代码
public class MsgService extends Service {      /**      * 进度条的最大值      */      public static final int MAX_PROGRESS = 100;      /**      * 进度条的进度值      */      private int progress = 0;            private Intent intent = new Intent("com.example.communication.RECEIVER");              /**      * 模拟下载任务,每秒钟更新一次      */      public void startDownLoad(){          new Thread(new Runnable() {                            @Override              public void run() {                  while(progress < MAX_PROGRESS){                      progress += 5;                                            //发送Action为com.example.communication.RECEIVER的广播                      intent.putExtra("progress", progress);                      sendBroadcast(intent);                                            try {                          Thread.sleep(1000);                      } catch (InterruptedException e) {                          e.printStackTrace();                      }                                        }              }          }).start();      }                @Override      public int onStartCommand(Intent intent, int flags, int startId) {          startDownLoad();          return super.onStartCommand(intent, flags, startId);      }            @Override      public IBinder onBind(Intent intent) {          return null;      }  






  • Handler进行发送消息
Activity中的代码
public class MainActivity extends Activity {static Handler hander;private TextView et;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);et=(TextView)findViewById(R.id.textView1);hander=new Handler(getMainLooper()){@Overridepublic void handleMessage(Message msg) {if(msg.what==1){et.setText(String.valueOf((Integer)msg.obj));}}   };}public void onclick(View v){Intent intent=new Intent(this,MyService.class);intent.putExtra("num", 7);startService(intent);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}
Service 中的代码

public class MyService extends IntentService {public MyService() {super("myservice01");}@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.throw new UnsupportedOperationException("Not yet implemented");}//ŽË·œ·šÔËÐÐÓÚ¹€×÷Ïß³Ì@Overrideprotected void onHandleIntent(Intent intent) {String tname=Thread.currentThread().getName();Log.i("TAG", "tname="+tname);int n=intent.getIntExtra("num", -1);if(n==-1){throw new RuntimeException("ÊýŸÝ²»ÕýÈ·");}int num=1;for(int i=n;i>0;i--){num*=i;}Log.i("TAG", n+"!="+num);Message msg=new Message();msg.obj=num;msg.what=1;MainActivity.hander.sendMessage(msg);}}


http://www.tuicool.com/articles/3AVrAz


http://blog.csdn.net/xiaanming/article/details/9750689

0 0
原创粉丝点击