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的效果是一樣的
*
*/
TagView里啟動TagService並且把待會在TagService里面啟動的Activity用Pending將其封裝好並且傳給TagService:
- TagService.saveMessages(this, msgs, false, getPendingIntent());private PendingIntent getPendingIntent() {
- Intent callback = new Intent();
- callback.setClass(this, TagViewer.class);
- callback.setAction(Intent.ACTION_VIEW);
- callback.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
- callback.putExtra(EXTRA_KEEP_TITLE, true);
- return PendingIntent.getActivity(this, 0, callback, PendingIntent.FLAG_CANCEL_CURRENT);
- }
- public static void saveMessages(Context context, NdefMessage[] msgs, boolean starred,
- PendingIntent pending) {
- Intent intent = new Intent(context, TagService.class);
- intent.putExtra(TagService.EXTRA_SAVE_MSGS, msgs);
- intent.putExtra(TagService.EXTRA_STARRED, starred);
- intent.putExtra(TagService.EXTRA_PENDING_INTENT, pending);
- context.startService(intent);
- }
- @Override
- public void onHandleIntent(Intent intent) {
- if (intent.hasExtra(EXTRA_SAVE_MSGS)) {
- Parcelable[] msgs = intent.getParcelableArrayExtra(EXTRA_SAVE_MSGS);
- NdefMessage msg = (NdefMessage) msgs[0];
- ContentValues values = NdefMessages.toValues(this, msg, false, System.currentTimeMillis());
- Uri uri = getContentResolver().insert(NdefMessages.CONTENT_URI, values);
- if (intent.hasExtra(EXTRA_PENDING_INTENT)) {
- Intent result = new Intent();
- result.setData(uri);
- PendingIntent pending = (PendingIntent) intent.getParcelableExtra(EXTRA_PENDING_INTENT);
- try {
- pending.send(this, 0, result);
- } catch (CanceledException e) {
- if (DEBUG) Log.d(TAG, "Pending intent was canceled.");
- }
- }
- return;
- }
- .....
- }
通過pending.send(this, 0, result);啟動了對應的Activity.
這里也是PendingIntent的用法之一。
我不太明白這兩種啟動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
代碼:
01 |
public 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 |
} |
1 |
if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0 ) { |
2 |
... |
3 |
} |
要回答這個問題,我們分析下service.startActivity()做了什么,其實,service.startActivity調用的是ContextWrapper.startActivity(),因為service繼承自ContextWrapper
2. 代碼文件
frameworks\base\core\java\android\content\ContextWrapper.java
代碼:
1 |
public void startActivity(Intent intent, Bundle options) { |
2 |
mBase.startActivity(intent, options); |
3 |
} |
mBase.startActivity(intent, options);
那么這個mBase是什么呢?又是什么時候賦值的呢?其實mBase是在ContextWrapper的attachBaseContext的時候初始化的。如下:
1 |
protected void attachBaseContext(Context base) { |
2 |
if (mBase != null ) { |
3 |
throw new IllegalStateException( "Base context already set" ); |
4 |
} |
5 |
mBase = base; |
6 |
} |
是在service創建的時候,在ActivityThread里面調用,如下:
3. 代碼文件
frameworks\base\core\java\android\app\ActivityThread.java
代碼:
01 |
private 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 |
} |
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
代碼:
1 |
public void startActivity(Intent intent) { |
2 |
this .startActivity(intent, null ); |
3 |
} |
原來如此,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.
這種設計,我覺得還是比較合理的。
轉載請注明地址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類
- <span style="font-family:System;">package com.example.communication;
- import android.app.Service;
- import android.content.Intent;
- import android.os.Binder;
- import android.os.IBinder;
- public class MsgService extends Service {
- /**
- * 進度條的最大值
- */
- public static final int MAX_PROGRESS = 100;
- /**
- * 進度條的進度值
- */
- private int progress = 0;
- /**
- * 增加get()方法,供Activity調用
- * @return 下載進度
- */
- public int getProgress() {
- return progress;
- }
- /**
- * 模擬下載任務,每秒鍾更新一次
- */
- public void startDownLoad(){
- new Thread(new Runnable() {
- @Override
- public void run() {
- while(progress < MAX_PROGRESS){
- progress += 5;
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }).start();
- }
- /**
- * 返回一個Binder對象
- */
- @Override
- public IBinder onBind(Intent intent) {
- return new MsgBinder();
- }
- public class MsgBinder extends Binder{
- /**
- * 獲取當前Service的實例
- * @return
- */
- public MsgService getService(){
- return MsgService.this;
- }
- }
- }</span>
- Intent intent = new Intent("com.example.communication.MSG_ACTION");
- bindService(intent, conn, Context.BIND_AUTO_CREATE);
通過上面的代碼我們就在Activity綁定了一個Service,上面需要一個ServiceConnection對象,它是一個接口,我們這里使用了匿名內部類
- <span style="font-family:System;"> ServiceConnection conn = new ServiceConnection() {
- @Override
- public void onServiceDisconnected(ComponentName name) {
- }
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- //返回一個MsgService對象
- msgService = ((MsgService.MsgBinder)service).getService();
- }
- };</span>
在onServiceConnected(ComponentName name, IBinder service) 回調方法中,返回了一個MsgService中的Binder對象,我們可以通過getService()方法來得到一個MsgService對象,然后可以調用MsgService中的一些方法,Activity的代碼如下
- <span style="font-family:System;">package com.example.communication;
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.content.ServiceConnection;
- import android.os.Bundle;
- import android.os.IBinder;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ProgressBar;
- public class MainActivity extends Activity {
- private MsgService msgService;
- private int progress = 0;
- private ProgressBar mProgressBar;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //綁定Service
- Intent intent = new Intent("com.example.communication.MSG_ACTION");
- bindService(intent, conn, Context.BIND_AUTO_CREATE);
- mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
- Button mButton = (Button) findViewById(R.id.button1);
- mButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- //開始下載
- msgService.startDownLoad();
- //監聽進度
- listenProgress();
- }
- });
- }
- /**
- * 監聽進度,每秒鍾獲取調用MsgService的getProgress()方法來獲取進度,更新UI
- */
- public void listenProgress(){
- new Thread(new Runnable() {
- @Override
- public void run() {
- while(progress < MsgService.MAX_PROGRESS){
- progress = msgService.getProgress();
- mProgressBar.setProgress(progress);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }).start();
- }
- ServiceConnection conn = new ServiceConnection() {
- @Override
- public void onServiceDisconnected(ComponentName name) {
- }
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- //返回一個MsgService對象
- msgService = ((MsgService.MsgBinder)service).getService();
- }
- };
- @Override
- protected void onDestroy() {
- unbindService(conn);
- super.onDestroy();
- }
- }</span><span style="font-family: simsun;">
- </span>
上面的代碼就完成了在Service更新UI的操作,可是你發現了沒有,我們每次都要主動調用getProgress()來獲取進度值,然后隔一秒在調用一次getProgress()方法,你會不會覺得很被動呢?可不可以有一種方法當Service中進度發生變化主動通知Activity,答案是肯定的,我們可以利用回調接口實現Service的主動通知,不理解回調方法的可以看看http://blog.csdn.net/xiaanming/article/details/8703708
新建一個回調接口
- public interface OnProgressListener {
- void onProgress(int progress);
- }
- <span style="font-family:System;">package com.example.communication;
- import android.app.Service;
- import android.content.Intent;
- import android.os.Binder;
- import android.os.IBinder;
- public class MsgService extends Service {
- /**
- * 進度條的最大值
- */
- public static final int MAX_PROGRESS = 100;
- /**
- * 進度條的進度值
- */
- private int progress = 0;
- /**
- * 更新進度的回調接口
- */
- private OnProgressListener onProgressListener;
- /**
- * 注冊回調接口的方法,供外部調用
- * @param onProgressListener
- */
- public void setOnProgressListener(OnProgressListener onProgressListener) {
- this.onProgressListener = onProgressListener;
- }
- /**
- * 增加get()方法,供Activity調用
- * @return 下載進度
- */
- public int getProgress() {
- return progress;
- }
- /**
- * 模擬下載任務,每秒鍾更新一次
- */
- public void startDownLoad(){
- new Thread(new Runnable() {
- @Override
- public void run() {
- while(progress < MAX_PROGRESS){
- progress += 5;
- //進度發生變化通知調用方
- if(onProgressListener != null){
- onProgressListener.onProgress(progress);
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }).start();
- }
- /**
- * 返回一個Binder對象
- */
- @Override
- public IBinder onBind(Intent intent) {
- return new MsgBinder();
- }
- public class MsgBinder extends Binder{
- /**
- * 獲取當前Service的實例
- * @return
- */
- public MsgService getService(){
- return MsgService.this;
- }
- }
- }</span>
- <span style="font-family:System;">package com.example.communication;
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.content.ServiceConnection;
- import android.os.Bundle;
- import android.os.IBinder;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ProgressBar;
- public class MainActivity extends Activity {
- private MsgService msgService;
- private ProgressBar mProgressBar;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //綁定Service
- Intent intent = new Intent("com.example.communication.MSG_ACTION");
- bindService(intent, conn, Context.BIND_AUTO_CREATE);
- mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
- Button mButton = (Button) findViewById(R.id.button1);
- mButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- //開始下載
- msgService.startDownLoad();
- }
- });
- }
- ServiceConnection conn = new ServiceConnection() {
- @Override
- public void onServiceDisconnected(ComponentName name) {
- }
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- //返回一個MsgService對象
- msgService = ((MsgService.MsgBinder)service).getService();
- //注冊回調接口來接收下載進度的變化
- msgService.setOnProgressListener(new OnProgressListener() {
- @Override
- public void onProgress(int progress) {
- mProgressBar.setProgress(progress);
- }
- });
- }
- };
- @Override
- protected void onDestroy() {
- unbindService(conn);
- super.onDestroy();
- }
- }
- </span>
- 通過broadcast(廣播)的形式
當我們的進度發生變化的時候我們發送一條廣播,然后在Activity的注冊廣播接收器,接收到廣播之后更新ProgressBar,代碼如下
- package com.example.communication;
- <span style="font-family:System;">
- import android.app.Activity;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ProgressBar;
- 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);
- }
- }
- }
- </span>
- <span style="font-family:System;">package com.example.communication;
- import android.app.Service;
- import android.content.Intent;
- import android.os.IBinder;
- 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;
- }
- }</span>
- Activity調用bindService (Intent service, ServiceConnection conn, int flags)方法,得到Service對象的一個引用,這樣Activity可以直接調用到Service中的方法,如果要主動通知Activity,我們可以利用回調方法
- Service向Activity發送消息,可以使用廣播,當然Activity要注冊相應的接收器。比如Service要向多個Activity發送同樣的消息的話,用這種方法就更好