Service 启动Activity

我想我们一般在Service里想启动Activity一定会这样写:

Java代码  

  1. Intent intentv = new Intent(Intent.ACTION_VIEW);
  2. intentv.setData(uri);
  3. intentv.putExtra("keepTitle", true);
  4. startActivity(intentv);

这样写就会报错的:

03-11 02:37:09.737: ERROR/AndroidRuntime(7881): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

提示要加上FLAG_ACTIVITY_NEW_TASK,所以加上 intentv.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);这一行就可以了。

但若看的源码够的话,还会发现有另外一种方法在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. return PendingIntent.getActivity(this, 0, callback, PendingIntent.FLAG_CANCEL_CURRENT);
  8. }

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. ContentValues values = NdefMessages.toValues(this, msg, false, System.currentTimeMillis());
  7. Uri uri = getContentResolver().insert(NdefMessages.CONTENT_URI, values);
  8. if (intent.hasExtra(EXTRA_PENDING_INTENT)) {
  9. Intent result = new Intent();
  10. result.setData(uri);
  11. PendingIntent pending = (PendingIntent) intent.getParcelableExtra(EXTRA_PENDING_INTENT);
  12. try {
  13. pending.send(this, 0, result);
  14. } catch (CanceledException e) {
  15. if (DEBUG) Log.d(TAG, "Pending intent was canceled.");
  16. }
  17. }
  18. return;
  19. }
  20. .....
  21. }

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

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

____________________________________________________

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

分类: Android 高手进阶2013-08-05 00:11 49344人阅读 评论(81) 收藏 举报

ServiceActivity通信

