Android 安卓:如何在真正的设备上永远运行安卓服务?

Android 安卓:如何在真正的设备上永远运行安卓服务?,android,Android,我已经创建了一个提供用户位置的活动,并使用web服务将此信息发送到服务器。在此之前,项目将成功运行。但我想将此活动作为服务运行,所以我创建了服务并复制了活动代码并将其粘贴到服务代码中。但它不起作用??我有关于这方面的研究,但不能弄清楚 GPSTracker.java package com.example.meragps; import java.io.IOException; import java.util.Date; import java.util.List; import or

我已经创建了一个提供用户位置的活动,并使用web服务将此信息发送到服务器。在此之前,项目将成功运行。但我想将此活动作为服务运行,所以我创建了服务并复制了活动代码并将其粘贴到服务代码中。但它不起作用??我有关于这方面的研究,但不能弄清楚

GPSTracker.java

package com.example.meragps;


import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
import android.util.Log;


public class GPSTracker extends Service implements LocationListener 
{


String imei="";
String simSerialNumber="";
String stAdd="";
String currentTime="";
String resultData="";


private static final String SOAP_ACTION = "http://tempuri.org/GetCurrentLocation";
private static final String METHOD_NAME = "GetCurrentLocation";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://"my static ip"/GPSTracker/Service1.asmx";


private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

 // The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000; // 1000 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 20; // 20 minute

// Declaring a Location Manager
protected LocationManager locationManager;






public GPSTracker(Context context) 
{
    this.mContext = context;
    getLocation();




}
@Override
public int onStartCommand(Intent intent, int flags, int startId) 
{
  //TODO do something useful
    gpsTraking();
    passing();

  return Service.START_NOT_STICKY;
}

public Location getLocation() 
    {

    try 
    {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) 
    {
            // no network provider is enabled
    } 
        else 
    {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) 
    {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) 
    {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) 
    {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
    }
    }
    }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) 
    {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) 
    {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) 
    {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
    }
    }
    }
    }
    }

    } catch (Exception e) 
    {
        e.printStackTrace();
    }

    return location;
    }


public void gpsTraking()
{
      // create class object


    // check if GPS enabled
    if(true)
    {

        double latitude = getLatitude();
        double longitude = getLongitude();
        Geocoder gc=new Geocoder(getBaseContext());
        try 
        {
            stAdd="";
            List<Address> list= gc.getFromLocation(latitude, longitude, 2);

            Address a= list.get(0);

            for(int i=0;i<=a.getMaxAddressLineIndex();i++)
            {
                    stAdd=stAdd+"\n "+a.getAddressLine(i);
            }
            stAdd=stAdd+" "+a.getLocality()+"\n"+a.getFeatureName();

        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    // \n is for new line
        CharSequence d = DateFormat.format("dd-MM-yyyy hh:mm:ss", new Date());
        currentTime= d.toString();
       Log.d("currentTime",currentTime);

        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
     // get IMEI
     imei = tm.getDeviceId();
     // get SimSerialNumber
   simSerialNumber = tm.getSimSerialNumber();




    }

    else
    {
        /* can't get location
        GPS or Network is not enabled
        Ask user to enable GPS/network in settings*/
        showSettingsAlert();
    }

    }

public void passing()
{
      SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

       request.addProperty("strIMEINumber",imei);
       request.addProperty("strSIMNumber",simSerialNumber);
       //request.addProperty("strAddress","Rajasthan 400031");
       request.addProperty("strAddress",stAdd);
       request.addProperty("strTime",currentTime);




           SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
           envelope.dotNet = true;
           envelope.encodingStyle=SoapSerializationEnvelope.ENC;
           envelope.setOutputSoapObject(request);
           System.setProperty("http.keepAlive", "false");

            try 
            {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.call(SOAP_ACTION, envelope);
                //SoapObject response = (SoapObject) envelope.getResponse();
                SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
                resultData= result.toString();              
                //editText.setText(resultData);
                Log.d("response", resultData);
            }
           catch (Exception e) 
            {
                // TODO Auto-generated catch block

                Log.d("My Error", ""+e.getMessage());

            }




    } 

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null)
{
        locationManager.removeUpdates(GPSTracker.this);
}
}

/**
 * Function to get latitude
 * */
public double getLatitude()
{
    if(location != null)
{
        latitude = location.getLatitude();
}

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude()
{
    if(location != null)
{
        longitude = location.getLongitude();
}

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() 
{
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will launch Settings Options
 * */
public void showSettingsAlert()
{
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() 
{
        public void onClick(DialogInterface dialog,int which) 
{
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
}
});

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
{
        public void onClick(DialogInterface dialog, int which) 
{
        dialog.cancel();
}
});

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) 
{
}

@Override
public void onProviderDisabled(String provider) 
{
}

@Override
public void onProviderEnabled(String provider) 
{
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) 
{
}



@Override
public IBinder onBind(Intent arg0) 
{
    return null;
}
}
MeraGPS Manifest.xml

  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.meragps"
  android:versionCode="1"
  android:versionName="1.0" >
     <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> 
      <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
      <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
       <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
      <uses-permission android:name="android.permission.INTERNET" /> 
        <application
    android:allowBackup="true">


   <receiver android:name=".MyReceiver" 
     android:enabled="true" 
     android:exported="false"
     android:label="MyReceiver">
  <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
  </intent-filter>
    </receiver>


  <intent-filter>

    <action android:name="android.intent.action.MAIN" />
      <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter> 


      </application>

      </manifest>


服务始终运行模式。。。或者您需要创建广播接收器。。然后,当您启动设备时,服务将启动

我已经创建了BroadcastReceiver…但它也不工作…我在上面提到过这一点…当你触发GPS轨迹时。这就像当设备启动时,您尝试调用广播接收器,您是否检查了日志,wht是LogCat.forcestopping package com.example.meragps uid=10041Am的状态假设您在设备启动时尝试调用GPS api,这可能是一个原因,您尝试将信息发送到服务器的基础是什么。根据代码,当启动时,调用GPSTrack服务。确保在执行操作之前,检查GPs是否能够继续。还有,请检查GPS是否在设备上。是的,我正在按照您假设的方式尝试…首先执行MyReceicer.java,然后调用GPSTracker.java。我已经检查过GPS是否打开,但它仍然不工作…上面的代码是否正确
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.meragps"
  android:versionCode="1"
  android:versionName="1.0" >
     <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> 
      <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
      <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
       <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
      <uses-permission android:name="android.permission.INTERNET" /> 
        <application
    android:allowBackup="true">


   <receiver android:name=".MyReceiver" 
     android:enabled="true" 
     android:exported="false"
     android:label="MyReceiver">
  <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
  </intent-filter>
    </receiver>


  <intent-filter>

    <action android:name="android.intent.action.MAIN" />
      <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter> 


      </application>

      </manifest>