如何在活动和服务android上运行应用程序?

时间:2013-05-04 02:47:48

标签: android service

如何将我的应用程序作为活动和服务运行。我搜索了很多,但我找不到解决方案。任何人都可以告诉我如何。我试过这个,它不适用于android 3.0及以上版本。

我需要将此代码作为应用程序和后台服务运行。这可能吗?

这是我的代码:

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();
   }
}
}

2 个答案:

答案 0 :(得分:1)

一个类不能同时是ActivityService,但Android应用程序肯定没有包含这两个类的问题。如果您需要在两者中运行相同的代码,只需将该公共代码抽象为公共类,然后从ActivityService调用该代码。

答案 1 :(得分:0)

当然可以。我认为您可以将Location Object实现为Singleton,然后在您的活动和服务中使用它。我就这样做了。 你看我的个人项目: http://code.google.com/p/wifi-map-with-nokia-here-api/source/browse/src/com/buptcoder/wifimap/location/Locator.java 此定位器由活动和服务使用。