当前位置: 首页 > 知识库问答 >
问题:

为什么在没有Wi-Fi连接的情况下无法触发土墙?

宰子琪
2023-03-14
    public class sendLocation extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<Status> {
dbCreate dbcreate;
SQLiteDatabase db;

private String empId;
public static final float GEOFENCE_RADIUS_IN_METERS = 300;
protected ArrayList<Geofence> mGeofenceList;
protected GoogleApiClient mGoogleApiClient;
public static final HashMap<String, LatLng> LANDMARKS = new HashMap<String, LatLng>();
private ScheduledExecutorService scheduledExecutorService;
private String logUrl="https://abdulhalim.pythonanywhere.com/rams/default/get_att_log.json";
//private String logUrl="https://rumytechnologies.com/ramsm/default/get_att_log.json";
public String Tag="newtag";
private boolean myDeletePermission=false;
dbUnitSuper dbunit;
public String unitUri="https://abdulhalim.pythonanywhere.com/rams/default/getUnits.json?client_id=";
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
@Override
public void onCreate() {
    super.onCreate();
    //buildGoogleApiClient();
    mGoogleApiClient=new GoogleApiClient.Builder(getApplicationContext())
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();
    //dbcreate=dbCreate.getInstance(this);

     dbunit=dbUnitSuper.getInstance(sendLocation.this);
    empId=dbunit.readEmpId();
    mGeofenceList = new ArrayList<Geofence>();
   populateGeofenceList();
   Log.d(Tag,"populate geofencelist is called on oncreate of service");
    scheduledExecutorService = Executors.newScheduledThreadPool(1);
   scheduledExecutorService.scheduleWithFixedDelay(startSend,3,3,          TimeUnit.MINUTES);
}
    Runnable startSend=new Runnable() {
@Override
public void run() {
    Log.d(Tag,"runnable is running");
    //String[] projection={dbcreate.UNITID};
    //Cursor C=db.query(dbcreate.TB_name,projection,null,null,null,null,null);
    ArrayList<String> unitIds=new ArrayList<>();
    dbBufferSuper dbBuffer=dbBufferSuper.getInstance(sendLocation.this);
    unitIds=dbunit.readUnitIds();
    if(isOnLine())
    { for(int i=0;i<unitIds.size();i++) {
        String loopUnitID = unitIds.get(i);
        JSONObject unitJson = dbBuffer.readBufferLog(loopUnitID);
        if (unitJson != null) {
            sendLog send = new sendLog();
            send.execute(unitJson);
        } else {
            Log.d(Tag, "unitjson returns null for unit "+i);
        }
    }
    getUnitUpdate unitUpdate=new getUnitUpdate();
    unitUpdate.execute(empId);}

}
 };
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (!mGoogleApiClient.isConnecting() || !mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }
    return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
    super.onDestroy();
    if (mGoogleApiClient.isConnecting() || mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}
protected boolean isOnLine()
{
    ConnectivityManager cm= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo=cm.getActiveNetworkInfo();
    if(netInfo!=null&& netInfo.isConnectedOrConnecting())
    {
        return true;
    }
    else
    {
        return false;
    }
}
public void populateLandmark(){

    dbUnitSuper dbunit=dbUnitSuper.getInstance(this);
    ArrayList<ArrayList<String>> unitInfo=dbunit.readUnitInformation();
    if(unitInfo!=null) {
    for(int i=0;i<unitInfo.size();i++)
      {
ArrayList<String> singleUnit=unitInfo.get(i);
LANDMARKS.put(singleUnit.get(0),
            new LatLng(Float.parseFloat(singleUnit.get(1)),          Float.parseFloat(singleUnit.get(2))));}
}
}
public void populateGeofenceList() {
    populateLandmark();
    for (Map.Entry<String, LatLng> entry : LANDMARKS.entrySet()) {
        mGeofenceList.add(new Geofence.Builder()
                .setRequestId(entry.getKey())
                .setCircularRegion(
                        entry.getValue().latitude,
                        entry.getValue().longitude,
                        GEOFENCE_RADIUS_IN_METERS
                )
                .setExpirationDuration(Geofence.NEVER_EXPIRE)
                .setLoiteringDelay(15000)
                .setNotificationResponsiveness(30000)
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_DWELL)
                .build());

       }
    int i=mGeofenceList.size();
    Log.d(Tag,"number of geofences entered in the geofence list is "+i);
     }

