处理方向变更服务

时间:2015-04-04 12:10:25

标签: android service android-lifecycle

我的应用程序中有两个服务,一个用于CountDownTimer,另一个用于Window管理器。我的主要活动是

public class MainActivity extends ActionBarActivity {

    // Variables


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       // some code here

    }



// Broadcase reciever for Countdown Timer
    private BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateGUI(intent); // or whatever method used to update your GUI
                                // fields
        }
    };

    private void updateGUI(Intent intent) {
        if (intent.getExtras() != null) {
            long millisUntilFinished = intent.getLongExtra("countdown", 0);
            HeadService.textView.setText("" + millisUntilFinished / 1000);
            Log.i("YOLO", "Countdown seconds remaining: " + millisUntilFinished
                    / 1000);
        }

    }


// Registrating and Starting services in onStart()
    @Override
    public void onStart() {
        // TODO Auto-generated method stub

        super.onStart();
        startHeadService();

        registerReceiver(br, new IntentFilter(BroadcastService.COUNTDOWN_BR));

        Log.i("Check", "Registered broacast receiver");
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    public void onStop() {
        try {
            unregisterReceiver(br);
            stopHeadService();
        } catch (Exception e) {
            // Receiver was probably already stopped in onPause()
        }
        super.onStop();
    }

    @Override
    public void onDestroy() {
        stopService(new Intent(this, BroadcastService.class));
        stopHeadService();
        Log.i("Check", "Stopped service");
        super.onDestroy();
    }

    private void startHeadService() {

        startService(new Intent(this, HeadService.class));
    }

    private void stopHeadService() {

        stopService(new Intent(this, HeadService.class));
    }
}

当我改变方向时,我的服务会停止,新服务会重新开始。所以基本上我想知道的是从哪里开始和停止我的服务,以便它甚至在方向改变时继续运行。此外,我知道从这里Which activity method is called when orientation changes occur?改变方向的生命周期是什么,我只是不知道该怎么做。提前谢谢。

1 个答案:

答案 0 :(得分:2)

更改活动的方向时,将调用

onCreate()方法。

为避免这种情况,请将以下代码添加到清单文件中的活动中:

... 机器人:configChanges = “取向|屏幕尺寸”