0

主活动.java

    package com.example.background_shake;

import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;


public class MainActivity extends Activity implements OnClickListener {
    Button ON,OFF;
private SensorManager sensorManager;
private long lastUpdate;

Intent i1;
public static final String TAG = "ServicesDemo";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    //reseting the window propertys
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //super method
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ON=(Button)findViewById(R.id.ON);
    OFF=(Button)findViewById(R.id.OFF);
    ON.setOnClickListener(this);
    OFF.setOnClickListener(this);
}
public void onClick(View src) {
    switch (src.getId()) {
    case R.id.ON:
      Log.d(TAG, "onClick: starting srvice");
      startService(new Intent(this, Background_service.class));
      break;
    case R.id.OFF:
      Log.d(TAG, "onClick: stopping srvice");
      stopService(new Intent(this, Background_service.class));
      break;
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
  }

背景服务.java

    package com.example.background_shake;

import java.util.List;
import java.util.Locale;
import android.app.Service;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Address;
import android.location.Geocoder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class Background_service extends Service implements SensorEventListener{
    boolean flag=false;
    private long lastUpdate;
    SensorManager sensorManager;
            int count=0;
@Override
public IBinder onBind(Intent intent) {

    return null;
}
public void onCreate()
{
    flag=true;
    Log.d(MainActivity.TAG, "onCreate");
    super.onCreate();

}
public void onDestroy() {

    flag=false;
    Log.d(MainActivity.TAG, "onDestroy");
    super.onDestroy();

}
public void onStart(Intent intent, int startId)
{
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    sensorManager.registerListener(this,
            sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_NORMAL);
    lastUpdate = System.currentTimeMillis();
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {


}
private void getAccelerometer(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
    float[] values = event.values;
    // Movement
    float x = values[0];
    float y = values[1];
    float z = values[2];
    double latitude=0;
    double longitude=0;
    String location_message;
    GPSTracker gps;

    float accelationSquareRoot = (x * x + y * y + z * z)
        / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
    long actualTime = System.currentTimeMillis();
    if (accelationSquareRoot >= 2) //
    {
      if (actualTime - lastUpdate < 2000) {
            count++;
        return;
      }

      lastUpdate = actualTime;

      {
          gps=new GPSTracker(Background_service.this);
          if((gps.canGetLocation())&&(count==3)){
                      count=0;    
              latitude = gps.getLatitude();
              longitude = gps.getLongitude();
        //  \n is for new line
        //  Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();    
              Geocoder gcd = new Geocoder(Background_service.this, Locale.getDefault());
              try{
                  List<Address> addresses = gcd.getFromLocation(latitude, longitude, 1);
                  location_message= addresses.get(0).getLocality();
                  if ((addresses.size() > 0)&&(flag))
                  {
                      Toast.makeText(getApplicationContext(), "Your Location is " +addresses.get(0).getLocality()
                              , Toast.LENGTH_LONG).show();
                                      count=0;
                  }

              }catch(Exception e)
              {
                  System.out.print(e);
              }
          }else{
        //  can't get location
        //  GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        Toast.makeText(getApplicationContext(), "Switch on gps"
                , Toast.LENGTH_LONG).show();
        gps.showSettingsAlert();
    }}


      /*Toast.makeText(this, "Device was shuffed", Toast.LENGTH_SHORT)
          .show();
      if (color) {
        view.setBackgroundColor(Color.GREEN);

      } else {
        view.setBackgroundColor(Color.RED);
      }*/

    }}
  }
public void onSensorChanged(SensorEvent event) {

    getAccelerometer(event);


}
protected void onResume() {
    //super.onResume();
    // register this class as a listener for the orientation and
    // accelerometer sensors
            sensorManager.registerListener(this,
            sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_NORMAL);
}

protected void onPause()
{
    // unregister listener
    sensorManager.unregisterListener(this);

}

}

上面的代码适用于一个应用程序,它可以感知摇动参数并为您提供当前位置。但问题是即使我的 GPS 已关闭,我仍在获取当前位置。

另外我想知道两件事 1. 即使您锁定了手机,服务是否有效?如果没有,必须对我的代码进行哪些修改才能使其正常工作?2. 如果我摇动我的手机一次,我的应用程序会给出输出,但我希望我的应用程序只有在我连续摇动它 3-4 次时才能给出所需的结果。可以这样做吗?

4

2 回答 2

3

回答您的问题: 1. 即使您锁定了手机,服务是否有效?如果没有,必须对我的代码进行哪些修改才能使其有效?

是的,一旦服务启动,它将继续无限运行,但是如果手机已关闭并且您希望服务在手机启动后立即启动,您可以尝试创建一个在启动时触发的广播接收器

public class Broadcastreceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent startSMSServiceIntent = new Intent(context, SOMEservice.class);
        context.startService(startSMSServiceIntent);
    }
}

在清单中

<receiver android:name=".Broadcastreceiver">             
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />  
    </intent-filter>         
</receiver>

不要忘记权限

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
于 2013-03-19T06:17:45.590 回答
0

akajaymo 已经在此处回答了 Q1。

对于第二季度,不是让应用程序在每次摇晃手机时都产生所需的输出,而是创建两个静态变量int countlong last.

每次摇晃手机时,您都会检查是否(System.currentTimeMillis() - last) < 1000/* considering the shakes are not more than 1 second apart */,如果是,则增加计数。

如果count达到 3 或 4,你就完成了:只需产生所需的输出。如果没有,则什么也不生产。

如果抖动间隔超过 1000 毫秒,只需设置count为 1。

此外,每次检测到抖动时,请last = System.currentTimeMillis(). 最后的更新必须在我提到的第一次检查之后完成。

于 2013-03-19T09:51:54.700 回答