Wifi Broadcastreceiver onreceive - android

I have problems with the wifi broadcast receiver. It doesn't receive anything, onReceive is never called. Here's my code:
public final class WifiChangeReceiver extends BroadcastReceiver {
boolean portableHotspot = true;
#Override
public void onReceive(final Context context, Intent intent) {
boolean alreadyPresent = false;
String action = intent.getAction();
if(action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
WifiManager w = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
List<ScanResult> l = w.getScanResults();
myApp myApp = (myApp)context.getApplicationContext();
List<ScanResult> previousScan = new ArrayList<ScanResult>();
previousScan = myApp.getPreviousScan();
System.out.print("previousScan " + previousScan + "\n");
for (ScanResult r : l) {
if(r.SSID.equals("\""+"TinyBox"+"\"")) {
if(previousScan!=null) {
for (ScanResult previousScanElement : previousScan) {
if(previousScanElement.SSID.contains("\""+"TinyBox"+"\"")) {
alreadyPresent = true;
break;
}
}
}
if (!alreadyPresent) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Methods.connectToNetwork(context);
}
}, 5000);
alreadyPresent = false;
}
}
}
myApp.setPreviousScan(l);
ConnectivityManager conMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo i = conMgr.getActiveNetworkInfo();
//Se non connesso a nessuna rete, allora tiro su TinyBox.
if (i == null) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i = conMgr.getActiveNetworkInfo();
if (i == null) {
boolean portableHotspot = false;
final SQLiteDatabase db = DatabaseManager.getInstance(context).getWritableDatabase();
Cursor c = HotSpotActivation.getHotSpotState(db);
if (c.getCount() > 0) {
String activation = c.getString(c.getColumnIndex(HotSpotActivation.CHECK_STATE));
if (activation.equals("ON")) {
portableHotspot = true;
}
else {
portableHotspot = false;
}
}
if (portableHotspot) {
Methods.setWirelessHotSpot(context.getApplicationContext());
}
}
}
else {
}
}
else if(action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
int iTemp = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN);
checkState(iTemp);
}
else if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
DetailedState state=
((NetworkInfo)intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO)).getDetailedState();
changeState(state, context);
}
}
private void changeState(DetailedState aState, Context context) {
if (aState == DetailedState.SCANNING) {
Log.d("wifiSupplicanState", "SCANNING");
}
else if (aState == DetailedState.CONNECTING) {
Log.d("wifiSupplicanState", "CONNECTING");
}
else if(aState == DetailedState.OBTAINING_IPADDR) {
Log.d("wifiSupplicanState", "OBTAINING_IPADDR");
}
else if (aState == DetailedState.CONNECTED) {
Log.d("wifiSupplicanState", "CONNECTED");
}
else if (aState == DetailedState.DISCONNECTING) {
Log.d("wifiSupplicanState", "DISCONNECTING");
}
else if (aState == DetailedState.DISCONNECTED) {
myApp myApp = (myApp)context.getApplicationContext();
portableHotspot = myApp.getPortableHotspot();
if (portableHotspot) {
Methods.setWirelessHotSpot(context.getApplicationContext());
}
}
else if (aState == DetailedState.FAILED) {
}
}
public void checkState(int aInt) {
if (aInt == WifiManager.WIFI_STATE_ENABLING) {
Log.d("WifiManager", "WIFI_STATE_ENABLING");
}
else if (aInt== WifiManager.WIFI_STATE_ENABLED) {
Log.d("WifiManager", "WIFI_STATE_ENABLED");
}
else if (aInt == WifiManager.WIFI_STATE_DISABLING) {
Log.d("WifiManager", "WIFI_STATE_DISABLING");
}
else if (aInt == WifiManager.WIFI_STATE_DISABLED) {
Log.d("WifiManager", "WIFI_STATE_DISABLED");
}
}
}
and the manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_SUPERUSER"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
<receiver android:name="sample.broadcastreceivers.WifiChangeReceiver">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"></action>
<action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE"></action>
<action android:name="android.net.wifi.STATE_CHANGE"></action>
<action android:name="android.net.wifi.SCAN_RESULTS"></action>
</intent-filter>
</receiver>
It works (on Receive is called) only if I go to the wifi settings menu, the one in which networks are listed, without pushing anything, just opening it. Immediatly after I enter that menu I start to receive from the broadcast receiver and all works fine, without any reason.
Where is the problem? It's like an Android bug. I'm quite sure the same code worked sometimes ago. Thanks

Check your AndroidManifest: you declare
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
?

Related

Detecting state changes using BroadcastReceiver is not working

