GVKun编程网logo

永远在后台运行Swift 2.0应用程序以更新服务器位置(swift运行环境)

14

这篇文章主要围绕永远在后台运行Swift2.0应用程序以更新服务器位置和swift运行环境展开,旨在为您提供一份详细的参考资料。我们将全面介绍永远在后台运行Swift2.0应用程序以更新服务器位置的优

这篇文章主要围绕永远在后台运行Swift 2.0应用程序以更新服务器位置swift运行环境展开,旨在为您提供一份详细的参考资料。我们将全面介绍永远在后台运行Swift 2.0应用程序以更新服务器位置的优缺点,解答swift运行环境的相关问题,同时也会为您带来Android iBeacon应用程序无法在后台运行、android – 如何让我的应用程序在后台运行?、android – 当我退出应用程序时,声音在后台运行、android – 让应用程序在后台运行的实用方法。

本文目录一览:

永远在后台运行Swift 2.0应用程序以更新服务器位置(swift运行环境)

永远在后台运行Swift 2.0应用程序以更新服务器位置(swift运行环境)

我写了下面的代码,其中包含一个计时器,每分钟调用一次回调函数。当应用程序进入后台时,我已经启动了另一个计时器,该计时器调用相同的回调方法,但是后台计时器仅工作三分钟。

我了解到Apple仅允许后台任务执行三分钟。我的应用程序更像是一个跟踪应用程序,即使在后台运行该应用程序,它也每分钟都会跟踪用户的位置,因此我需要实现此功能。

我了解到beginBackgroundTaskWithExpirationHandler将要使用它,但是我不知道我的实现是否正确。

注意:我在plist toApp寄存器中有必需的后台模式,用于位置更新。

任何工作代码或链接都将受到赞赏。

override func viewDidLoad() {    super.viewDidLoad()    timeInMinutes = 1 * 60    self.locationManager.requestAlwaysAuthorization()    self.locationManager.requestWhenInUseAuthorization()    if CLLocationManager.locationServicesEnabled() {        locationManager.delegate = self        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters        locationManager.startUpdatingLocation()    }    var timer = NSTimer.scheduledTimerWithTimeInterval( timeInMinutes, target: self, selector: "updateLocation", userInfo: nil, repeats: true)}func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){    let locValue:CLLocationCoordinate2D = manager.location!.coordinate    self.latitude = locValue.latitude    self.longitude = locValue.longitude    if UIApplication.sharedApplication().applicationState == .Active {    } else {        backgroundTaskIdentifier = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({ () -> Void in            self.backgroundTimer.invalidate()            self.backgroundTimer = NSTimer.scheduledTimerWithTimeInterval( 60.0, target: self, selector: "updateLocation", userInfo: nil, repeats: true)        })    }}func updateLocation() {    txtlocationLabel.text = String(n)    self.n = self.n+1    var timeRemaining = UIApplication.sharedApplication().backgroundTimeRemaining    print(timeRemaining)    if timeRemaining > 60.0 {        self.GeoLogLocation(self.latitude,Longitude: self.longitude) {            results in            print("View Controller: \(results)")            self.CheckResult(String(results))        }    } else {        if timeRemaining == 0 {            UIApplication.sharedApplication().endBackgroundTask(backgroundTaskIdentifier)        }        backgroundTaskIdentifier2 = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({ () -> Void in            self.backgroundTimer.invalidate()            self.backgroundTimer = NSTimer.scheduledTimerWithTimeInterval( 60.0, target: self, selector: "updateLocation", userInfo: nil, repeats: true)        })    }}

答案1

小编典典

定期的位置更新在IOS中有点棘手,有一个很好的讨论这个话题,您可以在这里阅读更多内容

无论您的计时器是否在运行,iOS都会在几分钟后终止您的应用程序。不过,有一种解决方法,我在编写离子应用程序时必须做类似的事情,因此您可以在此处查看代码,该链接具有一个快速类,用于管理iO中的定期位置更新。

为了在后台获得周期性的位置,并且不消耗设备的电池电量,您需要使用位置记录的准确性,降低位置管理器的准确性,将其期望的准确性设置为kCLLocationAccuracyThreeKilometers,然后每60秒需要将精度更改为kCLLocationAccuracyBest,这将使委托能够获得新的,准确的位置更新,然后将精度恢复为低。每次接收更新时都需要初始化计时器。

