I want to check whether internet connection is there or not in blackberry device so that depending on the result I can call webservices to get data or upload data from my application
I have tried this one
CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_MDS))) ||
(CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B)) != false
If you want to check the internet connection, then send any url to the web service and check the HTTP Response. If HTTPResponse is 200 then only you are having internet connection. Do like this.......
try
{
factory = new HttpConnectionFactory();
url="Here put any sample url or any of your web service to check network connection.";
httpConnection = factory.getHttpConnection(url);
response=httpConnection.getResponseCode();
if(response==HttpConnection.HTTP_OK)
{
callback(response);
}else
{
callback(response);
}
} catch (Exception e)
{
System.out.println(e.getMessage());
callback(0);
}
Here "response"=200 then you have an internet connection. otherwise it is a connection problem. You can check this like below...........
public void callback(int i)
{
if(i==200)
{
//You can do what ever you want.
}
else
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
int k=Dialog.ask(Dialog.D_OK,"Connection error,please check your network connection..");
if(k==Dialog.D_OK)
{
System.exit(0);
}
}
});
}
}
Here System.exit(0); exit the application where ever you are.
Take these two classes
1)HttpConnectionFactory.java
2)HttpConnectionFactoryException.java
from this link:HttpConnection Classes
Related
I am using paho library Classes for Mqtt Connections org.eclipse.paho.client.mqttv3.MqttClient. (not MqttAsyncClient)
In my case when I publish using
mqttClient.publish(uid + "/p", new MqttMessage(payload.toString().getBytes()));
This method does the task for me but doesn't return anything so I can't check the latency between publish and pubAck.
To get the latency I use the following instead of directly calling publish function of mqttClient.
public long publish(JsonObject payload , String uid, int qos) {
try {
MqttTopic topic = mqttClient.getTopic(uid + "/p");
MqttMessage message = new MqttMessage(payload.toString().getBytes());
message.setQos(qos);
message.setRetained(true);
long publishTime = System.currentTimeMillis();
MqttDeliveryToken token = topic.publish(message);
token.waitForCompletion(10000);
long pubCompleted = System.currentTimeMillis();
if (token.getResponse() != null && token.getResponse() instanceof MqttPubAck) {
return pubCompleted-publishTime;
}
return -1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
This gets the work done, but I am not sure whether this is the right approach or not. Please let me know in case there is some other way to to do this.
We decided to use mqtt protocol for chat module in our mobile application. I want to save messages of topic in server side also. But i saw,mqtt client is global here,so one way is i have to subscribe single instance of mqtt client to all topics and save messages in database. but is it right approach to do it. i am just worring about it.
private void buildClient(){
log.debug("Connecting... "+CLIENT_ID);
try {
mqttClient = new MqttClient(envConfiguration.getBrokerUrl(), CLIENT_ID);
} catch (MqttException e) {
log.debug("build client stopped due to "+e.getCause());
}
chatCallback = new ChatCallback();
mqttClient.setCallback(chatCallback);
mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(false);
}
#Override
public void connect() {
if(mqttClient == null || !mqttClient.getClientId().equals(CLIENT_ID)){
buildClient();
}
boolean tryConnecting = true;
while(tryConnecting){
try {
mqttClient.connect(mqttConnectOptions);
} catch (Exception e) {
log.debug("connection attempt failed "+ e.getCause() + " trying...");
}
if(mqttClient.isConnected()){
tryConnecting = false;
}else{
pause();
}
}
}
#Override
public void publish() {
boolean publishCallCompletedErrorFree = false;
while (!publishCallCompletedErrorFree) {
try {
mqttClient.publish(TOPIC, "hello".getBytes(), 1, true);
publishCallCompletedErrorFree = true;
} catch (Exception e) {
log.debug("error occured while publishing "+e.getCause());
}finally{
pause();
}
}
}
#Override
public void subscribe() {
if(mqttClient != null && mqttClient.isConnected()){
try {
mqttClient.subscribe(TOPIC, 2);
} catch (MqttException e) {
log.debug("subscribing error.."+e.getCause());
}
}
}
#Override
public void disconnect() {
System.out.println(this.mqttClient.isConnected());
try {
mqttClient.disconnect();
log.debug("disconnected..");
} catch (MqttException e) {
log.debug("erro occured while disconneting.."+e.getCause());
}
}
There are two possibilities how to solve this issue:
Write a MQTT client that subscribes to all topics using a wildcard (# in MQTT)
Write a broker plugin that does the job for you, depending on the broker implementation you're using
There is a good description of how to implement both options at the HiveMQ website, also describing limitations of the first option.
i would like to ask your help, this is my code :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==REQUEST_CODE_INPUT){
switch (resultCode){
case RESULT_CODE_PASS:
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager wifiManager= (WifiManager) getSystemService(Context.WIFI_SERVICE);
pass=data.getStringExtra("passWord");
nameWifi=data.getStringExtra("nameWifi");
WifiConfiguration conf=new WifiConfiguration();
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
List<ScanResult> networkList=wifiManager.getScanResults();
if(networkList !=null){
for(ScanResult network : networkList){
if(network.SSID.startsWith("\"")){
network.SSID=network.SSID.substring(1, network.SSID.length() - 1);
}
if(nameWifi.equals(network.SSID)){
String Capabilities=network.capabilities;
if(Capabilities.contains("WPA2")){
conf.preSharedKey="\""+pass+"\"";
}else if(Capabilities.contains("WEP")){
conf.wepKeys[0]="\""+pass+"\"";
conf.wepTxKeyIndex=0;
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
}
break;
}
}
}
wifiManager.addNetwork(conf);
List<WifiConfiguration> list=wifiManager.getConfiguredNetworks();
for(WifiConfiguration i: list){
if(i.SSID!=null && i.SSID.equals("\""+nameWifi+"\"")){
wifiManager.disconnect();
showWaiting();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
if(networkInfo.isConnected()){
dismissWaiting();
}else{
AlertDialog.Builder alert=new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Wrong Password")
.setMessage("Please try again")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.create().show();
}
}
}
break;
}
}
}
i have 2 Activities (MainActivity and ShareWifi), i create Sharewifi with purpose: users input wifi SSID and password then press Enter, both of them will send to MainActivity--> disable current wifi and reconnect with new password but it still uses old password to reconnect. I write this code follow this link : How do I connect to a specific Wi-Fi network in Android programmatically?
Please help me to resolve this problem. Thank you very much.
Resolved: add saveConfiguration and it works
wifiManager.addNetwork(conf);
wifiManager.saveConfiguration();
I am running a local server with xampp. I have some html files on it. I can run the files from my computer browser and from my iphone , my android phone and windows phone.
However when i try the BlackBerry i get the message :
HTTP Error 403: Forbidden . You are not authorized to view this page. Please try loading a different page.
If i press to view Details :
The following error was encountered while trying to retrieve the URL : myServersUrl
Access Denied
Access control configuration prevents your request from being allowed at this time. Please contact your service provider if you feel this is incorrect.
Now i was very careful to connect to the same wifi , as my computer that runs the server is connected , i type the ip correctly as i do to my other phones that i connect with no problem and i have my 3g closed so that i know it will use the wifi. Also i can open any page from the browser, that means i do have internet on the phone. BIS/BES are enabled.
Any idea why i cant connect on my local server here?
Some Code
I try to connect like this :
BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();
myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE,BrowserFieldConfig.NAVIGATION_MODE_POINTER);
BrowserField browserField = new BrowserField(myBrowserFieldConfig);
add(browserField);
//attaching the udid on the URL
browserField.requestContent("http://192.123.5.112/Server_CityInfo/jMobile.html?" + udid);
and
public static HttpConnection getHttpConnection(String url, byte[] postData) {
HttpConnection conn = null;
OutputStream out = null;
try {
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
if (conn != null) {
if (postData == null) {
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
} else {
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Length", String.valueOf(postData.length));
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
out = conn.openOutputStream();
out.write(postData);
out.flush();
}
if (conn.getResponseCode() != 0) {
return conn;
}
}
} catch (Exception e) {
} finally {
try {
out.close();
} catch (Exception e2) {
}
}
//Only if exception occurs, we close the connection.
//Otherwise the caller should close the connection himself.
try {
conn.close();
} catch (Exception e1) {
}
return null;
}
It would help if you included the relevant code from the BlackBerry app that sets up the connection. If you're not using the ConnectionFactory, you have to add appenders to make sure the connection is routed to the transport you are expecting. This is why including the code is helpful.
I tried to listen file change event in BlackBerry base on FileExplorer example, but whenever I added or deleted file, it always showed "Deferring persistence as device is being used" and I can't catch anything .Here is my code:
public class FileChangeListenner implements FileSystemJournalListener{
private long _lastUSN; // = 0;
public void fileJournalChanged() {
long nextUSN = FileSystemJournal.getNextUSN();
String msg = null;
for (long lookUSN = nextUSN - 1; lookUSN >= _lastUSN && msg == null; --lookUSN)
{
FileSystemJournalEntry entry = FileSystemJournal.getEntry(lookUSN);
// We didn't find an entry
if (entry == null)
{
break;
}
// Check if this entry was added or deleted
String path = entry.getPath();
if (path != null)
{
switch (entry.getEvent())
{
case FileSystemJournalEntry.FILE_ADDED:
msg = "File was added.";
break;
case FileSystemJournalEntry.FILE_DELETED:
msg = "File was deleted.";
break;
}
}
}
_lastUSN = nextUSN;
if ( msg != null )
{
System.out.println(msg);
}
}
}
Here is the caller:
Thread t = new Thread(new Runnable() {
public void run() {
new FileChangeListenner();
try {
Thread.sleep(5000);
createFile();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
Create file method worked fine:
private void createFile() {
try {
FileConnection fc = (FileConnection) Connector
.open("file:///SDCard/newfile.txt");
// If no exception is thrown, then the URI is valid, but the file
// may or may not exist.
if (!fc.exists()) {
fc.create(); // create the file if it doesn't exist
}
OutputStream outStream = fc.openOutputStream();
outStream.write("test content".getBytes());
outStream.close();
fc.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
and output:
0:00:44.475: Deferring persistence as device is being used.
0:00:46.475: AG,+CPT
0:00:46.477: AG,-CPT
0:00:54.476: VM:+GC(f)w=11
0:00:54.551: VM:-GCt=9,b=1,r=0,g=f,w=11,m=0
0:00:54.553: VM:QUOT t=1
0:00:54.554: VM:+CR
0:00:54.596: VM:-CR t=5
0:00:55.476: AM: Exit net_rim_bb_datatags(291)
0:00:55.478: Process net_rim_bb_datatags(291) cleanup started
0:00:55.479: VM:EVTOv=7680,w=20
0:00:55.480: Process net_rim_bb_datatags(291) cleanup done
0:00:55.481: 06/25 03:40:41.165 BBM FutureTask Execute: net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
0:00:55.487: 06/25 03:40:41.171 BBM FutureTask Finish : net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
I also tried to remove the thread or create or delete file in simulator 's sdcard directly but it doesn't help. Please tell me where is my problem. Thanks
You instantiate the FileChangeListenner, but you never register it, and also don't keep it as a variable anywhere. You probably need to add this call
FileChangeListenner listener = new FileChangeListenner();
UiApplication.getUiApplication().addFileSystemJournalListener(listener);
You also might need to keep a reference (listener) around for as long as you want to receive events. But maybe not (the addFileSystemJournalListener() call might do that). But, you at least need that call to addFileSystemJournalListener(), or you'll never get fileJournalChanged() called back.