I am trying to detect wifi, mobile data, bluetooth and location state changes using broadcastreceiver. this is how i do it:
StateChangeReceiver stateChangeReceiver = new StateChangeReceiver();
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
ConnectivityManager conManager = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
LocationManager locationManager = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
#Override
protected void onStart() {
super.onStart();
IntentFilter bluetooth = new IntentFilter(bluetoothAdapter.ACTION_STATE_CHANGED);
IntentFilter wifi = new IntentFilter(wifiManager.WIFI_STATE_CHANGED_ACTION);
IntentFilter gps = new IntentFilter(locationManager.PROVIDERS_CHANGED_ACTION);
IntentFilter data = new IntentFilter(conManager.CONNECTIVITY_ACTION);
registerReceiver(stateChangeReceiver, bluetooth);
registerReceiver(stateChangeReceiver, wifi);
registerReceiver(stateChangeReceiver , gps);
registerReceiver(stateChangeReceiver , data);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(stateChangeReceiver);
}
private class StateChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive (Context context, Intent intent) {
if (intent.getAction().equals(wifiManager.WIFI_STATE_CHANGED_ACTION)) {
WifiStateChanged(intent);
} else if(intent.getAction().equals(bluetoothAdapter.ACTION_STATE_CHANGED)) {
BluetoothStateChanged(intent);
} else if(intent.getAction().equals(locationManager.PROVIDERS_CHANGED_ACTION)) {
GpsSwitchStateChanged(context , intent);
} else if(intent.getAction().equals(conManager.CONNECTIVITY_ACTION)) {
DataStateChanged(intent);
}
}
};
private void WifiStateChanged (Intent intent){
int wifiStateExtra = intent.getIntExtra(wifiManager.EXTRA_WIFI_STATE, wifiManager.WIFI_STATE_UNKNOWN);
if (wifiStateExtra == wifiManager.WIFI_STATE_ENABLED)
((ImageView) launcher.findViewById(R.id.wifi_button)).setImageResource(R.drawable.ic_wifi_orange_24dp);
else if (wifiStateExtra == wifiManager.WIFI_STATE_DISABLED)
((ImageView) launcher.findViewById(R.id.wifi_button)).setImageResource(R.drawable.ic_wifi_white_24dp);
};
private void DataStateChanged (Intent intent) {
NetworkInfo netInfo = conManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_MOBILE)
((ImageView) launcher.findViewById(R.id.data_button)).setImageResource(R.drawable.ic_data_orange_24dp);
else
((ImageView) launcher.findViewById(R.id.data_button)).setImageResource(R.drawable.ic_data_white_24dp);
};
private void BluetoothStateChanged (Intent intent){
String action = intent.getAction();
if (bluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
if(intent.getIntExtra(bluetoothAdapter.EXTRA_STATE, -1) == bluetoothAdapter.STATE_ON)
((ImageView) launcher.findViewById(R.id.bluetooth_button)).setImageResource(R.drawable.ic_bluetooth_orange_24dp);
else if(intent.getIntExtra(bluetoothAdapter.EXTRA_STATE, -1) == bluetoothAdapter.STATE_OFF)
((ImageView) launcher.findViewById(R.id.bluetooth_button)).setImageResource(R.drawable.ic_bluetooth_white_64dp);
}
};
private void GpsSwitchStateChanged (Context context,Intent intent){
int locationMode=0;
try
{
locationMode = android.provider.Settings.Secure.getInt(context.getContentResolver(), android.provider.Settings.Secure.LOCATION_MODE);
} catch (android.provider.Settings.SettingNotFoundException e)
{
e.printStackTrace();
}
if (locationMode == android.provider.Settings.Secure.LOCATION_MODE_SENSORS_ONLY
|| locationMode == android.provider.Settings.Secure.LOCATION_MODE_HIGH_ACCURACY
||locationMode == android.provider.Settings.Secure.LOCATION_MODE_BATTERY_SAVING )
((ImageView) launcher.findViewById(R.id.location_button)).setImageResource(R.drawable.ic_location_orange_24dp);
else if (locationMode == android.provider.Settings.Secure.LOCATION_MODE_OFF) {
((ImageView) launcher.findViewById(R.id.location_button)).setImageResource(R.drawable.ic_location_white_24dp);
}
};
I also added permission that i though was needed:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
But the only changes that are tracking is wifi state changes and the rest doesn't fire the StateChangeReceiver. I am pretty confused why it's not working?
Try registering only one BroadcastReceiver with an unique IntentFilter with all actions. For example:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(bluetoothAdapter.ACTION_STATE_CHANGED);
intentFilter.addAction(wifiManager.WIFI_STATE_CHANGED_ACTION);
intentFilter.addAction(locationManager.PROVIDERS_CHANGED_ACTION);
intentFilter.addAction(conManager.CONNECTIVITY_ACTION);
registerReceiver(stateChangeReceiver, intentFilter);
With this way you simulate a declaration of BroadcastReceiver like in Manifest:
<receiver
android:name="YourReceiver">
<intent-filter>
<action android:name="action1"/>
<action android:name="action2"/>
</intent-filter>
</receiver>
Another solution is to create one BroadcastReceiver for each action, as I see you have one method for each action to parse it. It't not crazy to create 4 BroadcastReceivers and do the logic of each action inside its BroadcastReceiver.
You are calling registerReceiver multiple times which cause only last line to execute try using
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
intentFilter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
intentFilter.addAction(ConnectionManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, intentFilter);
You can listen actions in only one receiver and can extract as per action
eg:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
.....
} else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
...
}
}
};

Onesignal Push notifications is delivered But not receaved by any device