还有一种方法可以在用户杀死应用程序之后在后台唤醒该应用程序,使用应用程序委托让该应用程序在其被杀死之前侦听位置的重大变化。当用户的位置发生较大变化(大约200毫秒)时,这会在后台唤醒应用。当应用程序唤醒时,请停止监视重大更改,并照常重启位置服务以继续进行定期更新。

希望这可以帮助。

更新资料

在Swift 2中,您还需要:

self.locationManager.allowsBackgroundLocationUpdates = true

Android iBeacon应用程序无法在后台运行

Android iBeacon应用程序无法在后台运行

我开发了Android应用程序,以在客户接近1 mt距离时检测到信标.我正在使用Android Beacon Library开发应用程序.当我们处于前台时,我会收到通知,但是一旦应用程序进入后台,通知就会开始工作.你能帮我哪里错了吗?
下面是BeaconApp和MainActivity的代码.

BeaconApp.java

public class BeaconApp extends Application implements BootstrapNotifier {
    private static final String TAG = "BeaconApp";
    private RegionBootstrap regionBootstrap;
    private Region allbeaconsregions;
    private BackgroundPowerSaver bgSaver;
    BeaconManager beaconManager;
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "App started up");
        // To detect proprietary beacons, you must add a line likebelowcorresponding to your beacon
        // type.  Do a web search for "setBeaconLayout" to get the proper expression.
        // beaconManager.getBeaconParsers().add(new BeaconParser().
        //        setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));

        // wake up the app when any beacon is seen (you can specify specific id filers in the parameters below)
        beaconManager = BeaconManager.getInstanceForApplication(this);
        Beacon.setHardwareEqualityEnforced(true);
        bgSaver = new BackgroundPowerSaver(this);
        beaconManager.getBeaconParsers().add(new BeaconParser().
                setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));


        allbeaconsregions = new Region("treewalker", null, null, null);
        regionBootstrap = new RegionBootstrap(this, allbeaconsregions);
        //beaconManager.bind(this);
    }

    @Override
    public void didDetermineStateForRegion(int arg0, Region arg1) {
        // Don't care
        Log.d(TAG, "Enter in  didDetermineStateForRegion call");
    }

    @Override
    public void didEnterRegion(Region arg0) {
        Log.d(TAG, "Got a didEnterRegion call");
        // This call to disable will make it so the activity below only gets launched the first time a beacon is seen (until the next time the app is launched)
        // if you want the Activity to launch every single time beacons come into view, remove this call.
        regionBootstrap.disable();
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Important:  make sure to add android:launchMode="singleInstance" in the manifest
        // to keep multiple copies of this activity from getting created if the user has
        // already manually launched the app.
        this.startActivity(intent);


    }

    @Override
    public void didExitRegion(Region arg0) {
        // Don't care
        Log.d(TAG, "Enter in  didExitRegion call");
    }



}

在MainActivity.java中

public class MainActivity extends AppCompatActivity implements BeaconConsumer,RangeNotifier {
    protected static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBeaconManager = BeaconManager.getInstanceForApplication(this);
        Beacon.setHardwareEqualityEnforced(true);
        BackgroundPowerSaver bgSaver = new BackgroundPowerSaver(this);
        mBeaconManager.getBeaconParsers().add(new BeaconParser().
                setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
        mBeaconManager.bind(this);


    }

    private BeaconManager mBeaconManager;