@Override
public void onConnected(@Nullable Bundle bundle) {

    try {
        LocationServices.GeofencingApi.addGeofences(
                mGoogleApiClient,
                getGeofencingRequest(),
                getGeofencePendingIntent()
        ).setResultCallback(this); // Result processed in onResult().
    } catch (SecurityException securityException) {
        // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
        Log.d(Tag," securityException occured while adding in onconnected");
    }
}
@Override
public void onConnectionSuspended(int i) {
    mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
private GeofencingRequest getGeofencingRequest() {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_DWELL);
    builder.addGeofences(mGeofenceList);
    return builder.build();
}
private PendingIntent getGeofencePendingIntent() {
    Intent intent = new Intent(sendLocation.this, GeofenceTransitionsIntentService.class);
    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling addgeoFences()
    return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
public void onResult(@NonNull Status status) {
}
private class pollTask extends AsyncTask<String,Void,String>{
    @Override
    protected String doInBackground(String... params) {
        return null;
    }
}
private class getUnitUpdate extends AsyncTask<String,Void,String> implements ResultCallback<Status> {
    HttpsURLConnection https;
    @Override
    protected String doInBackground(String... params) {
        InputStreamReader inputStream = null;
        BufferedReader reader = null;
        StringBuilder newSb=new StringBuilder();
        newSb.append(unitUri);
        newSb.append(params[0]);
        try {
            URL url=new URL(newSb.toString());
           https=(HttpsURLConnection) url.openConnection();
            if(https==null)
            {Log.d(Tag,"urlconnection returns null");}
            https.setRequestMethod("GET");
            https.setDoInput(true);
            int status =https.getResponseCode();
            Log.d(Tag, "getunits Status : " + status);
            inputStream = new InputStreamReader(https.getInputStream());
            reader = new BufferedReader(inputStream);
            StringBuilder message = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                message.append(line);
            }
            return message.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            https.disconnect();
        }
        return null;
    }
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.d(Tag," updated units are"+s);
        try {
            JSONObject jsonRootObject=new JSONObject(s);
            JSONArray jsonlatArray=jsonRootObject.optJSONArray("Latitude");
            JSONArray jsonlonArray=jsonRootObject.optJSONArray("Longitude");
            JSONArray jsonuniArray=jsonRootObject.optJSONArray("Unit_Id");
            dbUnitSuper unitSuper=dbUnitSuper.getInstance(sendLocation.this);
            ArrayList<String> unitIds=unitSuper.readUnitIds();
            if(jsonuniArray.length()!=unitIds.size()){
                //String empId= unitSuper.readEmpId();
                //delete the rows in unit database
                int del=  unitSuper.deleteAllUnitInfo();
                Log.d(Tag,"number of deleted unit rows are"+del);
                //populate the unit database again
                for(int i=0;i<jsonlatArray.length();i++){
                    String unit_id=jsonuniArray.getString(i);
                    String latitude=jsonlatArray.getString(i);
                    String longitude=jsonlonArray.getString(i);
                    long intest=  unitSuper.insertData(empId,unit_id,latitude,longitude);
                    if(intest<0){
                        // Toast.makeText(MainActivity.this, "insert unsuccessful", Toast.LENGTH_LONG).show();
                        String rt=Integer.toString(i);
                        Log.d(Tag,"insert unsuccessful "+rt);
                    }
                    else{
                        // Toast.makeText(MainActivity.this, "successfully inserted a row", Toast.LENGTH_LONG).show();
                        String rt=Integer.toString(i);
                        Log.d(Tag,"successfully inserted a row "+rt);
                    }
                }
            /*remove geofences here
                removeGeofences();
                //clear mgeofencelist arraylist
                if(mGeofenceList.size()>0){
                    mGeofenceList.clear();
                }
                //recreate the geofences
                populateGeofenceList();*/
            }else{
                Log.d(Tag,"no new units are added or deleted");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /*if (!mGoogleApiClient.isConnecting() || !mGoogleApiClient.isConnected()) {
            Log.d(Tag," entered the if block to recreate the geofences");
            mGoogleApiClient.connect();
        }
        else {
            Log.d(Tag," entered the else block to recreate the geofences");
            try {
                Log.d(Tag," entered the try block to recreate the geofences");
                LocationServices.GeofencingApi.addGeofences(
                        mGoogleApiClient,
                        getGeofencingRequest(),
                        getGeofencePendingIntent()
                ).setResultCallback(this); // Result processed in onResult().
            } catch (SecurityException securityException) {
                // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
                Log.d(Tag,"sequrity exception occured at unit updaate while creating neew geofences");
            }
        }*/
    }
    @Override
    public void onResult(@NonNull com.google.android.gms.common.api.Status status) {
        Log.d(Tag,"geofences recreated successfully");
    }
}
private void removeGeofences(){
    LocationServices.GeofencingApi.removeGeofences(
            mGoogleApiClient,
            // This is the same pending intent that was used in addGeofences().
            getGeofencePendingIntent()
    ).setResultCallback(this); // Result processed in onResult().
}
private class sendLog extends AsyncTask<JSONObject,Void,String>{
    HttpsURLConnection https;
    String loopUnitID;
    @Override
    protected String doInBackground(JSONObject... params) {
        InputStreamReader inputStream = null;
        BufferedReader reader = null;
        JSONObject parseUnitIdJson=params[0];
        JSONObject rows=parseUnitIdJson.optJSONObject("Row");
        loopUnitID=rows.optString("unit_id");
        Log.d(Tag,"the unit id parsed in sendlog is "+loopUnitID);
        String postStr=String.format(params[0].toString());
        try {
            URL url=new URL(logUrl);
            https=(HttpsURLConnection) url.openConnection();
            https.setRequestMethod("POST");
            https.setDoInput(true);
            https.setDoOutput(true);
            OutputStreamWriter writer=new OutputStreamWriter(https.getOutputStream());
            writer.write(postStr);
            writer.flush();
            Log.d(Tag,"data flushed succesfully");
            int status =https.getResponseCode();
            Log.d(Tag, "Status : " + status);
            inputStream = new InputStreamReader(https.getInputStream());
            reader = new BufferedReader(inputStream);
            StringBuilder message = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                message.append(line);
            }
            Log.d(Tag,"sendLog returns"+message.toString());
            return message.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
           https.disconnect();
        }
        return null;
    }
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        try {
            dbBufferSuper dbBuffer=dbBufferSuper.getInstance(sendLocation.this);
            JSONObject sendResult=new JSONObject(s);
            JSONArray suck=sendResult.optJSONArray("result");
            Log.d(Tag,"the value read from result is "+suck.get(0));
            if(suck.get(0).equals("success")){
                Log.d(Tag,"permission granted for deleting a units log i");
                int status= dbBuffer.deleteRows(loopUnitID);
                if(status>0){
                    Log.d(Tag,"the number of affected rows in deletebufferrows is "+status);
                }
               // myDeletePermission=false;
                /*myDeletePermission=true;
                if(myDeletePermission==true){
                    Log.d(Tag,"delete permission is set to true");
                }else{
                    Log.d(Tag,"delete permission is still false after getting success");
                }*/
            }else {Log.d(Tag,"success is not extracted properly from the json response of sendlog");}
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d(Tag,"failed to instantiate getattlogs response as json" );
        }
    }
}
  }

