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
- android activity与service之间的通信
- Activity与service 之间的通信
- Activity 与 Service 之间的通信
- activity 与 service 之间的通信
- activity 与 service 之间的通信
- activity 与 service 之间的通信
- activity 与 service 之间的通信
- Activity与Service之间通信
- Activity与Service之间通信
- Android组件---Service,AIDL,Service与Activity之间的通信
- Android中Activity与Service之间的通信
- Android Service与Activity之间通信的几种方式
- Android Service与Activity之间通信的几种方式
- Android Service与Activity之间通信的几种方式
- Android Service与Activity之间通信的几种方式
- Android Service与Activity之间通信的几种方式
- Android Service与Activity之间通信的几种方式
- Android Service与Activity之间通信的几种方式
- rg.hibernate.ObjectNotFoundException: No row with the given identifier exists
- aix下设置自动启动、关闭oracle
- Timer 计时器进入后台仍能继续运行
- android效果集合[链]
- DirectByteBuffer
- Activity与service 之间的通信
- C++入门系列 拷贝构造函数 拷贝赋值函数
- Android 工具类积累
- 深入理解按位异或运算符
- ids for this class must be manually assigned before calling save()
- extjs 文本框后加一个按钮或 文字
- C/C++---static函数,static成员函数,static变量,static成员变量 再来理一理
- 转自: http://blog.csdn.net/xiaxiaorui2003/article/details/3838631
- c 程序必须要从main函数开始执行么?