    public void onResume() {
        super.onResume();
        mBeaconManager = BeaconManager.getInstanceForApplication(this.getApplicationContext());
        // Detect the main Eddystone-UID frame:
        mBeaconManager.getBeaconParsers().add(new BeaconParser().
                setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
        mBeaconManager.bind(this);
    }


   public void onBeaconServiceConnect() {


           try {
               mBeaconManager.startRangingBeaconsInRegion(new Region("treewalker", null, null, null));
               mBeaconManager.addRangeNotifier(this);
           }catch (remoteexception e){
               e.printstacktrace();
           }


   }

    @Override
    public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {

        if(beacons.size() > 0) {
            for (Beacon beacon : beacons) {
                if (beacon.getdistance() < 1.0) {
                    Log.d(TAG, "I see a beacon transmitting a : " +
                            " approximately " + beacon.getdistance() + " meters away.");

                    Log.d(TAG, "BEACON DATA : " +beacon.getBluetoothAddress()+":"+beacon.getBluetoothName()+":"+beacon.getId1());

                    showNotification("Treewalker","You are near beacon range");
                    Intent intent = new Intent(this,MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    this.startActivity(intent);


                }


            }
        }
    }

    public void showNotification(String title, String message) {
        Intent notifyIntent = new Intent(this, DashboardActivity.class);
        notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivities(this, 0,
                new Intent[] { notifyIntent }, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification = new Notification.Builder(this)
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .build();
        notification.defaults |= Notification.DEFAULT_SOUND;
        notificationmanager notificationmanager =
                (notificationmanager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationmanager.notify(1, notification);
    }
    @Override
    public void onPause() {
        super.onPause();
        //mBeaconManager.unbind(this);
    }
}

解决方法:

问题在于,当您的应用程序进入后台时,MainActivity将调用onPause,而该方法中的代码将调用mBeaconManager.unbind(this);.方法,可有效停止信标测距.

如果要在后台继续进行测距,最简单的方法是移动以下两行:

mBeaconManager.startRangingBeaconsInRegion(new Region("treewalker", null, null, null));
mBeaconManager.addRangeNotifier(this);

到BeaconApp类的didDetermineStateForRegion方法.您还需要将didRangeBeaconsInRegion和showNotification方法也移到那里.

android – 如何让我的应用程序在后台运行?

android – 如何让我的应用程序在后台运行?

我正在创建一个应用程序,我需要始终通过TCP套接字连接.我的应用程序已经在连接方面运行良好,但是当它被发送到后台时,android系统最终会杀死进程.这会导致它与服务器断开连接.

我一直在寻找一种方法来始终保持应用程序活着,但没有找到任何东西.
有人可以告诉我什么是最好的方法,以便我的应用程序在后台时不会关闭,或者,除非这样,如果它关闭,让它重新启动?
我从这开始就让我头疼:S

编辑
这是我的代码的一部分:

public int onStartCommand(Intent intent,int flags,int startId) {

      Toast.makeText(this,"service starting",Toast.LENGTH_SHORT).show();

      new Thread(new Runnable() { 
            public void run() {
                Playit();               }
        }).start();


     return START_STICKY;
  }

不过,该应用程序似乎在启动时被冻结.我没有很多经验,所以也许我的错误很简单,我没有注意到它.

解决方法

使用服务并通过startService()启动它.它将一直运行,直到Android停止它的资源

一些有关服务的文件:

> http://developer.android.com/reference/android/app/Service.html
> http://developer.android.com/guide/components/services.html

android – 当我退出应用程序时,声音在后台运行

android – 当我退出应用程序时,声音在后台运行

我“创建”了一个应用程序,当我回去或按下主页按钮退出应用程序时,我的应用程序中的音频仍在运行!我必须关闭所有正在运行的应用程序以使其停止.

当我按下主页按钮时,如何停止音频运行?

解决方法:

覆盖所有活动的onPause()方法,并在调用音乐时关闭/暂停/停止音乐.您可能需要使用布尔标志来检查您是否在应用程序中移动,这是您希望音乐继续的场景:

boolean movingInApp = false;
....
movingInApp = true;
Intent intent...
.....
public void onPause() {
    if(!movingInApp) {
        //stop service
    }
}

public void onResume() {
    movingInApp = false;
    //Rest of your code
}

通过在启动任何意图等之前将movingInApp的值设置为true,可以阻止您的应用停止播放音乐.请记住稍后在onResume()方法中将其再次设置为false.如果系统让您的应用程序转到后台,这将是错误的,您的音乐将被停止.

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答案寻求帮助.

我们今天的关于永远在后台运行Swift 2.0应用程序以更新服务器位置swift运行环境的分享就到这里,谢谢您的阅读,如果想了解更多关于Android iBeacon应用程序无法在后台运行、android – 如何让我的应用程序在后台运行?、android – 当我退出应用程序时,声音在后台运行、android – 让应用程序在后台运行的相关信息,可以在本站进行搜索。

本文标签: