Service 启动Activity

1, 在BroadcastReceiver中启动Activity的问题
  *
  * 如果在BroadcastReceiver的onReceive()方法中如下启动一个Activity
  * Intent intent=new Intent(context,AnotherActivity.class);
  * context.startActivity(intent);
  * 可捕获异常信息:
  * android.util.AndroidRuntimeException:
  * Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag.
  * Is this really what you want?
  * 它说明:在Activity的context(上下文环境)之外调用startActivity()方法时
  * 需要给Intent设置一个flag:FLAG_ACTIVITY_NEW_TASK
  *
  * 所以在BroadcastReceiver的onReceive()方法中启动Activity应写为:
  * Intent intent=new Intent(context,AnotherActivity.class);
  * intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  * context.startActivity(intent);
  *
  *
  * 之前描述了问题的现象和解决办法,现在试着解释一下原因:
  * 1 在普通情况下,必须要有前一个Activity的Context,才能启动后一个Activity
  * 2 但是在BroadcastReceiver里面是没有Activity的Context的
  * 3 对于startActivity()方法,源码中有这么一段描述:
  *   Note that if this method is being called from outside of an
  *   {@link android.app.Activity} Context, then the Intent must include
  *   the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag.  This is because,
  *   without being started from an existing Activity, there is no existing
  *   task in which to place the new activity and thus it needs to be placed
  *   in its own separate task.
  *   说白了就是如果不加这个flag就没有一个Task来存放新启动的Activity.
  *  
  * 4 其实该flag和设置Activity的LaunchMode为SingleTask的效果是一样的
  *
  */
 
2,但若看的源码够的话,还会发现有另外一种方法在Service里面启动Activity的另外一种方法:通过PendingIntent,下面就以Tag中TagView(Activity)和TagService为例子: 

TagView里启动TagService并且把待会在TagService里面启动的Activity用Pending将其封装好并且传给TagService: 
Java代码   收藏代码
  1. TagService.saveMessages(this, msgs, false, getPendingIntent());private PendingIntent getPendingIntent() {  
  2.         Intent callback = new Intent();  
  3.         callback.setClass(this, TagViewer.class);  
  4.         callback.setAction(Intent.ACTION_VIEW);  
  5.         callback.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);  
  6.         callback.putExtra(EXTRA_KEEP_TITLE, true);  
  7.   
  8.         return PendingIntent.getActivity(this, 0, callback, PendingIntent.FLAG_CANCEL_CURRENT);  
  9.     }  


Java代码   收藏代码
  1. public static void saveMessages(Context context, NdefMessage[] msgs, boolean starred,  
  2.             PendingIntent pending) {  
  3.         Intent intent = new Intent(context, TagService.class);  
  4.         intent.putExtra(TagService.EXTRA_SAVE_MSGS, msgs);  
  5.         intent.putExtra(TagService.EXTRA_STARRED, starred);  
  6.         intent.putExtra(TagService.EXTRA_PENDING_INTENT, pending);  
  7.         context.startService(intent);  
  8.     }  

Java代码   收藏代码
  1. @Override  
  2.     public void onHandleIntent(Intent intent) {  
  3.         if (intent.hasExtra(EXTRA_SAVE_MSGS)) {  
  4.             Parcelable[] msgs = intent.getParcelableArrayExtra(EXTRA_SAVE_MSGS);  
  5.             NdefMessage msg = (NdefMessage) msgs[0];  
  6.   
  7.             ContentValues values = NdefMessages.toValues(this, msg, false, System.currentTimeMillis());  
  8.             Uri uri = getContentResolver().insert(NdefMessages.CONTENT_URI, values);  
  9.             if (intent.hasExtra(EXTRA_PENDING_INTENT)) {  
  10.                 Intent result = new Intent();  
  11.                 result.setData(uri);  
  12.   
  13.                 PendingIntent pending = (PendingIntent) intent.getParcelableExtra(EXTRA_PENDING_INTENT);  
  14.                
  15.                 try {  
  16.                     pending.send(this, 0, result);  
  17.                 } catch (CanceledException e) {  
  18.                     if (DEBUG) Log.d(TAG, "Pending intent was canceled.");  
  19.                 }  
  20.             }  
  21.   
  22.             return;  
  23.         }  
  24. .....  
  25. }  


