android - 如何在后台运行android应用程序

标签 android

<分区>

Possible Duplicate:
how to run application in background in android?

如果我的位置纬度和经度等于数据库移动配置文件中的位置应进入静音模式,我正在使用位置管理器进行项目。所以我需要继续使用位置管理器更新我的位置。我做到了。但是如果我关闭我的应用程序,它就无法正常工作。 但是即使我关闭了我的应用程序,我的应用程序也应该可以工作。我尝试使用异步任务在我关闭应用程序时工作,但是在我手动切换到大声模式后它不会更改为静音。当我的应用程序在后台运行时我也应该得到通知..请提前帮助.tks

这是我的代码

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

最佳答案

你已经在Activity中编码了,我建议你把它改成Android Service .服务是在后台运行的组件,不与用户交互。

看看 Vogella 的 Service Example .

只需将您的 Activity 代码转换为 Android 服务,它将在后台运行而无需任何 GUI。

关于android - 如何在后台运行android应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12399170/

相关文章:

java - Firebase 用户通过 Google 注册

android - 我已经配对的蓝牙设备是否必须处于可发现模式才能扫描和查看?

android - android中ZXing和ZBar的解码速度

java - 创建一个每 x 秒执行一次的方法

android - SwipeRefresh 在 fragment 中不起作用?

android - 如何正确地将 kikoso 可刷卡从 github 导入到 Android studio?

android - 如何在monkeyrunner代码中运行外部程序?

java - 刷新 Activity 中的方法

android - 布局更改未反射(reflect)在应用程序中

java - SerializeObject.WriteSettings 在哪里写入文件? (小路)