Hello i am using onesignal push notifications in my android.
I am trying to send some push notifications for test the message but after sending push notifications i cannot get any notifications but onsignal show's that message is delivered.
Here is build.gradle
I am using Onesignal jar sdk because i didn't have pc so i cannot use Studio i am using Aide Ide to build my app.
android {
compileSdkVersion 26
buildToolsVersion '26.0.1'
defaultConfig {
applicationId "com.mytest.test"
// TODO: Please update the OneSignal ID below to yours!
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
manifestPlaceholders = [onesignal_app_id: "",
// Project number pulled from dashboard, local value is ignored.
onesignal_google_project_number: "REMOTE"]
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// OneSignal requires at least version 7.0.0 of GMS but the newest version is recommend.
// Required for OneSignal, even if you have added FCM.
compile 'com.google.android.gms:play-services-gcm:8.1.0'
compile 'com.android.support:palette-v7:23.1.1'
// Required for geotagging
compile 'com.google.android.gms:play-services-location:8.1.0'
// play-services-analytics is only needed when using 8.1.0 or older.
compile 'com.google.android.gms:play-services-analytics:8.1.0'
//noinspection GradleCompatible
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile files('libs/OneSignalSDK.jar')
}
MyApplication.java
public class MyApplication extends Application {
#Override public void onCreate() { super.onCreate();
OneSignal.startInit(this) .setNotificationOpenedHandler(new ExampleNotificationOpenedHandler()) .init(); }
// Fires when a notificaiton is opened by tapping on it or one is received while the app is runnning. private class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler { // This fires when a notification is opened by tapping on it. #Override public void notificationOpened(OSNotificationOpenResult result) { OSNotificationAction.ActionType actionType = result.action.type; OneSignal.setInFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification);
JSONObject data = result.notification.payload.additionalData; String launchUrl = result.notification.payload.launchURL; // update docs launchUrl
String customKey; String openURL = null; Object activityToLaunch = MainActivity.class;
if (data != null) {
customKey = data.optString("customkey", null);
openURL = data.optString("openURL", null);
if (customKey != null)
Log.i("hitpush", "customkey set with value: " + customKey);
if (openURL != null)
Log.i("hitpush", "openURL to webview with URL value: " + openURL); }
if (actionType == OSNotificationAction.ActionType.ActionTaken) {
Log.i("hitpush", "Button pressed with id: " + result.action.actionID);
if (result.action.actionID.equals("id1")) {
Log.i("hitpush", "button id called: " + result.action.actionID);
activityToLaunch = MainActivity.class;
} else {
Log.i("hitpush", "button id called: " + result.action.actionID);
}
} // The following can be used to open an Activity of your choice. // Replace - getApplicationContext() - with any Android Context. // Intent intent = new Intent(getApplicationContext(), YourActivity.class); Intent intent = new Intent(getApplicationContext(), (Class<?>) activityToLaunch); // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("openURL", openURL); Log.i("hitpush", "openURL = " + openURL); // startActivity(intent); startActivity(intent);
// Add the following to your AndroidManifest.xml to prevent the launching of your main Activity // if you are calling startActivity above. /*
<application ...>
<meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" />
</application>
*/
} }
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<!-- All OneSignal manifest entries are added for you automatically from the OneSignal aar gradle entry. -->
<!-- Optional permission, needed for geo tagging feature. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:name=".MyApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<!-- Disbale opening of launcher Activity -->
<meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" />
<service
android:name=".MyNotificationExtenderService"
android:exported="false">
<intent-filter>
<action android:name="com.onesignal.NotificationExtender" />
</intent-filter>
</service>
<!-- Disable Badges -->
<!-- <meta-data android:name="com.onesignal.BadgeCount" android:value="DISABLE" /> -->
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="onesignal_app_id"
android:value="" />
<meta-data
android:name="onesignal_google_project_number"
android:value="" />
</application>
I am using meta-data for onsignal app id and project number afterthat onsignal recognise my app.
MainActivity.java
private static Activity currentActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView)findViewById(R.id.debug_view);
textView.setText("OneSignal is Ready!");
Button onSendTagsButton = (Button)(findViewById(R.id.send_tags_button));
onSendTagsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
JSONObject tags = new JSONObject();
try {
tags.put("key1", "value1");
tags.put("user_name", "Jon");
} catch (JSONException e) {
e.printStackTrace();
}
OneSignal.sendTags(tags);
textView.setText("Tags sent!");
}
});
Button onGetTagsButton = (Button)(findViewById(R.id.get_tags_button));
onGetTagsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Collection<String> receivedTags = new ArrayList<String>();
OneSignal.getTags(new OneSignal.GetTagsHandler() {
#Override
public void tagsAvailable(final JSONObject tags) {
Log.d("debug", tags.toString());
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
receivedTags.add(tags.toString());
textView.setText("Tags Received: " + receivedTags);
}
});
}
});
}
});
Button onDeleteOrUpdateTagsButton = (Button)(findViewById(R.id.delete_update_tags_button));
onDeleteOrUpdateTagsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OneSignal.getTags(new OneSignal.GetTagsHandler() {
#Override
public void tagsAvailable(final JSONObject tags) {
Log.d("debug", "Current Tags on User: " + tags.toString());
OneSignal.deleteTag("key1");
OneSignal.sendTag("updated_key", "updated_value");
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
textView.setText("Updated Tags: " + tags.toString());
}
});
}
});
}
});
Button onGetIDsAvailableButton = (Button)(findViewById(R.id.get_ids_available_button));
onGetIDsAvailableButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState();
boolean isEnabled = status.getPermissionStatus().getEnabled();
boolean isSubscribed = status.getSubscriptionStatus().getSubscribed();
boolean subscriptionSetting = status.getSubscriptionStatus().getUserSubscriptionSetting();
String userID = status.getSubscriptionStatus().getUserId();
String pushToken = status.getSubscriptionStatus().getPushToken();
textView.setText("PlayerID: " + userID + "\nPushToken: " + pushToken);
}
});
Button onPromptLocationButton = (Button)(findViewById(R.id.prompt_location_button));
onPromptLocationButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
OneSignal.promptLocation();
/*
Make sure you have one of the following permissions in your AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
*/
}
});
Button onSendNotification1 = (Button)(findViewById(R.id.send_notification_button));
onSendNotification1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState();
String userId = status.getSubscriptionStatus().getUserId();
String pushToken = status.getSubscriptionStatus().getPushToken();
boolean isSubscribed = status.getSubscriptionStatus().getSubscribed();
if (isSubscribed) {
textView.setText("Subscription Status, is subscribed:" + isSubscribed);
try {
JSONObject notificationContent = new JSONObject("{'contents': {'en': 'The notification message or body'}," +
"'include_player_ids': ['" + userId + "'], " +
"'headings': {'en': 'Notification Title'}, " +
"'big_picture': 'http://i.imgur.com/DKw1J2F.gif'}");
OneSignal.postNotification(notificationContent, null);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Button onSendNotification2 = (Button)(findViewById(R.id.send_notification_button2));
onSendNotification2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState();
String userID = status.getSubscriptionStatus().getUserId();
String pushToken = status.getSubscriptionStatus().getPushToken();
boolean isSubscribed = status.getSubscriptionStatus().getSubscribed();
if (isSubscribed) {
textView.setText("Subscription Status, is subscribed:" + isSubscribed);
try {
OneSignal.postNotification(new JSONObject("{'contents': {'en':'Tag substitution value for key1 = {{key1}}'}, " +
"'include_player_ids': ['" + userID + "'], " +
"'headings': {'en': 'Tag sub Title HI {{user_name}}'}, " +
"'data': {'openURL': 'https://imgur.com'}," +
"'buttons':[{'id': 'id1', 'text': 'Go to GreenActivity'}, {'id':'id2', 'text': 'Go to MainActivity'}]}"),
new OneSignal.PostNotificationResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Log.i("OneSignalExample", "postNotification Success: " + response.toString());
}
#Override
public void onFailure(JSONObject response) {
Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
final Switch onSetSubscriptionSwitch = (Switch)(findViewById(R.id.set_subscription_switch));
onSetSubscriptionSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (onSetSubscriptionSwitch.isChecked()) {
OneSignal.setSubscription(true);
textView.setText("User CAN receive notifications if turned on in Phone Settings");
}
else {
OneSignal.setSubscription(false);
textView.setText("User CANNOT receive notifications, even if they are turned on in Phone Settings");
}
}
});
}
Anyone find any error in this code ?
Why i cannot get any notifications even onesignal delivered the notifications to my app?
I am sure that you forget some permissions that onesignal need to receive notifications.
Try this
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.mytest.test.permission.C2D_MESSAGE" />
<uses-permission android:name="com.sec.android.provider.badge.permission.READ" />
<uses-permission android:name="com.sec.android.provider.badge.permission.WRITE" />
<uses-permission android:name="com.htc.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.htc.launcher.permission.UPDATE_SHORTCUT" />
<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />
<uses-permission android:name="com.sonymobile.home.permission.PROVIDER_INSERT_BADGE" />
<uses-permission android:name="com.anddoes.launcher.permission.UPDATE_COUNT" />
<uses-permission android:name="com.majeur.launcher.permission.UPDATE_BADGE" />
<uses-permission android:name="com.huawei.android.launcher.permission.CHANGE_BADGE" />
<uses-permission android:name="com.huawei.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.huawei.android.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.READ_APP_BADGE" />
<uses-permission android:name="com.oppo.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.oppo.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="me.everything.badger.permission.BADGE_COUNT_READ" />
<uses-permission android:name="me.everything.badger.permission.BADGE_COUNT_WRITE" />
<receiver android:name="com.onesignal.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter android:priority="999">
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.mytest.test" />
</intent-filter>
</receiver>
<receiver android:name="com.onesignal.NotificationOpenedReceiver" />
<service android:name="com.onesignal.GcmIntentService" />
<service android:name="com.onesignal.GcmIntentJobService" android:permission="android.permission.BIND_JOB_SERVICE" />
<service android:name="com.onesignal.SyncService" />
<activity android:theme="#*android:style/Theme.Translucent.NoTitleBar" android:name="com.onesignal.PermissionsActivity" />
<service android:name="com.onesignal.NotificationRestoreService" />
<service android:name="com.onesignal.NotificationRestoreJobService" android:permission="android.permission.BIND_JOB_SERVICE" />
<receiver android:name="com.onesignal.BootUpReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<receiver android:name="com.onesignal.UpgradeReceiver">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
YourApplication.java
public class YourApplication extends Application
{
public void onCreate() {
super.onCreate();
OneSignal.setLogLevel(LOG_LEVEL.DEBUG, LOG_LEVEL.WARN);
OneSignal.startInit(this).setNotificationOpenedHandler(new ExampleNotificationOpenedHandler()).autoPromptLocation(true).init();
}
private class ExampleNotificationOpenedHandler implements NotificationOpenedHandler {
private ExampleNotificationOpenedHandler() {
}
public void notificationOpened(OSNotificationOpenResult result) {
ActionType actionType = result.action.type;
JSONObject data = result.notification.payload.additionalData;
if (data != null) {
String customKey = data.optString("customkey", null);
if (customKey != null) {
Log.i("OneSignalExample", "customkey set with value: " + customKey);
}
}
if (actionType == ActionType.ActionTaken) {
Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);
}
}
}
}
I am very sure now you receive notifications.

