首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Web服务连接Estimote信标

用Web服务连接Estimote信标
EN

Stack Overflow用户
提问于 2016-02-23 12:37:41
回答 1查看 82关注 0票数 0

我是Android新手,我正在尝试使用Estimote Beacons构建一个android应用程序。我想从web服务获得动态通知。为此,我在Android应用程序类中添加了网络调用,这样它就可以在后台连续调用。我面临的问题是,网络调用有时会触发,有时不会。从Application类进行网络调用是一种礼仪吗?我该怎么做呢?下面我附上了Application类代码。

代码语言:javascript
复制
    public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private boolean beaconNotificationsEnabled = false;
SharedPreferences sharedPreferences;
Editor editor;
private RequestQueue mRequestQueue;
String uuid_beacon;
String displayNotification;
private BeaconManager beaconManager;
private static AppController mInstance;

String authLoginValue;
String displayMinorNO;
String uuid;
String majorno;
String minorno;
String notify;
String urlforimage;

@Override
public void onCreate() {
    super.onCreate();

    sharedPreferences = getApplicationContext().getSharedPreferences("Reg", 0);
    editor = sharedPreferences.edit();
    mInstance = this;
    authLoginValue = sharedPreferences.getString("AuthTokenLogin", "");
    System.out.println("LOGIN FROM APP CONTROLLER:"+authLoginValue);

    beaconManager = new BeaconManager(getApplicationContext());
    beaconManager.setMonitoringListener(new BeaconManager.MonitoringListener() {
        @Override
        public void onEnteredRegion(Region region, List<Beacon> list) {
            System.out.println("ENETERD");

            for (Beacon beacon : list) {
                uuid = beacon.getProximityUUID().toString();
                majorno = String.valueOf(beacon.getMajor());
                minorno = String.valueOf(beacon.getMinor());
                sendUUID(uuid, authLoginValue, majorno, minorno);

            }
            displayNotification = sharedPreferences.getString("Notification", "");

            showNotification(displayNotification, "Click here to continue");
        }
        @Override
        public void onExitedRegion(Region region) {
            // could add an "exit" notification too if you want (-:
            showNotification(
                    "THANKS FOR VISITING",
                    "Come back again"
            );
        }
    });
    beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
        @Override
        public void onServiceReady() {
            beaconManager.startMonitoring(new Region("monitored region",
                    UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FE6D"), null, null));
        }
    });

}
public static synchronized AppController getInstance() {
    return mInstance;
}
public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}

public void showNotification(String title, String message) {
    Intent notifyIntent = new Intent(this, MainActivity.class);
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivities(this, 0,
            new Intent[]{notifyIntent}, PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new Notification.Builder(this)
            .setSmallIcon(R.drawable.logo_7edge)
            .setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .build();
    notification.defaults |= Notification.DEFAULT_SOUND;
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, notification);
}

public void sendUUID(final String uuid, final String authTokenLoginValue,final String majorno, final String minorno) {

    // Tag used to cancel the request
    String tag_string_req = "req_register";

    StringRequest strReq = new StringRequest(Request.Method.POST,
            AppConfig.URL_UUID, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Notification Response: " + response.toString());
            try {
                JSONObject jObj = new JSONObject(response);
                String notifyresponse = jObj.getString("notification");

                JSONObject objecttonotify = new JSONObject(notifyresponse);

                notify = objecttonotify.getString("notification");
                urlforimage = objecttonotify.getString("url");

                System.out.println("URL:"+urlforimage);


                editor.putString("Notification", notify);
                editor.putString("image_url", urlforimage);
                editor.commit();


                Log.d(TAG, "Notification1" + notify);

                String msg =jObj.get("status").toString();



                if(msg.equals("ok"))
                {
                    String SuccessMsg = jObj.getString("message");
                    //Toast.makeText(getApplicationContext(), SuccessMsg, Toast.LENGTH_LONG).show();
                }
                else if(msg.equals("error")) {
                    String errorMsg = jObj.getString("message");
                    Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Notification Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("uuid", uuid);
            params.put("authtoken", authTokenLoginValue);
            params.put("major_no", majorno);
            params.put("minor_no", minorno);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
EN

回答 1

Stack Overflow用户

发布于 2016-05-15 16:59:44

如果你的代码像你所说的那样间歇性地成功进行网络调用,那么在我看来,根据你的web/服务器参数,代码似乎是正常工作的。因此,我假设通过截击进行连接的尝试是合理的。

但是,从您发布的代码来看,您没有指明您已检查设备是否已启用BT、已启用网络和Internet可用性。为了判断您的代码是否一致地工作,它的良好实践是,首先确保移动设备已启用BT、启用网络并可访问Internet。下面的代码片段适用于我。当然包括所有必要的用户权限:

蓝牙已启用:

代码语言:javascript
复制
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();

网络和互联网:

代码语言:javascript
复制
public static NetworkInfo getNetworkInfo(Context context){
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo();
}


//Check if there is any connectivity

public static boolean isConnected(Context context){
    NetworkInfo info = Utilities.getNetworkInfo(context);
    return (info != null && info.isConnected());
}


 // Check if there is any connectivity to a Wifi network

public static boolean isConnectedWifi(Context context){
    NetworkInfo info = Utilities.getNetworkInfo(context);
    return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}


// Check if there is any connectivity to a mobile network

public static boolean isConnectedMobile(Context context){
    NetworkInfo info = Utilities.getNetworkInfo(context);
    return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}

// TEST FOR INTERNET ACCESS / WEBSITE AVAILABLE

public static boolean isInternetOn() {

    String command = "ping -c1 -w3 google.com";

    // TODO progress bar while checking for internet.

    try {
        return (Runtime.getRuntime().exec(command).waitFor() == 0);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return false;
} //EO Internet ping

希望能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35568929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档