通过pending.send(this, 0, result);启动了对应的Activity. 

这里也是PendingIntent的用法之一。 
我不太明白这两种启动Activity的方法有什么不同之处虽然效果都是一样的,对开销会怎样,希望知道的朋友能和我分享。呵呵.. 
____________________________________________________
 
Android异常之Service启动Activity

在Activity中其中startActivity这个大家应该是非常熟悉的;那么从service里面调用startActivity话,会怎么样呢?
会出现下面的异常:
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

也就是在service里面启动Activity的话,必须添加FLAG_ACTIVITY_NEW_TASK flag。
那么下面的话,我们将从下面几个方面分析这个问题。
1.    这个异常怎么产生的?
2.    解决这个异常后会出现问题?
3.    为什么Activity.startActivity()不会出现这个问题?
4.    Android 为什么要这么设计?
下面,一一分析

一.    Context的继承关系图
首先来看一张图, 这张图表示了Context里面的基本继承关系。
 
1.    最上面的是Context.java,它其实是一个抽象类,它有两个重要的子类ContextImpl和ContextWrapper
2.    ContextImpl,是Context功能实现的主要类,
3.    ContextWrapper,顾名思义,它只是一个包装而已。主要功能实现都是通过调用ContextImpl去实现的。
4.    ContextThemeWrapper,包括一些主题的包装,由于Service没有主题,所以直接继承ContextWrapper;但是Activity就需要继承ContextThemeWrapper



二.    异常如何产生
1.    找到报错的代码
文件:
frameworks\base\core\java\android\app\ContextImpl.java
代码:
01public void startActivity(Intent intent, Bundle options) {
02        warnIfCallingFromSystemProcess();
03        if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
04            throw new AndroidRuntimeException(
05                    "Calling startActivity() from outside of an Activity "
06                    + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
07                    + " Is this really what you want?");
08        }
09        mMainThread.getInstrumentation().execStartActivity(
10            getOuterContext(), mMainThread.getApplicationThread(), null,
11            (Activity)null, intent, -1, options);
12}
在下面的if条件判断,如果不包含FLAG_ACTIVITY_NEW_TASK就会报这个错误
1if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2    ...
3}   
那么service.startActivity(Intent intent)怎么会调用这里来的呢?
要回答这个问题,我们分析下service.startActivity()做了什么,其实,service.startActivity调用的是ContextWrapper.startActivity(),因为service继承自ContextWrapper
2.  代码文件
frameworks\base\core\java\android\content\ContextWrapper.java
代码:
1public void startActivity(Intent intent, Bundle options) {
2    mBase.startActivity(intent, options);
3}
ContextWrapper.startActivity的话,是直接调用的
mBase.startActivity(intent, options);
那么这个mBase是什么呢?又是什么时候赋值的呢?其实mBase是在ContextWrapper的attachBaseContext的时候初始化的。如下:
1protected void attachBaseContext(Context base) {
2        if (mBase != null) {
3            throw new IllegalStateException("Base context already set");
4        }
5        mBase = base;
6    }
那又是谁调用attachBaseContext的呢?
是在service创建的时候,在ActivityThread里面调用,如下:

