Android:如何在真实设备中永远运行Android服务?

时间:2013-03-02 09:36:19

标签: android

我创建了一个活动,该活动提供用户位置,并使用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;
}
}

MyReceiver.java

    package com.example.meragps;

    package com.example.meragps;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;

    public class MyReceiver extends BroadcastReceiver {


     public static final String TAG = "com.example.meragps";
     @Override
     public void onReceive(Context context, Intent intent) {
      // just make sure we are getting the right intent (better safe than sorry)
      /*if( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) 
      {
       ComponentName comp = new ComponentName(context.getPackageName(),
       LocationLoggerServiceManager.class.getName());
       ComponentName service = context.startService(new Intent().setComponent(comp));
       if (null == service){
        // something really wrong here
        Log.e(TAG, "Could not start service " + comp.toString());
       }
      } else {
       Log.e(TAG, "Received unexpected intent " + intent.toString());   
      }*/
         try
         { 
             Intent serviceIntent = new Intent(context, GPSTracker.class);
            context.startService(serviceIntent);     
         }
         catch(Exception e)
         {
             Log.e("My Service Error",e.getMessage());
         }


    }



    }

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>

1 个答案:

答案 0 :(得分:2)

服务始终运行模式...或者您需要创建BroadCast Receiver ..当您启动设备时服务将启动.. Link for BroadCastReciever