转载请注明地址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 plaincopy

  1. <span style="font-family:System;">package com.example.communication;
  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.Binder;
  5. import android.os.IBinder;
  6. public class MsgService extends Service {
  7. /**
  8. * 进度条的最大值
  9. */
  10. public static final int MAX_PROGRESS = 100;
  11. /**
  12. * 进度条的进度值
  13. */
  14. private int progress = 0;
  15. /**
  16. * 增加get()方法,供Activity调用
  17. * @return 下载进度
  18. */
  19. public int getProgress() {
  20. return progress;
  21. }
  22. /**
  23. * 模拟下载任务,每秒钟更新一次
  24. */
  25. public void startDownLoad(){
  26. new Thread(new Runnable() {
  27. @Override
  28. public void run() {
  29. while(progress < MAX_PROGRESS){
  30. progress += 5;
  31. try {
  32. Thread.sleep(1000);
  33. } catch (InterruptedException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }
  38. }).start();
  39. }
  40. /**
  41. * 返回一个Binder对象
  42. */
  43. @Override
  44. public IBinder onBind(Intent intent) {
  45. return new MsgBinder();
  46. }
  47. public class MsgBinder extends Binder{
  48. /**
  49. * 获取当前Service的实例
  50. * @return
  51. */
  52. public MsgService getService(){
  53. return MsgService.this;
  54. }
  55. }
  56. }</span>

上面的代码比较简单,注释也比较详细,最基本的Service的应用了,相信你看得懂的,我们调用startDownLoad()方法来模拟下载任务,然后每秒更新一次进度,但这是在后台进行中,我们是看不到的,所以有时候我们需要他能在前台显示下载的进度问题,所以我们接下来就用到Activity了

[java] view plaincopy

  1. Intent intent = new Intent("com.example.communication.MSG_ACTION");
  2. bindService(intent, conn, Context.BIND_AUTO_CREATE);

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

[java] view plaincopy

  1. <span style="font-family:System;">  ServiceConnection conn = new ServiceConnection() {
  2. @Override
  3. public void onServiceDisconnected(ComponentName name) {
  4. }
  5. @Override
  6. public void onServiceConnected(ComponentName name, IBinder service) {
  7. //返回一个MsgService对象
  8. msgService = ((MsgService.MsgBinder)service).getService();
  9. }
  10. };</span>

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

[java] view plaincopy

  1. <span style="font-family:System;">package com.example.communication;
  2. import android.app.Activity;
  3. import android.content.ComponentName;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.ServiceConnection;
  7. import android.os.Bundle;
  8. import android.os.IBinder;
  9. import android.view.View;
  10. import android.view.View.OnClickListener;
  11. import android.widget.Button;
  12. import android.widget.ProgressBar;
  13. public class MainActivity extends Activity {
  14. private MsgService msgService;
  15. private int progress = 0;
  16. private ProgressBar mProgressBar;
  17. @Override
  18. protected void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.activity_main);
  21. //绑定Service
  22. Intent intent = new Intent("com.example.communication.MSG_ACTION");
  23. bindService(intent, conn, Context.BIND_AUTO_CREATE);
  24. mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
  25. Button mButton = (Button) findViewById(R.id.button1);
  26. mButton.setOnClickListener(new OnClickListener() {
  27. @Override
  28. public void onClick(View v) {
  29. //开始下载
  30. msgService.startDownLoad();
  31. //监听进度
  32. listenProgress();
  33. }
  34. });
  35. }
  36. /**
  37. * 监听进度,每秒钟获取调用MsgService的getProgress()方法来获取进度,更新UI
  38. */
  39. public void listenProgress(){
  40. new Thread(new Runnable() {
  41. @Override
  42. public void run() {
  43. while(progress < MsgService.MAX_PROGRESS){
  44. progress = msgService.getProgress();
  45. mProgressBar.setProgress(progress);
  46. try {
  47. Thread.sleep(1000);
  48. } catch (InterruptedException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. }
  53. }).start();
  54. }
  55. ServiceConnection conn = new ServiceConnection() {
  56. @Override
  57. public void onServiceDisconnected(ComponentName name) {
  58. }
  59. @Override
  60. public void onServiceConnected(ComponentName name, IBinder service) {
  61. //返回一个MsgService对象
  62. msgService = ((MsgService.MsgBinder)service).getService();
  63. }
  64. };
  65. @Override
  66. protected void onDestroy() {
  67. unbindService(conn);
  68. super.onDestroy();
  69. }
  70. }</span><span style="font-family: simsun;">
  71. </span>

其实上面的代码我还是有点疑问,就是监听进度变化的那个方法我是直接在线程中更新UI的,不是说不能在其他线程更新UI操作吗,可能是ProgressBar比较特殊吧,我也没去研究它的源码,知道的朋友可以告诉我一声,谢谢!

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

新建一个回调接口

[java] view plaincopy

  1. public interface OnProgressListener {
  2. void onProgress(int progress);
  3. }

MsgService的代码有一些小小的改变,为了方便大家看懂,我还是将所有代码贴出来

[java] view plaincopy

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

Activity中的代码如下

[java] view plaincopy

  1. <span style="font-family:System;">package com.example.communication;
  2. import android.app.Activity;
  3. import android.content.ComponentName;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.ServiceConnection;
  7. import android.os.Bundle;
  8. import android.os.IBinder;
  9. import android.view.View;
  10. import android.view.View.OnClickListener;
  11. import android.widget.Button;
  12. import android.widget.ProgressBar;
  13. public class MainActivity extends Activity {
  14. private MsgService msgService;
  15. private ProgressBar mProgressBar;
  16. @Override
  17. protected void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_main);
  20. //绑定Service
  21. Intent intent = new Intent("com.example.communication.MSG_ACTION");
  22. bindService(intent, conn, Context.BIND_AUTO_CREATE);
  23. mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
  24. Button mButton = (Button) findViewById(R.id.button1);
  25. mButton.setOnClickListener(new OnClickListener() {
  26. @Override
  27. public void onClick(View v) {
  28. //开始下载
  29. msgService.startDownLoad();
  30. }
  31. });
  32. }
  33. ServiceConnection conn = new ServiceConnection() {
  34. @Override
  35. public void onServiceDisconnected(ComponentName name) {
  36. }
  37. @Override
  38. public void onServiceConnected(ComponentName name, IBinder service) {
  39. //返回一个MsgService对象
  40. msgService = ((MsgService.MsgBinder)service).getService();
  41. //注册回调接口来接收下载进度的变化
  42. msgService.setOnProgressListener(new OnProgressListener() {
  43. @Override
  44. public void onProgress(int progress) {
  45. mProgressBar.setProgress(progress);
  46. }
  47. });
  48. }
  49. };
  50. @Override
  51. protected void onDestroy() {
  52. unbindService(conn);
  53. super.onDestroy();
  54. }
  55. }
  56. </span>

用回调接口是不是更加的方便呢,当进度发生变化的时候Service主动通知Activity,Activity就可以更新UI操作了

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

[java] view plaincopy

  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. public class MainActivity extends Activity {
  14. private ProgressBar mProgressBar;
  15. private Intent mIntent;
  16. private MsgReceiver msgReceiver;
  17. @Override
  18. protected void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.activity_main);
  21. //动态注册广播接收器
  22. msgReceiver = new MsgReceiver();
  23. IntentFilter intentFilter = new IntentFilter();
  24. intentFilter.addAction("com.example.communication.RECEIVER");
  25. registerReceiver(msgReceiver, intentFilter);
  26. mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
  27. Button mButton = (Button) findViewById(R.id.button1);
  28. mButton.setOnClickListener(new OnClickListener() {
  29. @Override
  30. public void onClick(View v) {
  31. //启动服务
  32. mIntent = new Intent("com.example.communication.MSG_ACTION");
  33. startService(mIntent);
  34. }
  35. });
  36. }
  37. @Override
  38. protected void onDestroy() {
  39. //停止服务
  40. stopService(mIntent);
  41. //注销广播
  42. unregisterReceiver(msgReceiver);
  43. super.onDestroy();
  44. }
  45. /**
  46. * 广播接收器
  47. * @author len
  48. *
  49. */
  50. public class MsgReceiver extends BroadcastReceiver{
  51. @Override
  52. public void onReceive(Context context, Intent intent) {
  53. //拿到进度,更新UI
  54. int progress = intent.getIntExtra("progress", 0);
  55. mProgressBar.setProgress(progress);
  56. }
  57. }
  58. }
  59. </span>

