2015-04-04 34 views
0

我的应用程序中有两个服务,一个用于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?的定位更改遵循什么样的活动生命周期,我只是不知道该怎么做。提前致谢。

回答

2

当您更改活动的方向时,会调用onCreate()方法。

为了避免这种情况下面的代码添加到清单文件,你的活动:

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

+0

我是否需要把这个下? – Ajeet 2015-04-04 12:19:29

+0

真棒,我没有想到它会那么容易,谢谢@你好世界:) – Ajeet 2015-04-04 12:23:29

+0

例如: 2015-04-04 12:23:55

相关问题