2012-09-13 24 views
7

Eventuali duplicati:
how to run application in background in android?Come eseguire applicazioni Android in background

sto facendo progetto utilizzando location manager se la mia posizione di latitudine e longitudine pari alla stessa che è in mobili di database il profilo dovrebbe andare in modalità silenziosa. Quindi devo continuare ad aggiornare la mia posizione utilizzando il local manager. L'ho fatto. ma se chiudo la mia app non funziona. ma la mia app dovrebbe funzionare anche se chiudo la mia app.io ho provato con il task async quando ho chiuso l'app, ma dopo aver passato alla modalità loudly non cambia in silent.i devo anche ricevere una notifica quando la mia app viene eseguita n help.tks background..please di anticipo

ecco il mio codice

public class ShowLocationActivity extends Activity implements LocationListener { 
     private TextView latituteField; 
     private TextView longitudeField; 
     private LocationManager locationManager; 
     private String provider; 
     double lat,lng; 
     Location location; 
     AudioManager mobilemode ; 
     private Boolean flag = false; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.location); 
     latituteField = (TextView) findViewById(R.id.TextView02); 
     longitudeField = (TextView) findViewById(R.id.TextView04); 
     mobilemode = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE); 
     // Get the location manager 
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     // Define the criteria how to select the locatioin provider -> use 
     // default 
     Criteria criteria = new Criteria(); 
     provider = locationManager.getBestProvider(criteria, false); 
     location = locationManager.getLastKnownLocation(provider); 

     // Initialize the location fields 

     flag = displayGpsStatus(); 
     if (flag) { 

     if (location != null) { 
      System.out.println("Provider " + provider + " has been selected."); 
      onLocationChanged(location); 


      if((lat==12.905478)&&(lng==80.093358)) 
     { 
      mobilemode.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); 

      Toast.makeText(getBaseContext(),"VIBRATE profile activated ",Toast.LENGTH_SHORT).show(); 



     } 
     else if ((lat==12.90080625)&&(lng==80.09210655)) 
     { 
      mobilemode.setRingerMode(AudioManager.RINGER_MODE_SILENT); 





      Toast.makeText(getBaseContext(),"SILENT profile activated !",Toast.LENGTH_SHORT).show(); 
      //notification.setLatestEventInfo(ShowLocationActivity.this, "changed to silent mode", "because u r in office", pendingIntent); 
       // notificationManager.notify(i, notification); 
     } 
     else 
     { 
      mobilemode.setRingerMode(AudioManager.RINGER_MODE_NORMAL); 

      Toast.makeText(getBaseContext(),"LOUD profile activated !",Toast.LENGTH_SHORT).show(); 
     } 



     } 




     else { 
      latituteField.setText("Location not available"); 
      longitudeField.setText("Location not available"); 
     } 
    } 
     else { 
      alertbox("Gps Status!!", "Your GPS is: OFF"); 
     } 


    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.location, menu); 
     return true; 
    } 

    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle item selection 
     switch (item.getItemId()) { 
      case R.id.menu_settings: 
       Intent intent = new Intent(ShowLocationActivity.this,SetPreference.class); 
       startActivityForResult(intent, 0); 
       checkPref(); 
       return true; 

      default: 
       return super.onOptionsItemSelected(item); 
      } 








     } 

     private void checkPref(){ 

      SharedPreferences myPref 

      = PreferenceManager.getDefaultSharedPreferences(ShowLocationActivity.this); 

      String _pref = 

        "Option 1: " + myPref.getBoolean("pref_opt1", true); 


     } 



     @Override 

     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

      // TODO Auto-generated method stub 

      super.onActivityResult(requestCode, resultCode, data); 

      checkPref(); 

     } 
    @Override 
    public void onLocationChanged(Location location) { 
     // TODO Auto-generated method stub 
     lat = (double) (location.getLatitude()); 
     lng = (double) (location.getLongitude()); 
     latituteField.setText(String.valueOf(lat)); 
     longitudeField.setText(String.valueOf(lng)); 


    } 

    @Override 
    public void onProviderDisabled(String provider) { 
     // TODO Auto-generated method stub 
     Toast.makeText(this, "Disabled provider " + provider, 
        Toast.LENGTH_SHORT).show(); 

    } 

    @Override 
    public void onProviderEnabled(String provider) { 
     // TODO Auto-generated method stub 
     Toast.makeText(this, "Enabled new provider " + provider, 
       Toast.LENGTH_SHORT).show(); 

    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
     // TODO Auto-generated method stub 

    } 
    @Override 
    protected void onResume() { 
     super.onResume(); 
     locationManager.requestLocationUpdates(provider, 400, 1, this); 
     } 


     @Override 
     protected void onPause() { 
     super.onPause(); 
     locationManager.removeUpdates(this); 
     } 

     public void rrr(View v) 
     { 

      DownloadTask n= new DownloadTask(); 
      n.doInBackground(); 
     } 
     public void onDestroy() 
     { 
      super.onDestroy(); 
      Log.v("hhh","on destroy"); 
      DownloadTask n= new DownloadTask(); 
      n.doInBackground(); 
     } 

     public Boolean displayGpsStatus() { 
      ContentResolver contentResolver = getBaseContext().getContentResolver(); 
      boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(
        contentResolver, LocationManager.GPS_PROVIDER); 
      if (gpsStatus) { 
       return true; 

      } else { 
       return false; 
      } 
     } 

     /*----------Method to create an AlertBox ------------- */ 
     protected void alertbox(String title, String mymessage) { 
      AlertDialog.Builder builder = new AlertDialog.Builder(this); 
      builder.setMessage("Your Device's GPS is Disable") 
        .setCancelable(false) 
        .setTitle("** Gps Status **") 
        .setPositiveButton("Gps On", 
          new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, int id) { 
            // finish the current activity 
            // AlertBoxAdvance.this.finish(); 
            Intent myIntent = new Intent(
              Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
            startActivity(myIntent); 
            dialog.cancel(); 
           } 
          }) 
        .setNegativeButton("Cancel", 
          new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, int id) { 
            // cancel the dialog box 
            dialog.cancel(); 
           } 
          }); 
      AlertDialog alert = builder.create(); 
      alert.show(); 
     } 


    public class DownloadTask extends AsyncTask<Integer, Integer, Void> { 



     @Override 
     protected Void doInBackground(Integer... params) { 


      Log.v("hhh","back"); 
      onCreate(null); 
      // onLocationChanged(location); 
      /* 
      lat = (double) (location.getLatitude()); 
      lng = (double) (location.getLongitude()); 
      latituteField.setText(String.valueOf(lat)); 
      longitudeField.setText(String.valueOf(lng)); 

      if (location != null) { 
        System.out.println("Provider " + provider + " has been selected."); 
        onLocationChanged(location); 


        if((lat==12.905478)&&(lng==80.093358)) 
       { 
        mobilemode.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); 

        Toast.makeText(getBaseContext(),"VIBRATE profile activated ",Toast.LENGTH_SHORT).show(); 



       } 
       else if ((lat==12.90080625)&&(lng==80.09210655)) 
       { 
        mobilemode.setRingerMode(AudioManager.RINGER_MODE_SILENT); 





        Toast.makeText(getBaseContext(),"SILENT profile activated !",Toast.LENGTH_SHORT).show(); 
        //notification.setLatestEventInfo(ShowLocationActivity.this, "changed to silent mode", "because u r in office", pendingIntent); 
         // notificationManager.notify(i, notification); 
       } 
       else 
       { 
        mobilemode.setRingerMode(AudioManager.RINGER_MODE_NORMAL); 

        Toast.makeText(getBaseContext(),"LOUD profile activated !",Toast.LENGTH_SHORT).show(); 
       } 



       } 




       else { 
        latituteField.setText("Location not available"); 
        longitudeField.setText("Location not available"); 
       } 






      // TODO Auto-generated method stub 


     */ 
      return null; 
     } 
} 
} 
+3

Componente utente Android chiamato [Servizio] (http://developer.android.com/reference/android/app/Service.html) – Lucifer

+0

Questa domanda potrebbe rispondere a ciò che stai cercando http://stackoverflow.com/questions/5240246/broadcastreceiver-per-location –

risposta

11

Hai codificato in attività, vi consiglio di cambiato a Android Service. Un servizio è un componente che viene eseguito in background, senza interagire con l'utente.

Dai un'occhiata a Vogella's Service Example.

Basta convertire il codice attività in servizio Android e funzionerà in background senza alcuna GUI.

+1

Sì, il metodo di servizio funziona. Ma dovremmo anche utilizzare i ricevitori Broad Cast per inviare aggiornamenti sulla posizione dal servizio all'attività – Ruban

+1

anche se possono essere eseguiti anche in background. faccio lo stesso – Lucifer

Problemi correlati