【问题标题】:Handle Services in orientation change处理方向变化的服务
【发布时间】:2015-04-04 12:10:25
【问题描述】:

我的应用中有两项服务,一项用于 CountDownTimer,一项用于窗口管理器。我的主要活动是

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? 的方向变化遵循什么活动生命周期,我只是不知道我应该做什么。提前致谢。

【问题讨论】:

    标签: android service android-lifecycle


    【解决方案1】:

    onCreate() 方法在你改变一个活动的方向时被调用。

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

    ... android:configChanges="orientation|screenSize"

    【讨论】:

    • 我需要把它放在 下吗?
    • 太棒了,我没想到会那么容易,谢谢@Hello World :)
    • 例如:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 2011-02-28
    • 2013-07-11
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多