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.
Related
I'm trying to use fingerprint gestures in an accessibility service. It is working fine in android 8.1 devices (Nexus 5x emulator, Moto G5s Plus) but not working in android 9 devices (Nexus 5x emulator, Samsung M30s). I've added all the required lines mentioned in this question:
Android O - fingerprint gesture callback not working
Do I have to add something extra for android 9? Can someone please help me?
activity_service.xml:
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityFeedbackType="feedbackGeneric"
android:canRequestFingerprintGestures="true"
android:accessibilityFlags="flagDefault|flagRequestFingerprintGestures"
android:canPerformGestures="true"/>
MyAccessibilityService.java:
public class MyAccessibilityService extends AccessibilityService {
private static final String TAG = MyAccessibilityService.class.getSimpleName();
#Override
public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
Log.d(TAG, "onAccessibilityEvent");
}
#Override
public void onInterrupt() {
Log.d(TAG, "onInterrupt");
}
#Override
protected boolean onGesture(int gestureId) {
Log.d(TAG, "onGesture " + gestureId);
return super.onGesture(gestureId);
}
#Override
protected boolean onKeyEvent(KeyEvent event) {
Log.d(TAG, "onKeyEvent " + event.getKeyCode());
return super.onKeyEvent(event);
}
#Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "onDestroy" , Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
protected void onServiceConnected() {
super.onServiceConnected();
Log.d(TAG, "onServiceConnected");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
FingerprintGestureController gestureController = getFingerprintGestureController();
Toast.makeText(getApplicationContext(), "Is available: " + gestureController.isGestureDetectionAvailable(), Toast.LENGTH_LONG).show();
Log.e(TAG, "Is available: " + gestureController.isGestureDetectionAvailable() );
FingerprintGestureController.FingerprintGestureCallback callback = new
FingerprintGestureController.FingerprintGestureCallback() {
#Override
public void onGestureDetectionAvailabilityChanged(boolean available) {
super.onGestureDetectionAvailabilityChanged(available);
Toast.makeText(getApplicationContext(), "Gesture available change to: " + available, Toast.LENGTH_SHORT).show();
Log.d(TAG, "onGestureDetectionAvailabilityChanged " + available);
}
#Override
public void onGestureDetected(int gesture) {
super.onGestureDetected(gesture);
switch (gesture){
case GESTURE_SWIPE_DOWN:
CameraManager mCameraManager;
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String mCameraId = "";
try {
mCameraId = mCameraManager.getCameraIdList()[0];
mCameraManager.setTorchMode(mCameraId, true);
}
catch (Exception e){
}
break;
case GESTURE_SWIPE_UP:
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
mCameraManager.setTorchMode(mCameraId, false);
}
catch (Exception e){
}
break;
default:
Toast.makeText(getApplicationContext()
, "Gesture: " + gesture, Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "onGestureDetected " + gesture);
}
};
gestureController.registerFingerprintGestureCallback(callback, new Handler());
}
}
#Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "onUnbind " );
return super.onUnbind(intent);
}}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.bignerdranch.com.myapplication">
<uses-feature android:name="android.hardware.fingerprint"/>
<uses-feature android:name="android.hardware.camera.flash" />
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission." />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<permission android:name="android.permission.FLASHLIGHT"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
android:protectionLevel="normal" />
<application>
<service
android:name=".MyAccessibilityService"
android:label="#string/app_name"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="#xml/activity_service" />
</service>
</application>
</manifest>
You need to add this line in the gesture service xml
android:accessibilityFlags="flagDefault|flagRequestFingerprintGestures"
It could also be device related. Check the following answer for information.
Android M FingerprintManager.isHardwareDetected() returns false on a Samsung Galaxy S5
Can you provide your code samples for further debugging if this doesn't work?
I develop a VoIP app using this guide.
I faced the problem with a self-manged connection service on Samsung devices.
I'm placing a call using TelecomManager.
I expect that ConnectionService::onCreateOutgoingConnection or ConnectionService::onCreateOutgoingConnectionFailed will be invoked, but it doesn't happen on some Samsung devices.
After placing a call the dialog window appears. On samsung galaxy s10 an android toast appears with the text "Call not sent". Methods of connection service are not invoked.
On phones with the vanilla Android it works as expected.
Does anybody know how to solve this issue?
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.tcom">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
<uses-permission android:name="android.permission.MANAGE_OWN_CALLS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.tcom.ConnectionService"
android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE">
<intent-filter>
<action android:name="android.telecom.ConnectionService" />
</intent-filter>
</service>
</application>
</manifest>
ConnectionService:
public class ConnectionService extends android.telecom.ConnectionService {
private static final String TAG = "ConnectionService";
#Override
public android.telecom.Connection onCreateIncomingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i(TAG, "onCreateIncomingConnection");
Connection connection = new Connection();
MainActivity.setConnection(connection);
return connection;
}
#Override
public void onCreateIncomingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i(TAG, "onCreateIncomingConnectionFailed");
super.onCreateIncomingConnectionFailed(connectionManagerPhoneAccount, request);
}
#Override
public android.telecom.Connection onCreateOutgoingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i(TAG, "onCreateOutgoingConnection");
Connection connection = new Connection();
MainActivity.setConnection(connection);
return connection;
}
#Override
public void onCreateOutgoingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i(TAG, "onCreateOutgoingConnectionFailed");
super.onCreateOutgoingConnectionFailed(connectionManagerPhoneAccount, request);
}
}
Connection:
public class Connection extends android.telecom.Connection {
private static final String TAG = "Connection";
public Connection() {
super();
setConnectionProperties(android.telecom.Connection.PROPERTY_SELF_MANAGED);
}
#Override
public void onStateChanged(int state) {
super.onStateChanged(state);
Log.i(TAG, "onStateChanged state=" + android.telecom.Connection.stateToString(state));
}
}
PhoneAccount creating:
void createAccount() {
tm = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
if (tm == null) {
throw new RuntimeException("cannot obtain telecom system service");
}
ComponentName connectionServiceName = new ComponentName(getApplicationContext(), ConnectionService.class);
PhoneAccountHandle accountHandle = new PhoneAccountHandle(connectionServiceName, PHONE_ACCOUNT_LABEL);
try {
PhoneAccount phoneAccount = tm.getPhoneAccount(accountHandle);
if (phoneAccount == null) {
PhoneAccount.Builder builder = PhoneAccount.builder(accountHandle, PHONE_ACCOUNT_LABEL);
builder.setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED);
phoneAccount = builder.build();
tm.registerPhoneAccount(phoneAccount);
}
this.accountHandle = phoneAccount.getAccountHandle();
if (tm.getPhoneAccount(accountHandle) == null) {
throw new RuntimeException("cannot create account");
}
} catch (SecurityException e) {
throw new RuntimeException("cannot create account", e);
}
}
Call creating:
void createCall() {
try {
Bundle extras = new Bundle();
extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, accountHandle);
Uri uri = Uri.fromParts(PhoneAccount.SCHEME_SIP, "test_call", null);
tm.placeCall(uri, extras);
}
catch (SecurityException e) {
throw new RuntimeException("cannot place call", e);
}
}
After some firmware update the code above started working correctly.
So, the problem was in the phone itself.
Anybody else having this problem, just make sure of two things:
Remove PhoneAccount.CAPABILITY_CALL_PROVIDER from your phone account's capabilities.
You have implemented an InCallService.
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" />
?
Part of my application creates some files in the external storage and writes into them.
Everything was working like a charm until I changed something, I don't remember what. Now application creates files but doesn't write anything, i.e the files are empty.
Any ideas what is the problem?
Here is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myloader"
android:versionCode="26"
android:versionName="1.1" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:debuggable="true">
<activity
android:name="com.example.myloader.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>
</application>
</manifest>
Here is where I write to a file. I haven't changed anything though. It was like this when it was working
public class GraphHelper {
File directory;
File myExternalFile;
PrintWriter writer;
FileOutputStream outputStream;
ArrayList<float[]> dataList;
float []toWrite;
String strToWrite;
private String filepath = "MyFileStorage";
public GraphHelper(Context context)
{
directory = context.getExternalFilesDir(filepath);
}
public GraphHelper(Application application)
{
directory = application.getExternalFilesDir(filepath);
}
public void writeToFile(String filename,ArrayList <float[]>data)
{
if(isExternalStorageAvailable()&&!isExternalStorageReadOnly())
{
myExternalFile = new File(directory, filename);
try {
outputStream = new FileOutputStream(myExternalFile);
writer = new PrintWriter(outputStream);
dataList = data;
for(int i=0;i< data.size();i++)
{
toWrite = data.get(i);
System.out.println("toWrite[1]: "+toWrite[0]+"toWrite[2]: "+toWrite[1]);
}
writer.close();
outputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
you never call print
for(int i=0;i< data.size();i++) {
toWrite = data.get(i);
System.out.println("toWrite[1]: "+toWrite[0]+"toWrite[2]: "+toWrite[1]);
writer.print(toWrite);
}
writer.flush();
writer.close();
I have written the android application and I want the application to send the call information whenever there is an incoming call and it ends. This way I would be sending all calls to the server irrespective of size of the call log.
Here is the code
public class PhoneInfo extends BroadcastReceiver {
private int incoming_call = 0;
private Cursor c;
Context context;
public void onReceive(Context con, Intent intent) {
c = con.getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC");
context = con;
IncomingCallListener phoneListener = new IncomingCallListener();
TelephonyManager telephony = (TelephonyManager) con
.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
public class IncomingCallListener extends PhoneStateListener {
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
if (incoming_call == 1) {
CollectSendCallInfo();
incoming_call = 0;
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
break;
case TelephonyManager.CALL_STATE_RINGING:
incoming_call = 1;
break;
}
}
private void CollectSendCallInfo() {
int numberColumn = c
.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int dateColumn = c.getColumnIndex(android.provider.CallLog.Calls.DATE);
int typeColumn = c.getColumnIndex(android.provider.CallLog.Calls.TYPE);
int durationColumn = c
.getColumnIndex(android.provider.CallLog.Calls.DURATION);
ArrayList<String> callList = new ArrayList<String>();
try {
boolean moveToFirst = c.moveToFirst();
}
catch (Exception e) {
; // could not move to the first row.
return;
}
int row_count = c.getCount();
int loop_index = 0;
int is_latest_call_read = 0;
String callerPhonenumber = c.getString(numberColumn);
int callDate = c.getInt(dateColumn);
int callType = c.getInt(typeColumn);
int duration = c.getInt(durationColumn);
while ((loop_index < row_count) && (is_latest_call_read != 1)) {
switch (callType) {
case android.provider.CallLog.Calls.INCOMING_TYPE:
is_latest_call_read = 1;
break;
case android.provider.CallLog.Calls.MISSED_TYPE:
break;
case android.provider.CallLog.Calls.OUTGOING_TYPE:
break;
}
loop_index++;
c.moveToNext();
}
SendCallInfo(callerPhonenumber, Integer.toString(duration),
Integer.toString(callDate));
}
private void SendCallInfo(String callerPhonenumber, String callDuration,
String callDate) {
JSONObject j = new JSONObject();
try {
j.put("Caller", callerPhonenumber);
j.put("Duration", callDuration);
j.put("CallDate", callDate);
} catch (JSONException e) {
Toast.makeText(context, "Json object failure!", Toast.LENGTH_LONG)
.show();
}
String url = "http://xxxxxx.xxx.xx/xxxx/xxx.php";
Map<String, String> kvPairs = new HashMap<String, String>();
kvPairs.put("phonecall", j.toString());
HttpResponse re;
try {
re = doPost(url, kvPairs);
String temp;
try {
temp = EntityUtils.toString(re.getEntity());
if (temp.compareTo("SUCCESS") == 0) {
;
}
else
;
} catch (ParseException e1) {
Toast.makeText(context, "Parse Exception in response!",
Toast.LENGTH_LONG).show();
e1.printStackTrace();
} catch (IOException e1) {
Toast.makeText(context, "Io exception in response!",
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
} catch (ClientProtocolException e1) {
Toast.makeText(context, "Client Protocol Exception!",
Toast.LENGTH_LONG).show();
e1.printStackTrace();
} catch (IOException e1) {
Toast.makeText(context, "Client Protocol Io exception!",
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
}
}
and here is the manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.Friend" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission>
<uses-permission android:name="android.permission.INSTALL_LOCATION_PROVIDER"></uses-permission>
<uses-permission android:name="android.permission.SET_DEBUG_APP"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Friend" 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=".LoginInfo" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.DEFAULT" />
</intent-filter>
</activity>
<service android:exported="true" android:enabled="true"
android:name=".GeoUpdateService">
</service>
<receiver android:name=".SmsInfo">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<receiver android:name=".PhoneInfo">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"></action>
</intent-filter>
</receiver>
</application>
</manifest>
The application just crashes when there is an incoming call. I have been able to log the information about incoming SMS, but this call info logging is failing.
In my opinion you use BroadcastReciver in wrong way. You perform sync-query which can last more time than you have for handling broadcast. Next issue - you register listener object which will be probably collected by GC just after the end of onReceive method. Your BroadR should start service for handling those events.