android – 让应用程序在后台运行

前端之家收集整理的这篇文章主要介绍了android – 让应用程序在后台运行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想让我的应用程序在后台运行
我有一个应用程序将用户的位置发送到我们的服务器
我有以下代码
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LocationManager locationManager;
    String context = Context.LOCATION_SERVICE;
    locationManager = (LocationManager)getSystemService(context);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltituderequired(false);
    criteria.setBearingrequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    String provider = locationManager.getBestProvider(criteria,true);

    updateWithNewLocation(null);

    locationManager.requestLocationUpdates(provider,(10*60*1000),10,locationListener);
}
private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      updateWithNewLocation(location);
    }

    public void onProviderDisabled(String provider){
      updateWithNewLocation(null);
    }

    public void onProviderEnabled(String provider){ }
    public void onStatusChanged(String provider,int status,Bundle extras){ }
  };
  public void updateWithNewLocation(Location location) {


        if (location != null) {
            Dbhelper helper = new Dbhelper(this);
            final sqliteDatabase db = helper.getWritableDatabase();
            long time = System.currentTimeMillis();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
            final String curTime = df.format(time);
            final double lat = location.getLatitude();
            final double lng = location.getLongitude();
            final double alt = location.getAltitude();
            System.out.println(lat);
            System.out.println(lng);
            System.out.println(alt);
            db.execsql("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
            "('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
            db.close();
            /*Timer timer = new Timer();
            timer.scheduleAtFixedRate(new TimerTask(){
                @Override
                public void run(){
                    db.execsql("INSERT INTO location (longitude,tgl_buat) VALUES " +
                            "('121.2149012','-6.217837','0.0','2012-05-07 10:20:01')");
                    db.close();
                }
            },10*60*1000,10*60*1000);*/

          } 
       }

我希望我的应用程序在后台运行.我希望它在手机开机时自动启动

解决方法

对于您的问题,一个非常简单的答案是使用 Service.它将允许您在后台执行各种任务,并且是您静默地将您的位置发送到服务器的最佳选择.

阅读this答案寻求帮助.

原文链接:https://www.f2er.com/android/315731.html

猜你在找的Android相关文章