0

アプリケーションをアクティビティとサービスの両方として実行するにはどうすればよいですか。私はたくさん検索しましたが、解決策を見つけることができませんでした。誰でも方法を教えてもらえますか。私はこれを試しましたが、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();
   }
}
}
4

2 に答える 2