3. 代码文件
frameworks\base\core\java\android\app\ActivityThread.java
代码:
01private void handleCreateService(CreateServiceData data) {
02        LoadedApk packageInfo = getPackageInfoNoCheck(
03                data.info.applicationInfo, data.compatInfo);
04        Service service = null;
05        try {
06            java.lang.ClassLoader cl = packageInfo.getClassLoader();
07            service = (Service) cl.loadClass(data.info.name).newInstance();
08        } catch (Exception e) {
09            ....
10        }
11        try {
12            if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
13            ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
14            context.setOuterContext(service);
15            Application app = packageInfo.makeApplication(false, mInstrumentation);
16            service.attach(context, this, data.info.name, data.token, app,
17                    ActivityManagerNative.getDefault());
18            service.onCreate();
19            mServices.put(data.token, service);
20            ....
21        } catch (Exception e) {
22            ...
23        }
24    }
抽出主要代码分析ActivityThread. handleCreateService()方法里面主要做这几件事
3.1 通过pms找到要启动的Service配置信息,然后通过反射生成Service对象
3.2 创建ContextImpl对象,然后调用service.attach方法设置到ContextWrapper.java的mBaseContext变量里面。

那现在就明白了,service.startActivity()->ContextWrapper.startActivity()->ContextImpl.startActivity()
然后再ContextImpl.startActivity里面会检查Intent的参数是否包含FLAG_ACTIVITY_NEW_TASK,从而出现这个异常。

三.    解决这个异常后会出现问题?
有些同学就会说了,在Service里面启动Activity必须要有FLAG_ACTIVITY_NEW_TASK参数,那么我们添加上不就可以了?如下:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
那么这样会带来什么问题呢?
这样带来的问题就是在最近任务列表里面会出现两个相同的应用程序,比如你是在电话本里面启动的,那么最近任务列表就会出现两个电话本;因为有两个Task嘛!
那怎么解决呢?其实也非常好解决,只要在新的Task里面的Activity里面配置android:excludeFromRecents="true"就可以了。表示这个Activity不会显示在最近列表里面。

四.    Activity.startActivity()为什么不出现这个异常呢?
要回答这个问题,需要看下Activity.startActivity()调用到哪里去了
代码文件:
frameworks\base\core\java\android\app\Activity.java
代码:
1public void startActivity(Intent intent) {
2   this.startActivity(intent, null);
3}
接下来会调用startActivityForResult()->然后一路调用到Ams去启动Activity;
原来如此,Activity重写了startActivity()方法...


五.    Android 为什么要这么设计?
那现在来回答这个问题,为什么Android在Service 里面启动Activity要强制规定使用参数FLAG_ACTIVITY_NEW_TASK呢?
我们可以来做这样一个假设,我们有这样一个需求:
我们在电话本里面启动一个Service,然后它执行5分钟后,启动一个Activity
那么很有可能用户在5分钟后已经不在电话本程序里面操作了,有可能去上网,打开浏览器程序了。
5分钟后,此时当前的Task是浏览器的task,那么弹出Activity,如果这个Activity在当前Task的话,也就是浏览器的Task;那么用户就会觉得莫名其妙;因为弹出的Activity和浏览器在一个Task,本来这个Activity应该属于电话本的。

所以,对于Service而言,干脆强制定义启动的Activity要创建一个新的Task.
这种设计,我觉得还是比较合理的。

 
————————————----------------------------------------------------------

Android Service与Activity之间通信的几种方式

分类: Android 高手进阶

转载请注明地址http://blog.csdn.net/xiaanming/article/details/9750689

在Android中,Activity主要负责前台页面的展示,Service主要负责需要长期运行的任务,所以在我们实际开发中,就会常常遇到Activity与Service之间的通信,我们一般在Activity中启动后台Service,通过Intent来启动,Intent中我们可以传递数据给Service,而当我们Service执行某些操作之后想要更新UI线程,我们应该怎么做呢?接下来我就介绍两种方式来实现Service与Activity之间的通信问题

 

  • 通过Binder对象

 

当Activity通过调用bindService(Intent service, ServiceConnection conn,int flags),我们可以得到一个Service的一个对象实例,然后我们就可以访问Service中的方法,我们还是通过一个例子来理解一下吧,一个模拟下载的小例子,带大家理解一下通过Binder通信的方式

