gpt4 book ai didi

java - 当App后台震动方法不起作用时

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:46 27 4
gpt4 key购买 nike

我们正在尝试在android中实现摇动方法。如果我们关闭应用程序,它会使用服务在后台运行,在这种情况下,它会在后台运行,但不会使用传感器和加速度计来实现摇动方法。任何人都可以提供该服务的示例代码。请指导我们并告诉我们是否可能

 @Override
public void onShake(float force) {

if (location != null) {

onLocationChanged(location);
} else {
Toast.makeText(getBaseContext(), "No Location found!",
Toast.LENGTH_SHORT).show();
}


preferences = getApplicationContext().getSharedPreferences("prefs", Context.MODE_PRIVATE);
reg_email = preferences.getString("Emailid", "");
phone1 = preferences.getString("Phone1", "");
phone2 = preferences.getString("Phone2", "");
phone3 = preferences.getString("Phone3", "");

// token = preferences.getString("token", "");

StringRequest stringRequest1 = new StringRequest(Request.Method.POST, NOTIFICATION_EMAIL_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println("Response : " + response.toString());

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// your code to handle error or failure
// dismissDialog(DIALOG_LOADING);
// Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> mapParams = new HashMap<String, String>();
mapParams.put("EmailID", reg_email);
mapParams.put("PhoneNumber1", phone1);
mapParams.put("PhoneNumber2", phone2);
mapParams.put("PhoneNumber3", phone3);
mapParams.put("Latitude", String.valueOf((latitude)));
mapParams.put("Longitude", String.valueOf((longitude)));
mapParams.put("Address", Address);
//mapParams.put("TokenID", token);
return mapParams;
}
};
stringRequest1.setRetryPolicy(new DefaultRetryPolicy(15000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(stringRequest1);

}

最佳答案

创建ShakeEventListener类

class ShakeEventListener implements SensorEventListener {
@Override
public void onSensorChanged(SensorEvent event) {
handleShake(event); // see below
}

void handleShake(event) {
if (shake movement detected) {
//Do your process or event.
}
}
}

在您的服务 onCreate() 中向传感器管理器注册一个 this 监听器

public class ShakeHandleService extends Service {
@Override
public void onCreate() {
Log.i(TAG, "Service onCreate");

SensorManager sManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
sensor = sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sManager.registerListener(new ShakeEventListener(), sensor, SensorManager.SENSOR_DELAY_NORMAL); // or other delay
}
}

确保在启动 Activity 时调用 unregisterListener,否则您将不会在 Activity 中收到摇动事件。

关于java - 当App后台震动方法不起作用时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35331281/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com