共有1个答案

漆雕彦
2023-03-14

如果您的应用程序没有wifi连接,请确保您有可靠的数据连接,以便仍然可以使用Geofence。

正如您所拥有的文档中已经提到的,

如果没有可靠的数据连接,可能不会生成警报。这是因为geofence服务依赖于网络位置提供商,而网络位置提供商又需要数据连接。

此外,如果您喜欢关闭wifi,请使用SettingsApi确保设备的系统设置正确配置,以实现最佳位置检测。

还请查看SettingsAPI,其中提到,

当向位置服务发出请求时,设备的系统设置可能处于阻止应用程序获取所需位置数据的状态。例如,GPS或Wi-Fi扫描可以被关闭。

请尝试浏览给定的文档,您也可以选择查看这篇文章中的回复--我如何使用Android Geofencing API?。希望有帮助!

 类似资料:
  • 光环板连接Wi-Fi。 启用上传模式 点击启用上传模式。 连接网络 1. 添加事件类积木 当光环板启动时,Wi-Fi类积木 开始连接无线网络()密码(),输入附近Wi-Fi的名称和密码。 2. 网络连接成功后,我们需要一个信号来告诉我们网络连接成功。添加控制类积木 等待(),拖入Wi-Fi类积木 网络已连接?,添加灯光类积木 显示(),让灯环亮起指定图案。 下载代码

  • 当您将 M600 连上 Wi-Fi 网络后,您就可以使用 M600 上的 Google 应用程式商店来更新 Polar 应用程式并下载更多应用程式到您的 Wear OS by Google 智能手表上。 仅适用于与 Android 手机配对的 Polar M600 如果您的 M600 与手机蓝牙的连接断开,则它将自动连接到保存的 Wi-Fi 网络上。当 Android 手机已连接至 Wi-Fi 或

  • 我试图让一个Maven版本为一个Java项目工作,但有一点很有趣,我正在构建的机器没有也不可能访问Maven库。 我在尝试和运行的任何生命周期过程中遇到的错误是 无法对项目xxxxxx执行goal org . Apache . maven . plugins:maven-clean-Plugin:2.5:clean(default-clean):对goal org . Apache . maven

  • 我试着去看其他的代码例子,但是它们和我的代码比较相似,但是我的应用程序仍然会因为同样的错误而崩溃。 这是我使用firebase文档的指导方针编写的代码: 上面的代码正在将otp发送到给定的号码,但是它崩溃了,并且cat-log显示了上面提到的错误。

  • 1. 开始连接无线网络()密码() 连接到指定无线网络。 示例: 光环板启动后,开始连接到无线网络“Maker-guest”。 2. 网络已连接? 如果网络已连接,报告条件成立。 示例: 光环板启动后,开始连接到无线网络“Maker-guest”。等网络连接成功后,所有LED灯亮起绿色。 3. 识别()语音()秒钟 识别指定语言(汉语或英语)语音指定时间。 示例: 光环板启动后,识别汉语语音3秒钟

  • 问题内容: 有什么方法可以向连接到特定Wi-Fi网络的设备发送通知? 说,我有一个名为“我的Wi-Fi”的Wi-Fi网络,该网络不安全,任何人都可以连接。公共网络。 可能有N个用户连接到“我的Wi-Fi”。这些用户可以执行任何类型的交易,例如在线支付。 现在,如果我想关闭或关闭“我的Wi-Fi”路由器或接入点,这些交易可能会失败。 因此,在关闭之前,我想向连接到“我的Wi-Fi”网络的所有用户发送