首先我们新建一个工程Communication,然后新建一个Service类

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:System;">package com.example.communication;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.Binder;  
  6. import android.os.IBinder;  
  7.   
  8. public class MsgService extends Service {  
  9.     /** 
  10.      * 进度条的最大值 
  11.      */  
  12.     public static final int MAX_PROGRESS = 100;  
  13.     /** 
  14.      * 进度条的进度值 
  15.      */  
  16.     private int progress = 0;  
  17.   
  18.     /** 
  19.      * 增加get()方法,供Activity调用 
  20.      * @return 下载进度 
  21.      */  
  22.     public int getProgress() {  
  23.         return progress;  
  24.     }  
  25.   
  26.     /** 
  27.      * 模拟下载任务,每秒钟更新一次 
  28.      */  
  29.     public void startDownLoad(){  
  30.         new Thread(new Runnable() {  
  31.               
  32.             @Override  
  33.             public void run() {  
  34.                 while(progress < MAX_PROGRESS){  
  35.                     progress += 5;  
  36.                     try {  
  37.                         Thread.sleep(1000);  
  38.                     } catch (InterruptedException e) {  
  39.                         e.printStackTrace();  
  40.                     }  
  41.                       
  42.                 }  
  43.             }  
  44.         }).start();  
  45.     }  
  46.   
  47.   
  48.     /** 
  49.      * 返回一个Binder对象 
  50.      */  
  51.     @Override  
  52.     public IBinder onBind(Intent intent) {  
  53.         return new MsgBinder();  
  54.     }  
  55.       
  56.     public class MsgBinder extends Binder{  
  57.         /** 
  58.          * 获取当前Service的实例 
  59.          * @return 
  60.          */  
  61.         public MsgService getService(){  
  62.             return MsgService.this;  
  63.         }  
  64.     }  
  65.   
  66. }</span>  
上面的代码比较简单,注释也比较详细,最基本的Service的应用了,相信你看得懂的,我们调用startDownLoad()方法来模拟下载任务,然后每秒更新一次进度,但这是在后台进行中,我们是看不到的,所以有时候我们需要他能在前台显示下载的进度问题,所以我们接下来就用到Activity了

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. Intent intent = new Intent("com.example.communication.MSG_ACTION");    
  2. bindService(intent, conn, Context.BIND_AUTO_CREATE);  

 

通过上面的代码我们就在Activity绑定了一个Service,上面需要一个ServiceConnection对象,它是一个接口,我们这里使用了匿名内部类

 

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:System;">  ServiceConnection conn = new ServiceConnection() {  
  2.           
  3.         @Override  
  4.         public void onServiceDisconnected(ComponentName name) {  
  5.               
  6.         }  
  7.           
  8.         @Override  
  9.         public void onServiceConnected(ComponentName name, IBinder service) {  
  10.             //返回一个MsgService对象  
  11.             msgService = ((MsgService.MsgBinder)service).getService();  
  12.               
  13.         }  
  14.     };</span>  