Epson printer connect fails status ERR_CONN

I have an Epson printer and I used epos2_printer (sample project) code given with SDK to integrate with my app. I have copied the same code but it never seems to work!
However, the same works when I connect the sample project to my printer.
private boolean runPrintReceiptSequence() {
if (!initializeObject()) {
return false;
}
if (!createReceiptData()) {
finalizeObject();
return false;
}
if (!printData()) {
finalizeObject();
return false;
}
return true;
}
private boolean initializeObject() {
try {
final SpnModelsItem spnModel = new SpnModelsItem("TM-T82 Series", Printer.TM_T82);
final SpnModelsItem spnLang = new SpnModelsItem("ANK", Printer.MODEL_ANK);
mPrinter = new Printer(spnModel.getModelConstant(),
spnLang.getModelConstant(), this);
}
catch (Exception e) {
Log.e("Printer", e.toString());
return false;
}
mPrinter.setReceiveEventListener(this);
return true;
}
private boolean createReceiptData() {
String method = "";
Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.logo_saltnpepper);
StringBuilder textData = new StringBuilder();
final int barcodeWidth = 2;
final int barcodeHeight = 100;
Date currentDate = new Date();
info.saltnpepper.ordersmart2.MenuItem currItem = null;
double price = 0;
double total = 0;
int totalQty =0;
if (mPrinter == null) {
return false;
}
try {
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_CENTER);
method = "addImage";
mPrinter.addImage(logoData, 0, 0,
logoData.getWidth(),
logoData.getHeight(),
Printer.COLOR_1,
Printer.MODE_MONO,
Printer.HALFTONE_DITHER,
Printer.PARAM_DEFAULT,
Printer.COMPRESS_AUTO);
method = "addFeedLine";
mPrinter.addFeedLine(1);
textData.append("SALT-N-PEPPER\n");
//textData.append("STORE DIRECTOR – John Smith\n");
textData.append("\n");
textData.append((new SimpleDateFormat("dd/MM/yy HH:mm:ss")).format(currentDate).toString() + "\n");
//textData.append("ST# 21 OP# 001 TE# 01 TR# 747\n");
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
if(alFinalOrder != null)
{
for(int i=0; i < alFinalOrder.size(); i++)
{
currItem = alFinalOrder.get(i);
textData.append(currItem.getName()+" "+currItem.getQty()+" "+currItem.getPrice()+"\n");
//calculate total quantity
totalQty = totalQty + currItem.getQty();
//calculate price
double dPrice = currItem.getQty()*Double.parseDouble(currItem.getPrice().substring(1));
total = total + dPrice;
total = Math.round(total*100.0)/100.0;
}
}
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
textData.append("TOTAL "+"\n");
textData.append("TAX "+"\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
mPrinter.addFeedLine(2);
method = "addBarcode";
mPrinter.addBarcode("01209457",
Printer.BARCODE_CODE39,
Printer.HRI_BELOW,
Printer.FONT_A,
barcodeWidth,
barcodeHeight);
method = "addCut";
mPrinter.addCut(Printer.CUT_FEED);
}
catch (Exception e) {
//ShowMsg.showException(e, method, mContext);
return false;
}
textData = null;
return true;
}
private boolean printData() {
if (mPrinter == null) {
return false;
}
if (!connectPrinter()) {
return false;
}
PrinterStatusInfo status = mPrinter.getStatus();
dispPrinterWarnings(status);
if (!isPrintable(status)) {
Log.e("Printer", "Is not printable");
try {
mPrinter.disconnect();
}
catch (Exception ex) {
// Do nothing
}
return false;
}
try {
mPrinter.sendData(Printer.PARAM_DEFAULT);
}
catch (Exception e) {
Log.e("Printer", e.getMessage());
try {
mPrinter.disconnect();
}
catch (Exception ex) {
// Do nothing
}
return false;
}
return true;
}
private boolean connectPrinter() {
boolean isBeginTransaction = false;
if (mPrinter == null) {
return false;
}
try {
mPrinter.connect("TCP:"+mIP, Printer.PARAM_DEFAULT);
}
catch (Epos2Exception e) {
//ShowMsg.showException(e, "connect", this);
if(e.getErrorStatus() == Epos2Exception.ERR_CONNECT)
{
Log.e("testing", "error connect");
}
if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_OPENED)
{
Log.e("testing", "already open");
}
if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_USED)
{
Log.e("testing", "already used");
}
if(e.getErrorStatus() == Epos2Exception.ERR_BOX_CLIENT_OVER)
{
Log.e("testing", "box client over");
}
if(e.getErrorStatus() == Epos2Exception.ERR_BOX_COUNT_OVER)
{
Log.e("testing", "count over");
}
if(e.getErrorStatus() == Epos2Exception.ERR_DISCONNECT)
{
Log.e("testing", "disconnect");
}
if(e.getErrorStatus() == Epos2Exception.ERR_FAILURE)
{
Log.e("testing", "failure");
}
if(e.getErrorStatus() == Epos2Exception.ERR_ILLEGAL)
{
Log.e("testing", "illegal");
}
if(e.getErrorStatus() == Epos2Exception.ERR_IN_USE)
{
Log.e("testing", "in use");
}
if(e.getErrorStatus() == Epos2Exception.ERR_MEMORY)
{
Log.e("testing", "memory");
}
return false;
}
try {
mPrinter.beginTransaction();
isBeginTransaction = true;
}
catch (Exception e) {
Log.e("Printer", e.toString ());
}
if (isBeginTransaction == false) {
try {
mPrinter.disconnect();
}
catch (Epos2Exception e) {
// Do nothing
return false;
}
}
return true;
}
It always gives me exception ERR_CONNECT on printer.connect inside connectprinter function.
What am I doing wrong?
This code works fine with the sample app.
P.S: I have tried to connect this app before connecting the sample app to check if the sample app holds the connection and does not allow other apps to connect but that is not the case. Epson help is unable to provide any further help.
My AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xyz"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="21"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MenuActivity" >
</activity>
<activity
android:name=".SaltnPepperActivity"
android:label="#string/title_activity_saltn_pepper" >
</activity>
<activity
android:name=".FinalOrder"
></activity>
<activity
android:name=".ZinVietActivity"
>
</activity>
<activity
android:name="com.epson.epos2_printer.DiscoverActivity"
></activity>
</application>
Looks like you don't have the proper permissions in your manifest. Try putting these in your project under the manifest tag:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
They also have the
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
permission but I'm not sure you need it. I think the essentials are Bluetooth and Internet permissions.
As I suspect there seems to be an error in connect printer method. I have used this SDK once so better follow the documentation properly (means don't skip steps). Make sure you have defined permission as mentioned in the SDK.
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<activity android:name=".MainActivity" android:label="#string/app_title" android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="#xml/device_filter"/>
As I see you haven't mentioned what type of connection you are making thus, in that case, there must be problem in selecting target
Check out the function from SDK:
Public void connect(String target, int timeout) throws Epos2Exception;
You might be using wrong target parameter.
Note: if you are using USB or any other mode make sure run discoverability service as per the docs.
Discovery.start(this, mFilterOption, mDiscoveryListener);
It will return you the required target name. And I am sure no connection failure will occur. Good Luck \o
Status ERR_CONN is basically shows if device cannot be reached or connection failing with device. It can be USB, LAN/NETWORK, Bluetooth Connection failure status.
If you are trying to connect printer with Bluetooth then you must write below permissions:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
If you are using LAN for network printers then
<uses-permission android:name="android.permission.INTERNET"/>
For USB Printer Connection Use:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
As you are using EPOS2 Sample Project, remember to import Jar file "EPOS2.jar". Click here to download the file.

Android : Sync Adapter not running in some devices

In my android project i have a sync adapter that will sync data from android device to the server and its working fine, but recently i noticed that the onPerfomSync is not calling in my moto g3 android phone, I don't know whether there is the same problem in any other phones,I have tested it in some other Samsung phones with different android api level,but didn't find any problem there.I have configured the sync when a successful user login found.What will be the reason for this behaviour.Correct me if i am doing anything wrong.
Below is my codes.
private void finishLogin(Intent intent) {
String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
if (getIntent().getBooleanExtra(ARG_IS_ADDING_ACCOUNT, false)) {
String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
String authtokenType = authTokenType;
String refreshToken = intent.getStringExtra(KEY_REFRESH_TOKEN);
Bundle userData = new Bundle();
userData.putString(KEY_REFRESH_TOKEN, refreshToken);
accountManager.addAccountExplicitly(account, accountPassword, userData);
accountManager.setAuthToken(account, authtokenType, authtoken);
accountManager.setUserData(account,KEY_REFRESH_TOKEN,refreshToken);
ContentResolver.setMasterSyncAutomatically(true);
ContentResolver.setSyncAutomatically(account, "com.myexample.mysampleproject", true);
configurePeriodicSync(account, SYNC_INTERVAL, SYNC_FLEXTIME);
try {
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("condition else getIntent().getBooleanExtra(ARG_IS_ADDING_ACCOUNT, false)");
accountManager.setPassword(account, accountPassword);
}
setAccountAuthenticatorResult(intent.getExtras());
setResult(RESULT_OK, intent);
finish();
}
public void configurePeriodicSync(Account account, int syncInterval, int flexTime) {
Log.d(TAG, "PERIODC SYNC CONFIGURED");
Bundle mySyncExtras = new Bundle();
mySyncExtras.putBoolean("MY_SYNC", true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
System.out.println("if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)");
SyncRequest request = new SyncRequest.Builder().
syncPeriodic(syncInterval, flexTime).
setSyncAdapter(account, "com.myexample.mysampleproject").setExtras(mySyncExtras).build();
ContentResolver.requestSync(request);
} else {
System.out.println("else (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)");
ContentResolver.addPeriodicSync(account, "com.myexample.mysampleproject", mySyncExtras, syncInterval);
}
}
SyncService.java :
public class SyncService extends Service {
private static SyncAdapter syncAdapter = null;
private static final Object syncAdapterLock = new Object();
#Override
public void onCreate() {
synchronized (syncAdapterLock) {
if (syncAdapter == null) {
syncAdapter = new SyncAdapter(getApplicationContext(), true);
}
}
}
#Override
public IBinder onBind(Intent intent) {
return syncAdapter.getSyncAdapterBinder();
}
}
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myexample.mysampleproject" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:largeHeap="true"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".view.MainActivity"
android:configChanges="orientation|screenSize"
android:theme="#style/AppTheme"
android:label="#string/app_name" >
</activity>
<activity android:name=".view.LoginActivity"
android:configChanges="orientation|screenSize"
android:theme="#style/AppTheme"
android:label="#string/login_label"/>
........
........
<provider
android:name=".db.MyContentProvider"
android:authorities="com.myexample.mysampleproject"
android:exported="false"
android:syncable="true" />
<service
android:name=".sync.SyncService"
android:exported="true">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/sync_adapter" />
</service>
</application>
</manifest>
sync_adapter.xml :
<?xml version="1.0" encoding="utf-8"?>
<sync-adapter
xmlns:android="http://schemas.android.com/apk/res/android"
android:contentAuthority="com.myexample.mysampleproject"
android:accountType="com.myexample.mysampleproject"
android:userVisible="true"
android:supportsUploading="true"
android:allowParallelSyncs="true"
android:isAlwaysSyncable="true" />
SyncAdapter.java :
public class SyncAdapter extends AbstractThreadedSyncAdapter {
ContentResolver contentResolver;
Context context;
String authToken;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
this.context = context;
contentResolver = context.getContentResolver();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
contentResolver = context.getContentResolver();
}
#Override
public void onPerformSync(Account account, final Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
try {
System.out.println("start sync ");
AccountManager manager = AccountManager.get(context);
authToken = manager.peekAuthToken(account, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS);
try {
if(authToken != null) {
if (isOnline()) {
// perform sync....
} else {
Log.d("ATTEMPT SYNC ERROR", "NO NETWORK CONNECTION");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Android app. works in emulator but not working in android device

I have written a simple application to fetch the network details where i have used an AlarmManager to continuously run a piece of code in the background(IntentServiceImpl class)..
I am invoking the AlarmManager class from the BroadcastReceiver, and i have registered the BroadcastReceiver(BroadcastReceiverImpl class) for BOOT_COMPLETE event... it is working properly in the android emulator but it is not working in Android Device(i have checked it in Samsung Galaxy s2 and Samsung Galaxy Tab) Here is the source code..
BroadcastReceiverImpl.java
public class BroadcastReceiverImpl extends BroadcastReceiver {
private static final String LOG_TAG = BroadcastReceiverImpl.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
Log.d(LOG_TAG, "Inside the BroadcastReceiver Class");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,QOSConstants.TIME_DELAY_IN_SECONDS);
Intent serviceIntent = new Intent(context, IntentServiceImpl.class);
serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getService(context, QOSConstants.REQUEST_CODE,serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//After after 60 seconds
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
QOSConstants.MILLISECONDS * QOSConstants.TIME_DELAY_IN_SECONDS, pendingIntent);
Log.d(LOG_TAG, "Exiting the QOSBroadcastReceiver Class");
}
}
IntentServiceImpl.java
public class IntentServiceImpl extends IntentService implements LocationListener {
private String strNetworkInfo;
private LocationManager locationManager;
private QOSDatabaseHelper qosDatabaseHelper;
private NetworkDetailsVO networkDetailsVO ;
private static final String LOG_TAG = QOSIntentService.class.getName();
private QOSServlet qosServlet;
private QOSPhoneStateListner qosPhoneStateListner;
public QOSIntentService() {
super(LOG_TAG);
Log.d(LOG_TAG , ": Inside NetworkInfoService() constructor");
}
#Override
public void onCreate() {
super.onCreate();
qosServlet = new QOSServlet();
networkDetailsVO = new NetworkDetailsVO();
qosPhoneStateListner = new QOSPhoneStateListner();
qosDatabaseHelper = new QOSDatabaseHelper(getApplicationContext());
}
#Override
protected void onHandleIntent(Intent intent) {
Log.i("LOG_TAG: ", "Inside onHandleIntent(Intent) method Fetching Network Details ");
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo!=null && networkInfo.isConnected()){
String networkState = getNetworkStateString(networkInfo.getState());
String stateString = networkInfo.toString().replace(',', '\n');
strNetworkInfo = String.format(QOSConstants.NETWORK_STATE_DISPLAY_FORMAT,
networkInfo.getTypeName(),networkState,stateString);
networkDetailsVO.setNetworkState(networkState);
networkDetailsVO.setNetworkType(networkInfo.getTypeName());
networkDetailsVO.setRoaming(String.valueOf(networkInfo.isRoaming()));
networkDetailsVO.setReason(networkInfo.getReason());
networkDetailsVO.setFailOver(String.valueOf(networkInfo.isFailover()));
networkDetailsVO.setNetworkAvailable(String.valueOf(networkInfo.isAvailable()));
networkDetailsVO.setNetworkConnectivity(String.valueOf(networkInfo.isConnected()));
if(networkInfo.getExtraInfo()!=null)
networkDetailsVO.setExtraNetworkInfo(networkInfo.getExtraInfo());
else
networkDetailsVO.setExtraNetworkInfo(QOSConstants.NETWORK_EXTRA_INFO_NOT_AVAILABLE);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, QOSConstants.MINIMUM_TIME, QOSConstants.MINIMUM_DISTANCE, this);
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false));
if(location!=null){
onLocationChanged(location);
QOSGeocoder qosGeocoder = new QOSGeocoder();
networkDetailsVO.setLocationAddress(qosGeocoder.getLocationAddress(getApplicationContext(), location));
}else{
networkDetailsVO.setLatitude(0.0);
networkDetailsVO.setLongitude(0.0);
}
// Identify the connectivity type. WI-FI/MOBILE.
if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI){
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
networkDetailsVO.setSignalStrength(wifiManager.getConnectionInfo().getLinkSpeed());
}else if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE){
telephonyManager.listen(qosPhoneStateListner, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
networkDetailsVO.setSignalStrength(qosPhoneStateListner.getStrSignalStrength());
}
networkDetailsVO.setNetworkInfo(strNetworkInfo);
networkDetailsVO.setSimSerialNumber(telephonyManager.getSimSerialNumber());
networkDetailsVO.setOperatorName(telephonyManager.getNetworkOperatorName());
networkDetailsVO.setDateTime(new Date().toString());
Log.i(LOG_TAG , "Network Details :- " + "\t" + networkInfo.toString());
//qosDatabaseHelper = new QOSDatabaseHelper(getApplicationContext());
qosDatabaseHelper.saveRecord(networkDetailsVO);
qosServlet.invokeServlet(networkDetailsVO);
Log.i(LOG_TAG , " Network details are saved to the Database,exiting onHandleIntent(Intent) method ");
}
#Override
public void onLocationChanged(Location location) {
Log.i(LOG_TAG, " : Inside onLocationChanged(Location) method ");
networkDetailsVO.setLatitude(location.getLatitude());
networkDetailsVO.setLongitude(location.getLongitude());
Log.i(LOG_TAG, " : Exiting onLocationChanged(Location) method ");
}
#Override
public void onProviderEnabled(String provider) {
Log.i(LOG_TAG, ": Provider is Enabled !! ");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, QOSConstants.MINIMUM_TIME,
QOSConstants.SECOND_MINIMUM_DISTANCE, this);
}
#Override
public void onProviderDisabled(String string) {
Log.i(LOG_TAG, ": Provider is Disabled !! ");
}
#Override
public void onStatusChanged(String strStatus, int arg1, Bundle bundle) {
Log.i(LOG_TAG, " : Inside onStatusChanged(String,int,Bundle) method ");
}
private String getNetworkStateString(NetworkInfo.State state){
Log.i(LOG_TAG, ": Inside getNetworkStateString(NetworkInfo.State)");
String stateString = QOSConstants.NETWORK_STATE_UNKNOWN;
switch(state)
{
case CONNECTED:
stateString = QOSConstants.NETWORK_STATE_CONNECTED;
break;
case CONNECTING:
stateString = QOSConstants.NETWORK_STATE_CONNECTING;
break;
case DISCONNECTED:
stateString = QOSConstants.NETWORK_STATE_DISCONNECTED;
break;
case DISCONNECTING:
stateString = QOSConstants.NETWORK_STATE_DISCONNECTING;
break;
case SUSPENDED:
stateString = QOSConstants.NETWORK_STATE_SUSPENDED;
break;
default:
stateString = QOSConstants.NETWORK_STATE_UNKNOWN;
break;
}
return stateString;
}
#Override
public void onDestroy() {
super.onDestroy();
if(qosDatabaseHelper!=null){
qosDatabaseHelper.closeDatabase();
}
}
}
#Override
public void onProviderDisabled(String string) {
Log.i(LOG_TAG, ": Provider is Disabled !! ");
}
/*#Override
public IBinder onBind(Intent intent) {
Log.i("LOG_TAG: ", "Inside onBind(Intent) method");
return null;
}
*/
#Override
public void onStatusChanged(String strStatus, int arg1, Bundle bundle) {
Log.i(LOG_TAG, " : Inside onStatusChanged(String,int,Bundle) method ");
}
private class SignalStrengthDetector extends PhoneStateListener{
#Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
super.onSignalStrengthsChanged(signalStrength);
networkDetailsVO.setSignalStrength(signalStrength.getGsmSignalStrength());
Log.i(LOG_TAG, "Signal Strength :-" + String.valueOf(signalStrength.getGsmSignalStrength()));
}
}
private String getNetworkStateString(NetworkInfo.State state){
Log.i(LOG_TAG, ": Inside getNetworkStateString(NetworkInfo.State)");
String stateString = NetworkInfoConstants.NETWORK_STATE_UNKNOWN;
switch(state)
{
case CONNECTED:
stateString = NetworkInfoConstants.NETWORK_STATE_CONNECTED;
break;
case CONNECTING:
stateString = NetworkInfoConstants.NETWORK_STATE_CONNECTING;
break;
case DISCONNECTED:
stateString = NetworkInfoConstants.NETWORK_STATE_DISCONNECTED;
break;
case DISCONNECTING:
stateString = NetworkInfoConstants.NETWORK_STATE_DISCONNECTING;
break;
case SUSPENDED:
stateString = NetworkInfoConstants.NETWORK_STATE_SUSPENDED;
break;
default:
stateString = NetworkInfoConstants.NETWORK_STATE_UNKNOWN;
break;
}
return stateString;
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pervazive.qualityofservice_v01"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.pervazive.qualityofservice_v01.activity.QOSActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:theme="#style/FullscreenTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.pervazive.qualityofservice_v01.intentservice.<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pervazive.qualityofservice_v01"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.pervazive.qualityofservice_v01.activity.QOSActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:theme="#style/FullscreenTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.pervazive.qualityofservice_v01.intentservice.IntentServiceImpl"
android:enabled="true" >
</service>
<receiver android:name="com.pervazive.qualityofservice_v01.broadcastreceiver.BroadcastReceiverImpl" >
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Please let know what is the error...please let me know where can i find the log file in Android device... (because it is running on the Android Emulator but not running i=on the Android device...) Thanks in Advance
Right click on your project> Android Tools> Export as signed android application.
Fill required fields and you are good to go.

Categories

Resources