如果App正在运行,则在BroadcastReceiver中显示对话框

时间:2017-12-13 09:28:45

标签: android broadcastreceiver

我正在尝试显示通知(如果您单击它,打开带对话框的活动),如果应用程序已关闭或在后台运行,但如果它已打开或正在前台运行,我想直接显示对话框。

我有这段代码:

@Override
public void onReceive( Context context, Intent intent )
{
    if ( RunningHelper.isAppRunning(context, Constants.PROJECT_NAME ) )
    {
        Log.d("Running", "--------APP RUNNING");


    }
    else
    {

        Log.d("Running", "--------APP NOT RUNNING");
        showNotification();
    }
}

我的RunningHelper:

 public static boolean isAppRunning(final Context context, final String packageName) {
    final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    final List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
    if (procInfos != null)
    {
        for (final ActivityManager.RunningAppProcessInfo processInfo : procInfos) {
            if (processInfo.processName.equals(packageName)) {
                return true;
            }
        }
    }
    return false;
}

问题是应用程序始终检测到正在运行onReceive(),有人有任何线索可以正确执行吗?感谢。

1 个答案:

答案 0 :(得分:1)

实施自定义应用程序类

//node_modules (using ES6 modules)
import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';

//others
import { Home } from './pages/Home.js';
import { Page1 } from './pages/Page1.js';
import { Page2 } from './pages/Page2.js';

//App variables
const { Content, Footer, Sider } = Layout;

class App extends Component {
  render() {
    return (
      <Router>
        <Layout>
          <Sider>
             //some code
          </Sider>
          <Layout>
            <Header>
             //some code
            </Header>
            <Content>
              <Route exact path="/" component={Home}/>
              <Route path="/page1" component={Page1}/>
              <Route path="/page2" component={Page2}/>
            </Content>
            <Footer>
             //some code     
            </Footer>
          </Layout>
        </Layout>
      </Router>
    );
  }
}

export default App;

不要忘记在应用程序类的AndroidManifest中输入。

将onPause和onResume添加到项目中的每个Activity,或者您可以创建扩展AppCompatActivity / FragmentActivity的BaseActivity,并且所有项目活动都必须扩展BaseActivity

@覆盖

    public class ProjectApplication extends Application {

  public static boolean isActivityVisible() {
    return activityVisible;
  }  

  public static void activityResumed() {
    activityVisible = true;
  }

  public static void activityPaused() {
    activityVisible = false;
  }

  private static boolean activityVisible;
}

当收到广播时,您可以检查活动是在前景还是背景

protected void onResume() {
  super.onResume();
  ProjectApplication.activityResumed();
}

@Override
protected void onPause() {
  super.onPause();
  ProjectApplication.activityPaused();
}