在onServiceConnected(ComponentName name, IBinder service) 回调方法中,返回了一个MsgService中的Binder对象,我们可以通过getService()方法来得到一个MsgService对象,然后可以调用MsgService中的一些方法,Activity的代码如下

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:System;">package com.example.communication;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.ComponentName;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.content.ServiceConnection;  
  8. import android.os.Bundle;  
  9. import android.os.IBinder;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.widget.Button;  
  13. import android.widget.ProgressBar;  
  14.   
  15. public class MainActivity extends Activity {  
  16.     private MsgService msgService;  
  17.     private int progress = 0;  
  18.     private ProgressBar mProgressBar;  
  19.       
  20.   
  21.     @Override  
  22.     protected void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.activity_main);  
  25.           
  26.           
  27.         //绑定Service  
  28.         Intent intent = new Intent("com.example.communication.MSG_ACTION");  
  29.         bindService(intent, conn, Context.BIND_AUTO_CREATE);  
  30.           
  31.           
  32.         mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);  
  33.         Button mButton = (Button) findViewById(R.id.button1);  
  34.         mButton.setOnClickListener(new OnClickListener() {  
  35.               
  36.             @Override  
  37.             public void onClick(View v) {  
  38.                 //开始下载  
  39.                 msgService.startDownLoad();  
  40.                 //监听进度  
  41.                 listenProgress();  
  42.             }  
  43.         });  
  44.           
  45.     }  
  46.       
  47.   
  48.     /** 
  49.      * 监听进度,每秒钟获取调用MsgService的getProgress()方法来获取进度,更新UI 
  50.      */  
  51.     public void listenProgress(){  
  52.         new Thread(new Runnable() {  
  53.               
  54.             @Override  
  55.             public void run() {  
  56.                 while(progress < MsgService.MAX_PROGRESS){  
  57.                     progress = msgService.getProgress();  
  58.                     mProgressBar.setProgress(progress);  
  59.                     try {  
  60.                         Thread.sleep(1000);  
  61.                     } catch (InterruptedException e) {  
  62.                         e.printStackTrace();  
  63.                     }  
  64.                 }  
  65.                   
  66.             }  
  67.         }).start();  
  68.     }  
  69.       
  70.     ServiceConnection conn = new ServiceConnection() {  
  71.         @Override  
  72.         public void onServiceDisconnected(ComponentName name) {  
  73.               
  74.         }  
  75.           
  76.         @Override  
  77.         public void onServiceConnected(ComponentName name, IBinder service) {  
  78.             //返回一个MsgService对象  
  79.             msgService = ((MsgService.MsgBinder)service).getService();  
  80.               
  81.         }  
  82.     };  
  83.   
  84.     @Override  
  85.     protected void onDestroy() {  
  86.         unbindService(conn);  
  87.         super.onDestroy();  
  88.     }  
  89.   
  90.   
  91. }</span><span style="font-family: simsun;">  
  92. </span>  
其实上面的代码我还是有点疑问,就是监听进度变化的那个方法我是直接在线程中更新UI的,不是说不能在其他线程更新UI操作吗,可能是ProgressBar比较特殊吧,我也没去研究它的源码,知道的朋友可以告诉我一声,谢谢!

 

上面的代码就完成了在Service更新UI的操作,可是你发现了没有,我们每次都要主动调用getProgress()来获取进度值,然后隔一秒在调用一次getProgress()方法,你会不会觉得很被动呢?可不可以有一种方法当Service中进度发生变化主动通知Activity,答案是肯定的,我们可以利用回调接口实现Service的主动通知,不理解回调方法的可以看看http://blog.csdn.net/xiaanming/article/details/8703708

新建一个回调接口

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. public interface OnProgressListener {  
  2.     void onProgress(int progress);  
  3. }  
MsgService的代码有一些小小的改变,为了方便大家看懂,我还是将所有代码贴出来

 

 

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:System;">package com.example.communication;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.Binder;  
  6. import android.os.IBinder;  
  7.   
  8. public class MsgService extends Service {  
  9.     /** 
  10.      * 进度条的最大值 
  11.      */  
  12.     public static final int MAX_PROGRESS = 100;  
  13.     /** 
  14.      * 进度条的进度值 
  15.      */  
  16.     private int progress = 0;  
  17.       
  18.     /** 
  19.      * 更新进度的回调接口 
  20.      */  
  21.     private OnProgressListener onProgressListener;  
  22.       
  23.       
  24.     /** 
  25.      * 注册回调接口的方法,供外部调用 
  26.      * @param onProgressListener 
  27.      */  
  28.     public void setOnProgressListener(OnProgressListener onProgressListener) {  
  29.         this.onProgressListener = onProgressListener;  
  30.     }  
  31.   
  32.     /** 
  33.      * 增加get()方法,供Activity调用 
  34.      * @return 下载进度 
  35.      */  
  36.     public int getProgress() {  
  37.         return progress;  
  38.     }  
  39.   
  40.     /** 
  41.      * 模拟下载任务,每秒钟更新一次 
  42.      */  
  43.     public void startDownLoad(){  
  44.         new Thread(new Runnable() {  
  45.               
  46.             @Override  
  47.             public void run() {  
  48.                 while(progress < MAX_PROGRESS){  
  49.                     progress += 5;  
  50.                       
  51.                     //进度发生变化通知调用方  
  52.                     if(onProgressListener != null){  
  53.                         onProgressListener.onProgress(progress);  
  54.                     }  
  55.                       
  56.                     try {  
  57.                         Thread.sleep(1000);  
  58.                     } catch (InterruptedException e) {  
  59.                         e.printStackTrace();  
  60.                     }  
  61.                       
  62.                 }  
  63.             }  
  64.         }).start();  
  65.     }  
  66.   
  67.   
  68.     /** 
  69.      * 返回一个Binder对象 
  70.      */  
  71.     @Override  
  72.     public IBinder onBind(Intent intent) {  
  73.         return new MsgBinder();  
  74.     }  
  75.       
  76.     public class MsgBinder extends Binder{  
  77.         /** 
  78.          * 获取当前Service的实例 
  79.          * @return 
  80.          */  
  81.         public MsgService getService(){  
  82.             return MsgService.this;  
  83.         }  
  84.     }  
  85.   
  86. }</span>  
