【问题标题】:How to differentiate SCREEN_ON and PHONE_STATE broadcast receiver如何区分 SCREEN_ON 和 PHONE_STATE 广播接收器
【发布时间】:2013-01-22 05:00:52
【问题描述】:

我有两个广播。

一个是屏幕开/关,第二个是手机状态。如果屏幕打开,我想向用户显示我的活动,但如果是电话,则不显示。

如何管理这个任何帮助将不胜感激..

【问题讨论】:

    标签: android broadcastreceiver lockscreen phone-state-listener


    【解决方案1】:

    您需要使用 if/else 条件将广播操作标识为:

    public static final String Screen_on = "android.intent.action.SCREEN_ON";
    @Override
    public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Screen_on)) {
       // do your job here if screen is on /off
    }
    else{
            // send new intent to your Activity here 
             Intent intent = new Intent(context,Activity1.class);
         intent.putExtra("status","CALL_STATE");
         context.startActivity(intent);
    
            Bundle extras = intent.getExtras();
           if (extras != null) {
            String state = extras.getString(TelephonyManager.EXTRA_STATE);
            if (state.equals(TelephonyManager.EXTRA_STATE_RINGING) {
               // do your job here if PHONE STATE CHNAGED
            }
          }
    
    }
    

    并将AndroidManifest.xml 中的 Activity 声明为 android:launchMode="singleTask" 并在 Activity 运行时覆盖 onNewIntent 以接收意图:

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        finishactivity();
    }
    private void finishactivity(){
        Intent intent = getIntent();
        Bundle extras=intent.getExtras();
        if(extras!=null){
              if(extras.getString("status").equals("CALL_STATE"))
             // finish your Activity here
        } 
    }
    

    【讨论】:

    • 我试过这个,但似乎出现了一个问题,比如 screen_on 比电话状态先被调用,假设在 screen_on 上我已经显示了我的活动,然后在获取 Phone_state 接收器之后,不应该显示活动。
    • @sandy :作为您的问题,此代码仅在 SCREEN_ON Action BroadcastReceiver 时才开始活动。
    • @sandy :查看我的编辑答案可能会帮助您实现您的目标
    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多