【问题标题】:About android lifecycle关于安卓生命周期
【发布时间】:2013-09-27 22:21:14
【问题描述】:

我从这里Dev guide 了解了 android 活动的生命周期。现在我对代码的哪一部分驻留在哪个方法中感到困惑,例如 onCreate、onStart、onResume、onRestart、onPause、onResume、onStop 和 onDestroy。你能帮我把它们放在正确的地方吗?即使应用程序最小化,跟踪也应该继续。我有以下代码。

public class MainActivity extends FragmentActivity implements  LocationListener {

//List of user defined variables

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    /*for now i  have kept everything in onCreate method
     * i have start and stop button to start the tracking and stop the tracking and show the distance of travel
    1. Checking whether GPS is on or OFF
    2. button = (ImageButton) findViewById(R.id.myButton);
    3. Code to load the Google map
    4. Now specified what start and stop button does.
        i. when i press start button it starts overlaying the path in the map and calculate distance travelled so far
        ii. when i press stop button it stops tracking and shows the details of final result in next activity.
    LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 2, this);
    */

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

@Override
public void onLocationChanged(Location arg0) {
    // TODO Auto-generated method stub
    //i hace code for tracking and overlaying here

}

@Override
public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}

}

【问题讨论】:

  • 谁说你应该只在活动中收听位置更新?如果您有一个单独的服务或专用模型对象怎么办。确保你也阅读了this article
  • 这完全取决于你想在你的应用程序中做什么。您想在后台还是仅在前台收听 GPS 位置?
  • 我想同时监听背景和前景的 GPS。
  • 那么你应该为它使用服务而不是活动。

标签: android


【解决方案1】:

基于我认为您想要的想法:“具有开始记录和停止记录按钮的应用程序,同时使用谷歌地图显示路线。” 对吗?

您将需要 2 个组件:

服务(后台操作)

  • 启动时:侦听 GPS 更新并将其存储在内部。
  • 停止时:停止收听

活动(图形用户界面)

有 2 个按钮,开始和停止记录,以及 Google 地图小部件。

  • 按钮启动:使用startService 启动Service
  • 按钮停止:使用stopService 停止Service
  • 位置检索(在onResumeonPause 之间):向服务(使用绑定或Messager)询问内部存储的位置。检索到后,使用 Google 地图小部件显示它们。

【讨论】:

  • 是的,这正是我想要的。你能帮我提供一些代码或任何使用服务(后台操作)的教程链接吗?你能告诉我哪些代码位于哪个方法中吗?
  • 这个行为在你能找到的任何教程中都有解释。查看 d.android.com 和 vogella.com/android.html
  • 在 onPause() 中启动服务,使服务做一些工作并定期将数据发送到调用活动,并在 onResume() 中停止服务。这行得通吗?由于后台activity无法运行任何代码,activity将如何从service获取消息?
  • 你应该在点击按钮的时候启动服务,而不是在Activity的onResume的onPause中。
猜你喜欢
  • 2017-11-07
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 2019-03-04
相关资源
最近更新 更多