[英]How can I determine if a broadcast receiver was invoked when the app was running as opposed to when the app was dormant or in the background?
我在清單中注冊了BroadcatReceiver,目的是在電話鈴響時使音頻靜音。 我希望BroadcastListener在3種情況下的行為有所不同:
我想要這種能力來識別,因為我認為廣播接收器會自動並以隱藏的方式啟動發送通知的服務。 如果用戶在明確離開應用程序后收到此通知,則很煩人。
這是我的一些嘗試
public class MyBroadcastReceiver extends BroadcastReceiver {
//private final static Global global = Global.getInstance();
private static final String TAG = MyBroadcastReceiver.class.getName();
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "broadcast recieved");
//Log.d(TAG, "context package name is: " + context.getPackageName());
Bundle extras = intent.getExtras();
if (extras != null) {
String state = extras.getString(TelephonyManager.EXTRA_STATE);
Log.d(TAG, "State : " + state);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
{
Log.d(TAG, "context package name: " + context.getPackageName());
Global global = Global.getInstance();
global.shutUp();
Log.d(TAG, "global package name: " + global.getPackageName());
String phoneNumber = extras.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.d(TAG, "Calling number: " + phoneNumber);
//TODO try to condition this if receiver activated from outside the application
if(isAppOnForeground(context))
{
Log.d(TAG, "app is in forgeround");
}
else
{
Log.d(TAG, "app is not in forgeround");
}
if(isMyServiceRunning(context))
{
Log.d(TAG, "service running");
}
else
{
Log.d(TAG, "service isn't running");
}
//global.stopService(new Intent(ReturnService.class.getName()));
//Log.d(TAG, "requested return service stoped");
}
}
//I think this return is imperative so that return service isn't invoked
return;
}
private boolean isAppOnForeground(Context context)
{
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null)
{
return false;
}
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses)
{
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName))
{
return true;
}
}
return false;
}
private boolean isMyServiceRunning(Context context)
{
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
{
if (ReturnService.class.getName().equals(service.service.getClassName()))
{
return true;
}
}
return false;
}
}
我認為,在您的情況下,更簡單的解決方案是在創建啟動器活動時簡單地將其設置為全局標志,而在銷毀活動時將其關閉。 如果在將廣播發送到接收器時您的應用未打開,則該標志將關閉,然后您可以進行相應操作。
如果您的應用程序是一個活動(並且我不認為它是一個InputMethodService),則可以重寫Activity方法onPause()和onResume() 。 如果您在其中一個中將某個靜態標志設置為true,而在另一個中將其清除,則該標志將告訴您是否在屏幕上顯示了最后一個活動。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.