Activity中的代码如下

 

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:System;">package com.example.communication;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.ComponentName;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.content.ServiceConnection;  
  8. import android.os.Bundle;  
  9. import android.os.IBinder;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.widget.Button;  
  13. import android.widget.ProgressBar;  
  14.   
  15. public class MainActivity extends Activity {  
  16.     private MsgService msgService;  
  17.     private ProgressBar mProgressBar;  
  18.       
  19.   
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.activity_main);  
  24.           
  25.           
  26.         //绑定Service  
  27.         Intent intent = new Intent("com.example.communication.MSG_ACTION");  
  28.         bindService(intent, conn, Context.BIND_AUTO_CREATE);  
  29.           
  30.           
  31.         mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);  
  32.         Button mButton = (Button) findViewById(R.id.button1);  
  33.         mButton.setOnClickListener(new OnClickListener() {  
  34.               
  35.             @Override  
  36.             public void onClick(View v) {  
  37.                 //开始下载  
  38.                 msgService.startDownLoad();  
  39.             }  
  40.         });  
  41.           
  42.     }  
  43.       
  44.   
  45.     ServiceConnection conn = new ServiceConnection() {  
  46.         @Override  
  47.         public void onServiceDisconnected(ComponentName name) {  
  48.               
  49.         }  
  50.           
  51.         @Override  
  52.         public void onServiceConnected(ComponentName name, IBinder service) {  
  53.             //返回一个MsgService对象  
  54.             msgService = ((MsgService.MsgBinder)service).getService();  
  55.               
  56.             //注册回调接口来接收下载进度的变化  
  57.             msgService.setOnProgressListener(new OnProgressListener() {  
  58.                   
  59.                 @Override  
  60.                 public void onProgress(int progress) {  
  61.                     mProgressBar.setProgress(progress);  
  62.                       
  63.                 }  
  64.             });  
  65.               
  66.         }  
  67.     };  
  68.   
  69.     @Override  
  70.     protected void onDestroy() {  
  71.         unbindService(conn);  
  72.         super.onDestroy();  
  73.     }  
  74.   
  75.   
  76. }  
  77. </span>  
用回调接口是不是更加的方便呢,当进度发生变化的时候Service主动通知Activity,Activity就可以更新UI操作了

 

 