[java] view plaincopy

  1. <span style="font-family:System;">package com.example.communication;
  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.IBinder;
  5. public class MsgService extends Service {
  6. /**
  7. * 进度条的最大值
  8. */
  9. public static final int MAX_PROGRESS = 100;
  10. /**
  11. * 进度条的进度值
  12. */
  13. private int progress = 0;
  14. private Intent intent = new Intent("com.example.communication.RECEIVER");
  15. /**
  16. * 模拟下载任务,每秒钟更新一次
  17. */
  18. public void startDownLoad(){
  19. new Thread(new Runnable() {
  20. @Override
  21. public void run() {
  22. while(progress < MAX_PROGRESS){
  23. progress += 5;
  24. //发送Action为com.example.communication.RECEIVER的广播
  25. intent.putExtra("progress", progress);
  26. sendBroadcast(intent);
  27. try {
  28. Thread.sleep(1000);
  29. } catch (InterruptedException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }
  34. }).start();
  35. }
  36. @Override
  37. public int onStartCommand(Intent intent, int flags, int startId) {
  38. startDownLoad();
  39. return super.onStartCommand(intent, flags, startId);
  40. }
  41. @Override
  42. public IBinder onBind(Intent intent) {
  43. return null;
  44. }
  45. }</span>

总结:

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

Service 启动Activity的相关文章

关于通过adb启动Activity、activity、service以及发送broadcast的命令

一.启动activity: $ adb shell$ am start -n {包名}/{包名}.{活动名称} 如:启动一个名叫MainActivity的活动 # am start -n com.example.test/com.example.test.MainActivity 二.启动service: $ adb shell$ am startservice -n {包名}/{包名}.{服务名称} 如:启动一个名叫MyService的服务 # am startservice -n com.e

【Android】Activity切换效果——当通过Service启动自己Activity的时候怎么控制

1原因: 当你在网上搜activity切换效果的时候基本就是告诉你要么是XML要么是overridePendingTransition,但是如果你是Service启动的Activity怎么办,这个网上没有一个给出答案了,所以就自己想了下,发现其实很简单. 2解决方案: 其实很简单,让我们了解下原理,所谓的activity切换也无非是activity根据theme或者别人startactivity的时候调用了overridePendingTransition修改了activity切换的参数,所以很

adb启动activity、service、发送broadcast

一.adb启动activity: $ adb shell$ am start -n {包(package)名}/{包名}.{活动(activity)名称} 如:启动浏览器 # am start -n com.android.browser/com.android.browser.BrowserActivity 二.adb启动service: $ adb shell$ am startservice -n {包(package)名}/{包名}.{服务(service)名称} 如:启动自己应用中一个

[Android UI] Service里面启动Activity和Alertdialog

启动Activity源码:(记得要加上Intent.FLAG_ACTIVITY_NEW_TASK) Intent intent = new Intent(); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setClass(getApplicationContext(),FileBrowserActivity.class); startActivity(intent); 原因:如果一个外部的Activity Context调用sta

Service里面启动Activity和Alertdialog

启动Activity源码:(记得要加上Intent.FLAG_ACTIVITY_NEW_TASK) Intent intent = new Intent(); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setClass(getApplicationContext(),FileBrowserActivity.class); startActivity(intent); 启动AlertDialog源码: AlertDialog.Bu

使用intent来启动activity

Intent最常见的用途是绑定应用程序组件,并在应用程序之间通信.Intent用来启动Activity,允许创建不同屏幕的一个工作流. 要创建并显示一个Activity,可以调用startActivity,并传递给它一个Intent,如: startActiiy(myintent); 可以构造Intent来显示地指定要打开的Activity类,或者包含一个目标Activity必须执行的动作.在后面一种情况时,运行时将会使用一个成为"intent解析"的过程来动态选择activity.

Android隐式启动Activity匹配详解:Action,category,data

更多例子请参考:http://hi.baidu.com/wishwingliao/blog/item/0a38ccfce06f39e8fc037f85.html 隐式启动Activity的intent到底发给哪个activity,需要进行三个匹配,一个是action,一个是category,一个是data,可以是全部或部分匹配 同样适用于Service和BroadcastReceiver,下面是以Activity为例 MainActivity.java --主Activity TestActiv

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

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

Service与Activity通信与AIDL

出差深圳一个月,终于回来了,一个月里干了不少,这些天里会慢慢总结一点东西出来,今天说的是关于Service的一点事:通信.通信的做法比较固定,基本上按照模板来写就可以实现. 1.Service与Activity通信 Activity通过startService()方法启动Service之后,Service将独立于Activity运行(虽然仍然是同一个进程),Activity无法指导Service如何运行.当Activity需要根据一些条件决定Service如何运行的时候,就需要有另外的方法了:将