如何在服务方法中完全运行后台进程?

时间:2013-05-03 08:50:37

标签: android service

大家可以告诉我如何在没有活动的情况下在服务中运行此代码,我在一个活动中完成了这个代码,但我不希望它成为一个应用程序我需要它只是为了显示它而在服务中服务谢谢你,我试过,但我的活动在30分钟内显示一次。

这是我的代码:

public class gps extends Activity implements LocationListener {

    LocationManager manager;
    String closestStation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

{
            Calendar cur_cal = Calendar.getInstance();
            cur_cal.setTimeInMillis(System.currentTimeMillis());
            cur_cal.add(Calendar.MINUTE, 15);
            Log.d("Testing", "Calender Set time:" + cur_cal.getTime());

            Intent intent = new Intent(gps.this, gps_back_process.class);
            PendingIntent pintent = PendingIntent.getService(gps.this, 0,
                    intent, 0);
            AlarmManager alarm_manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarm_manager.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 1000 * 60 * 15, pintent);
            alarm_manager.set(AlarmManager.RTC, cur_cal.getTimeInMillis(),
                    pintent);
            Log.d("Testing", "alarm manager set");
            Toast.makeText(this, "gps_back_process.onCreate()",
                    Toast.LENGTH_LONG).show();
        }

         Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
         intent.putExtra("enabled", true);
         this.sendBroadcast(intent);

        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if(!provider.contains("gps")){ //if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3")); 
            this.sendBroadcast(poke);


        }
    {
        //initialize location manager
        manager =  (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //check if GPS is enabled
        //if not, notify user with a toast
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); else {
            //get a location provider from location manager
            //empty criteria searches through all providers and returns the best one
            String providerName = manager.getBestProvider(new Criteria(), true);
            Location location = manager.getLastKnownLocation(providerName);

            TextView tv = (TextView)findViewById(R.id.locationResults);
            if (location != null) {
                tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
            } else
            {
                tv.setText("Last known location not found. Waiting for updated location...");
            }

            manager.requestLocationUpdates(providerName, 1000*60*30 , 1 , this);
        }
    }
}

    @Override
    public void onLocationChanged(Location location) {
        TextView tv = (TextView)findViewById(R.id.locationResults);
        if (location != null) {
            tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
          // I have added this line
          appendData ( location.getLatitude() + " latitude, " + location.getLongitude() + " longitude" );
        } else {
            tv.setText("Problem getting gps NETWORK ID : " + "");
        }
    }

    @Override
    public void onProviderDisabled(String arg0) {}

    @Override
    public void onProviderEnabled(String arg0) {}

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}

    // Find the closest Bart Station
    public String findClosestBart(Location loc) {
        double lat = loc.getLatitude();
        double lon = loc.getLongitude();

        double curStatLat = 0;
        double curStatLon = 0;
        double shortestDistSoFar = Double.POSITIVE_INFINITY;
        double curDist;
        String curStat = null;
        String closestStat = null;

        //sort through all the stations
        // write some sort of for loop using the API.

        curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
                        ((lon - curStatLon) * (lon - curStatLon)) );
        if (curDist < shortestDistSoFar) {
            closestStat = curStat;
        }

        return closestStat;

        }   
     // method to write in file 
public void appendData(String text)
{       
   File dataFile = new File(Environment.getExternalStorageDirectory() + "/GpsData.txt");
   if (!dataFile.exists())
   {
      try
      {
         dataFile.createNewFile();
      } 
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   try
   {
      //BufferedWriter for performance, true to set append to file flag
      BufferedWriter buf = new BufferedWriter(new FileWriter(dataFile, true)); 
      SimpleDateFormat sdf = new SimpleDateFormat("HH:mm, dd/MM/yyyy");
      String currentDateandTime = sdf.format(new Date());
    //  text+=","+currentDateandTime;      
      buf.append(text + "," + currentDateandTime);
      buf.newLine();
      buf.close();
   }
   catch (IOException e)
   {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
}
}

1 个答案:

答案 0 :(得分:2)

1.扩展服务类而不是Activity类和
2.将您的代码放入oncreate()
3.将您的服务加入到manefest中 4.来自活动的服务一次就像

         Intent service = new Intent(context, localService.class);
         context.startService(service); 

关注this tutorial.