当我们的进度发生变化的时候我们发送一条广播,然后在Activity的注册广播接收器,接收到广播之后更新ProgressBar,代码如下

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. package com.example.communication;  
  2. <span style="font-family:System;">  
  3. import android.app.Activity;  
  4. import android.content.BroadcastReceiver;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.content.IntentFilter;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.view.View.OnClickListener;  
  11. import android.widget.Button;  
  12. import android.widget.ProgressBar;  
  13.   
  14. public class MainActivity extends Activity {  
  15.     private ProgressBar mProgressBar;  
  16.     private Intent mIntent;  
  17.     private MsgReceiver msgReceiver;  
  18.       
  19.   
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.activity_main);  
  24.           
  25.         //动态注册广播接收器  
  26.         msgReceiver = new MsgReceiver();  
  27.         IntentFilter intentFilter = new IntentFilter();  
  28.         intentFilter.addAction("com.example.communication.RECEIVER");  
  29.         registerReceiver(msgReceiver, intentFilter);  
  30.           
  31.           
  32.         mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);  
  33.         Button mButton = (Button) findViewById(R.id.button1);  
  34.         mButton.setOnClickListener(new OnClickListener() {  
  35.               
  36.             @Override  
  37.             public void onClick(View v) {  
  38.                 //启动服务  
  39.                 mIntent = new Intent("com.example.communication.MSG_ACTION");  
  40.                 startService(mIntent);  
  41.             }  
  42.         });  
  43.           
  44.     }  
  45.   
  46.       
  47.     @Override  
  48.     protected void onDestroy() {  
  49.         //停止服务  
  50.         stopService(mIntent);  
  51.         //注销广播  
  52.         unregisterReceiver(msgReceiver);  
  53.         super.onDestroy();  
  54.     }  
  55.   
  56.   
  57.     /** 
  58.      * 广播接收器 
  59.      * @author len 
  60.      * 
  61.      */  
  62.     public class MsgReceiver extends BroadcastReceiver{  
  63.   
  64.         @Override  
  65.         public void onReceive(Context context, Intent intent) {  
  66.             //拿到进度,更新UI  
  67.             int progress = intent.getIntExtra("progress", 0);  
  68.             mProgressBar.setProgress(progress);  
  69.         }  
  70.           
  71.     }  
  72.   
  73. }  
  74. </span>  

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <span style="font-family:System;">package com.example.communication;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.IBinder;  
  6.   
  7. public class MsgService extends Service {  
  8.     /** 
  9.      * 进度条的最大值 
  10.      */  
  11.     public static final int MAX_PROGRESS = 100;  
  12.     /** 
  13.      * 进度条的进度值 
  14.      */  
  15.     private int progress = 0;  
  16.       
  17.     private Intent intent = new Intent("com.example.communication.RECEIVER");  
  18.       
  19.   
  20.     /** 
  21.      * 模拟下载任务,每秒钟更新一次 
  22.      */  
  23.     public void startDownLoad(){  
  24.         new Thread(new Runnable() {  
  25.               
  26.             @Override  
  27.             public void run() {  
  28.                 while(progress < MAX_PROGRESS){  
  29.                     progress += 5;  
  30.                       
  31.                     //发送Action为com.example.communication.RECEIVER的广播  
  32.                     intent.putExtra("progress", progress);  
  33.                     sendBroadcast(intent);  
  34.                       
  35.                     try {  
  36.                         Thread.sleep(1000);  
  37.                     } catch (InterruptedException e) {  
  38.                         e.printStackTrace();  
  39.                     }  
  40.                       
  41.                 }  
  42.             }  
  43.         }).start();  
  44.     }  
  45.   
  46.       
  47.   
  48.     @Override  
  49.     public int onStartCommand(Intent intent, int flags, int startId) {  
  50.         startDownLoad();  
  51.         return super.onStartCommand(intent, flags, startId);  
  52.     }  
  53.   
  54.   
  55.   
  56.     @Override  
  57.     public IBinder onBind(Intent intent) {  
  58.         return null;  
  59.     }  
  60.   
  61.   
  62. }</span>  
总结:

 

 

  1. Activity调用bindService (Intent service, ServiceConnection conn, int flags)方法,得到Service对象的一个引用,这样Activity可以直接调用到Service中的方法,如果要主动通知Activity,我们可以利用回调方法
  2.  Service向Activity发送消息,可以使用广播,当然Activity要注册相应的接收器。比如Service要向多个Activity发送同样的消息的话,用这种方法就更好

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值