android – 如果活动正在运行,则禁止来自服务的通知

前端之家收集整理的这篇文章主要介绍了android – 如果活动正在运行,则禁止来自服务的通知前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个活动和服务在我的应用程序中一起工作.我已将服务配置为远程服务(已实现的AIDL),因此即使活动不可见,它也会继续运行.

该服务负责轮询服务器以获取数据,并在满足特定条件时发送警报通知.我不希望服务在活动可见时发送这些通知.

服务是否有办法了解任何特定活动的状态?特别是一项与之相关的活动?

使用清单更新以解决权限问题:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.interact.listen.android.voicemail"
  4. android:versionCode="1"
  5. android:versionName="1.0">
  6. <application android:icon="@drawable/icon" android:label="@string/app_name">
  7. <activity android:name=".MyAppName"
  8. android:label="@string/app_name">
  9. <intent-filter>
  10. <action android:name="android.intent.action.MAIN" />
  11. <category android:name="android.intent.category.LAUNCHER" />
  12. </intent-filter>
  13. </activity>
  14. <activity android:name=".MyObjectDetails"/>
  15. <service android:enabled="true" android:name=".MyService" />
  16. <receiver android:name=".MyReceiver">
  17. <intent-filter>
  18. <action android:name="com.foo.bar.EVENT"/>
  19. </intent-filter>
  20. </receiver>
  21. </application>
  22. <uses-permission android:name="android.permission.INTERNET"></uses-permission>
  23. </manifest>

我在Logcat中遇到的错误

  1. 09-17 15:33:17.881: WARN/ActivityManager(53): Permission Denial: receiving Intent { act=com.foo.bar.myobject.EVENT (has extras) } to ProcessRecord{43928b40 223:com.foo.bar.myobject/10022} (pid=223,uid=10022) requires com.foo.bar.myobject.EVENT due to sender com.foo.bar.myobject (uid 10022)
  2. 09-17 15:33:48.901: WARN/ActivityManager(53): Permission Denial: receiving Intent { act=com.foo.bar.myobject.EVENT (has extras) } to com.foo.bar.myobject requires com.foo.bar.myobject.EVENT due to sender com.foo.bar.myobject (uid 10022)

发送广播的任务:

  1. @Override
  2. public void onStart(Intent intent,int startId)
  3. {
  4. super.onStart(intent,startId);
  5. serviceHandler = new Handler();
  6. serviceHandler.postDelayed(myTask,100L);
  7. Log.d(TAG,"onStart()");
  8. }
  9.  
  10. class Task implements Runnable
  11. {
  12. public void run()
  13. {
  14. Log.i(TAG,"Getting myObjects...");
  15. getMyObjects();
  16. Bundle bundle = new Bundle();
  17. bundle.putLongArray("ids",getIdsToUpdate());
  18.  
  19. Intent i = new Intent();
  20. i.setAction(UPDATE_ACTION_STRING);
  21. i.putExtras(bundle);
  22.  
  23. sendOrderedBroadcast(i,UPDATE_ACTION_STRING);
  24.  
  25. serviceHandler.postDelayed(this,30000L);
  26. }
  27. }
  28. }

解决方法

Is there a way for the Service to know the status of any particular activity? Particularly an activity that
is bound to it?

您可以实现某种回调系统.

但是有一种更清洁的方法可以解决这个问题.使用有序广播.活动有一个高优先级的接收器;将raise-a-notification逻辑置于低优先级接收器中.让活动的接收者调用abortBroadcast()来阻止通知.我有一个关于这项技术的blog post.使用事件总线:greenrobot的EventBus,LocalBroadcastManager,基于Rx的事件总线,甚至是MutableLiveData.让服务向总线发送消息.当UI位于前台时,让UI层注册总线上的事件.如果没有人拿起放在公交车上的事件,请让服务提出通知.

猜你在找的Android相关文章