如何在手机状态进入闲置状态时关闭活动?

时间:2014-09-18 14:51:20

标签: android

我想知道当手机状态变为空闲时如何关闭活动。当电话状态从服务中“关闭”时,我可以打开一个活动。现在,我需要关闭这项活动。任何帮助将不胜感激。

这是我的代码:

public class OnCallListener extends Service {
PhoneStateListener phoneStateListener;
TelephonyManager mgr;
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        mgr= (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
         phoneStateListener = new PhoneStateListener() {
                @Override
                public void onCallStateChanged(int state, String incomingNumber) {

                    if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
                        Intent i=new Intent(getBaseContext(),OnCall.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(i);
                        //mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
                    } 
                      if(state==TelephonyManager.CALL_STATE_IDLE)
                    {  


                    **//Here i want to close the activity which i opened in "Off-Hook" state**




                    }

                    }

                };

                     mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        return super.onStartCommand(intent, flags, startId);

    }

}

3 个答案:

答案 0 :(得分:0)

使用包含标志(例如额外)的意图启动该活动,以告知您的活动关闭

在您的活动中,您可以覆盖onNewIntent()阅读标记并在活动意图关闭时致电finish()

答案 1 :(得分:0)

您可以从服务发送本地广播,以通知活动自行关闭。在您的Activity的onResume中,注册该特定广播并调用finish()。例如:

服务代码:

Intent i = new Intent(MyActivity.ACTION_COMPLETED);
LocalBroadcastManager.getInstance(this).sendBroadcast(i);

活动代码:

@Override
public void onResume() {
    super.onResume();
    IntentFilter f = new IntentFilter(ACTION_COMPLETED);
    LocalBroadcastManager.getInstance(this).registerReceiver(onPhoneIdle, f);
}

@Override
public void onPause() {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(onPhoneIdle);
    super.onPause();
}

private BroadcastReceiver onPhoneIdle = new BroadcastReceiver() {
    public void onReceive(Context context, Intent i) {
        finish();
    }
}

答案 2 :(得分:0)

如果你想关闭活动,只需

像你一样在你的活动中写一个广播接收器

private final BroadcastReceiver mybroadcast = new BroadcastReceiver() {
             @Override
             public void onReceive(Context context, Intent intent) {
                   finish();                                   
             }
     };

在你的onCreate方法中注册它:

onCreate(){

    registerReceiver(mybroadcast, new IntentFilter("brcdt"));
}
不要忘记取消注册:

onDestroy(){

unregisterReceiver(mybroadcast);
}

发送广播以撤销您要关闭活动的Boradcast接收器

sendBroadcast(new Intent("brcdt"));