I am implementing an app to clean cache of installed applications,And what I have tried is following :
public static void freeAllAppsCache(final Handler handler,Context oContext)
{
File externalDir = oContext.getApplicationContext().getExternalCacheDir();
if (externalDir == null) {
return;
}
PackageManager pm = oContext.getApplicationContext().getPackageManager();
List<ApplicationInfo> installedPackages = pm.getInstalledApplications(PackageManager.GET_GIDS);
for (ApplicationInfo info : installedPackages)
{
String externalCacheDir = externalDir.getAbsolutePath().replace(oContext.getApplicationContext().getPackageName(), info.packageName);
File externalCache = new File(externalCacheDir);
if (externalCache.exists() && externalCache.isDirectory())
{
deleteFile(externalCache);
}
}
try {
Method freeStorageAndNotify = pm.getClass()
.getMethod("freeStorageAndNotify", long.class, IPackageDataObserver.class);
long freeStorageSize = Long.MAX_VALUE;
freeStorageAndNotify.invoke(pm, freeStorageSize, new IPackageDataObserver.Stub() {
#Override
public void onRemoveCompleted(String packageName, boolean succeeded) throws RemoteException {
Message msg = handler.obtainMessage(MainActivity.MSG_SYS_CACHE_CLEAN_FINISH);
msg.sendToTarget();
}
});
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public static boolean deleteFile(File file) {
if (file !=null && file.isDirectory()) {
String[] children = file.list();
if (children != null)
{
for (String name : children) {
boolean suc = deleteFile(new File(file, name));
if (!suc) {
return false;
}
}
}
}
return file.delete();
}
And I also have declared following permissions in manifest file :
uses-permission android:name="android.permission.GET_PACKAGE_SIZE"
uses-permission android:name="android.permission.CLEAR_APP_CACHE"
But it's not clearing cache. What's the reason ?
Related
How to handle this kind of exception? Given work is not active exception in Oreo while i m using unique job id across the app.
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:353)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.lang.IllegalArgumentException: Given work is not active: JobWorkItem{id=2 intent=Intent { cmp=com.virinchi.mychat/com.virinchi.receiver.AnalysticsSubmit } dcount=1}
at android.app.job.JobParameters.completeWork(JobParameters.java:221)
at android.support.v4.app.JobIntentService$JobServiceEngineImpl$WrapperWorkItem.complete(JobIntentService.java:267)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:393)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:382)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask)
public class AnalysticsSubmit extends JobIntentService {
private static String TAG = "AnalysticsSubmit";
/**
* Unique job ID for this service.
*/
/**
* Convenience method for enqueuing work in to this service.
*/
public static void enqueueWork(Context context, Intent work) {
try{
enqueueWork(context, AnalysticsSubmit.class, JOB_ID, work);
}catch (Exception ex){
Log.e(TAG, "enqueueWork: ex"+ex.getMessage() );
}
}
#Override
protected void onHandleWork(Intent intent) {
try {
UtilsUserInfo userInfo = new UtilsUserInfo(DocApplication.getContext());
int width = 0;
int height = 0;
String widthstr = "0";
String heightstr = "0";
JSONObject records = new JSONObject();
JSONObject device_info = new JSONObject();
WindowManager wm = (WindowManager) DocApplication.getContext().getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics displayMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(displayMetrics);
width = displayMetrics.widthPixels;
height = displayMetrics.heightPixels;
widthstr = String.valueOf(width);
heightstr = String.valueOf(height);
String device_model = Build.MODEL + " " + Build.VERSION.RELEASE;
device_info.put("app_version", userInfo.getFromPreferences("version"));
device_info.put("operating_system", getOsName());
device_info.put("device_resolution", widthstr + "*" + heightstr);
device_info.put("device_model", device_model);
device_info.put("device_manufacturer", Build.MANUFACTURER);
device_info.put("app_identifier", ResourceUtils.getResourceString(this, R.string.app_identifier_analytics));
JSONArray event = new JSONArray();
try {
Realm realm = SingleInstace.getInstace().getRealm();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
try {
JSONObject eventobj = null;
RealmResults<DocquityLog> results = realm.where(DocquityLog.class).findAll();
results.load();
for (DocquityLog obj : results) {
JSONObject session_time = new JSONObject();
JSONObject location = new JSONObject();
eventobj = new JSONObject();
eventobj.put("event_name", obj.getEvent_name());
eventobj.put("product_type", obj.getProduct_type());
eventobj.put("product_type_id", obj.getProduct_type_id());
eventobj.put("session_id", obj.getSession_id());
eventobj.put("local_id", obj.getId());
eventobj.put("screen_name", obj.getScreen_name());
if (!Validation.isEmptyString(userInfo.getFromPreferences("user_id"))) {
eventobj.put("user_id", Integer.parseInt(userInfo.getFromPreferences("user_id")));
if (userInfo.isKeyExist("untrack_user_identifier")) {
eventobj.put("untrack_user_identifier", userInfo.getFromPreferences("untrack_user_identifier"));
userInfo.removeKey("untrack_user_identifier");
}
} else {
eventobj.put("user_id", 0);
eventobj.put("untrack_user_identifier", userInfo.getFromPreferences("untrack_user_identifier"));
}
session_time.put("start_time", obj.getStart_time());
session_time.put("end_time", obj.getEnd_time());
eventobj.put("session_time", session_time);
location.put("latitude", obj.getLatitude());
location.put("longitude", obj.getLongitude());
location.put("local", obj.getLocal());
location.put("time_zone", obj.getTime_zone());
eventobj.put("location", location);
event.put(eventobj);
}
} catch (Exception ex) {
LogEx.logExecption(TAG, "", ex);
}
}
});
} catch (Exception ex) {
LogEx.logExecption(TAG, "", ex);
} finally {
SingleInstace.getInstace().destroyRealm();
}
records.put("device_info", device_info);
records.put("event", event);
// Log.e(TAG, " records "+records.toString());
if (records != null && event.length() > 0) {
//apiAnalysticWork(records.toString());
ApiManager.getClientBasicAuthNewReactive(userInfo.getFromPreferences("user_auth_key"),
userInfo.getFromPreferences(userInfo.token_id),
ApiManager.GENRIC_API_VERSION_2, userInfo.getFromPreferences("version"),
GlobalSetting.Lng, "", ApiManager.DeviceType).getAnalysticRecord(records.toString())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.computation())
.subscribe(searchResponse -> {
try {
int status = searchResponse.getStatus();
if (status == 1) {
// Log.e(TAG, "showSearchResult: success");
// delete work
try {
Realm realm = SingleInstace.getInstace().getRealm();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
try {
RealmQuery q = realm.where(DocquityLog.class);
int x = 0;
for (Integer id : searchResponse.getAnalysticData().getSuccess_session_ids()) {
if (x != 0) {
q.or();
}
q = q.equalTo("id", id);
x++;
}
RealmResults<DocquityLog> filteredArticles = q.findAll();
filteredArticles.deleteAllFromRealm();
} catch (Exception ex) {
Log.e(TAG, " ex " + ex.getMessage());
Crashlytics.logException(ex);
}
}
});
} finally {
SingleInstace.getInstace().destroyRealm();
}
//RealmController.commitInput();
}
} catch (Exception ex) {
LogEx.logExecption(TAG, "", ex);
}
}, throwable -> LogEx.displayRetrofitError(TAG, throwable));
// Log.e(TAG, "jsonWorkAnalystic:reords "+records.toString() );
}
} catch (JSONException e) {
LogEx.logExecption(TAG, "JSONException", e);
} catch (Exception e) {
LogEx.logExecption(TAG, "OtherException", e);
}
}
/*public AnalysticsSubmit() {
super("AnalysticsSubmit");
}
#Override
public void onDestroy() {
// Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
}
*/
public String getOsName() {
StringBuilder builder = new StringBuilder();
// builder.append("android : ").append(Build.VERSION.RELEASE);
Field[] fields = Build.VERSION_CODES.class.getFields();
for (Field field : fields) {
String fieldName = field.getName();
int fieldValue = -1;
try {
fieldValue = field.getInt(new Object());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
if (fieldValue == Build.VERSION.SDK_INT) {
builder.append(fieldName);
}
}
return builder.toString();
}
}
I am making an android app in which i need to take the users location through fused location provider. Before taking the location i want to check whether the gps is on or not. And i want to do this without using location manager. Any suggestions?
Throw bellow method you can check Location Mode,
/**
* Method is used to check which locatrion mode is selected,
*
* #param context
* #return If return 0 = LOCATION_MODE_OFF, 1 = LOCATION_MODE_SENSORS_ONLY & DEVICE_ONLY, 2 = LOCATION_MODE_BATTERY_SAVING , 3 = LOCATION_MODE_HIGH_ACCURACY
*/
public static int getLocationMode(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
return Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return 0;
}
} else {
try {
String locationProviders = Settings.Secure.getString(
context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED
);
if (!TextUtils.isEmpty(locationProviders)) {
return 2;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
private void checkGpsEnabled() {
LocationSettingsRequest settingsRequest = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest)
.setNeedBle(true)
.setAlwaysShow(true)
.build();
SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> response = client.checkLocationSettings(settingsRequest);
response.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
}
});
response.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ResolvableApiException) {
ResolvableApiException resolvableApiException = (ResolvableApiException) e;
try {
resolvableApiException.startResolutionForResult(LocationFusedActivity.this, 1002);
} catch (IntentSender.SendIntentException e1) {
e1.printStackTrace();
}
}
}
});
}
Following is my code and I want to get push notification when my device is offline or app is killed.
When my app is background I want to get notify by XMPP ejabberd server
IQ Class
class MyCustomIQ extends IQ {
String token = SharedPreferenceManager.getValue(getApplicationContext(), "DEVICE_TOKEN");
protected MyCustomIQ() {
super("query", "urn:xmpp:registernoti");
}
#Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.rightAngleBracket();
xml.element("token", token);
xml.element("devicetpye", "android");
return xml;
}
}
On connected
#Override
public void connected(XMPPConnection connection) {
Log.e(TAG, "connected: ");
MyCustomIQ iq = new MyCustomIQ();
iq.setType(IQ.Type.set);
try {
abstractXMPPConnection.sendIqWithResponseCallback(iq, new StanzaListener() {
#Override
public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException {
Log.e(TAG, "processStanza: " + packet.toString());
}
});
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Try following code for register device token on xmpp server
Register token stanza
<iq to="YourServer" type="set">
<register xmlns="https://android.googleapis.com/gcm" >
<key>API_KEY</key>
</register>
</iq>
1) way for register token
public void registerTokenTomod_gcm(final String deviceToken){
IQ iq=new IQ("register","https://android.googleapis.com/gcm") {
#Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.attribute("key",deviceToken);
xml.setEmptyElement();
return xml;
}
};
iq.setType(IQ.Type.set);
iq.setTo(AppConstants.CHAT_HOSTNAME);
debugLog("getpushDicsoInfo send stanza:"+iq.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(iq.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(iq);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
2) way to register token
public void registerTokenToXmpp(String deviceId,String deviceName,String deviceToken){
DataForm xep0004 = new DataForm(DataForm.Type.submit);
FormField token = new FormField("token");
token.addValue(deviceToken);
FormField device_id = new FormField("device-id");
device_id.addValue(deviceId);
FormField device_name = new FormField("device-name");
device_name.addValue(deviceName);
xep0004.addField(token);
xep0004.addField(device_id);
xep0004.addField(device_name);
AdHocCommandData stanza = new AdHocCommandData();
stanza.setTo("android");
stanza.setType(IQ.Type.set);
stanza.setStanzaId("0043423");
stanza.setNode("register-push-gcm");
stanza.setAction(AdHocCommand.Action.execute);
stanza.setForm(xep0004);
stanza.setFrom(connection.getUser());
debugLog("getpushDicsoInfo send stanza:"+stanza.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(stanza.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(stanza);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
UnRegister device token from server
private void unregisterToken(){
String deviceid="3524940..."; //sony
String tokenstring="GHkd7Ro2qtMg:XPA91bflkgklDeg..."; // sony
DataForm xep0004 = new DataForm(DataForm.Type.submit);
FormField token = new FormField("token");
token.addValue(tokenstring);
FormField device_id = new FormField("device-id");
device_id.addValue(deviceid);
FormField device_name = new FormField("device-name");
// device_name.addValue(devicename);
xep0004.addField(token);
xep0004.addField(device_id);
xep0004.addField(device_name);
AdHocCommandData stanza = new AdHocCommandData();
stanza.setTo("android");
stanza.setType(IQ.Type.set);
stanza.setStanzaId("0043423");
stanza.setNode("register-push-gcm");
stanza.setAction(AdHocCommand.Action.execute);
stanza.setForm(xep0004);
stanza.setFrom(connection.getUser());
debugLog("getpushDicsoInfo send stanza:"+stanza.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(stanza.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(stanza);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
i call below php webservice and get xml response and parse resonse and set it to hashmap.now i want save server response in offline mode .can i save data in offline mode.how plz give me answer.
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
try {
if (response.length() > 0) {
int code = Integer.parseInt(XMLManualParser.getTagValue(Constant.TAG_CODE, response));
if (code == 1) {
spinner.clear();
ArrayList<String> eventlist = XMLManualParser.getMultipleTagList(Constant.TAG_LIST, response);
for (int i = 0; i < eventlist.size(); ++i) {
String responseContent = eventlist.get(i);
HashMap<String, String> hashMap = new HashMap<String, String>();
String title = XMLManualParser.getTagValue(Constant.title, responseContent);
hashMap.put("title", title);
hashMap.put("id", XMLManualParser.getTagValue(Constant.id, responseContent));
hashMap.put("url", XMLManualParser.getTagValue(Constant.url, responseContent));
hashMap.put("balanceurl", XMLManualParser.getTagValue(Constant.balanceurl, responseContent));
spinner.add(hashMap);
}
} else {
Toast.makeText(SettingsEditActivity.this, "no data found", Toast.LENGTH_SHORT).show();
}
CustomSpinnerAdapter customSpinnerAdapter = new CustomSpinnerAdapter(SettingsEditActivity.this, spinner);
settingsBinding.splist.setAdapter(customSpinnerAdapter);
settingsBinding.splist.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
item = parent.getItemAtPosition(position).toString();
// Toast.makeText(parent.getContext(), "Android Custom Spinner Example Output..." + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can save your response into a file and get in offline
public static void saveDataSingleItemDetails(Context context,String file, MainListModel data) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = context.openFileOutput(file, MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
return;
}
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException | NullPointerException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.writeObject(data);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static MainListModel getSinglItemDetails(Context context,String file) {
MainListModel items = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = context.openFileInput(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return items;
} catch (NullPointerException e) {
return items;
}
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(fileInputStream);
} catch (IOException | NullPointerException e) {
e.printStackTrace();
return items;
}
try {
items = (MainListModel) objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return items;
}
I was download epson android sdk from
https://download.epson-biz.com/modules/pos/index.php?page=single_soft&cid=5228&pcat=7&pid=4179.
I have an Epson TM-T81 series printer,When i try to connect this sdk with my printer it show Error code(ERR_UNSUPPORTED),but when i change the printer series to TM-T82 or some other from the spinner, it works fine with my TM-T81 printer but it is not working when i select TM-T81.What is the reason for that?
You can use like this. This answer Will Help you.
public boolean initializeObject(Printer printerSeries) {
try {
// mPrinter=new Printer(Printer.TM_T88,Printer.LANG_EN,mContext);
or
mPrinter=new Printer(printerSeries,Printer.LANG_EN,mContext);
}
catch (Exception e) {
ShowMsg.showException(e, "Printer", mContext);
return false;
}
mPrinter.setReceiveEventListener(new com.epson.epos2.printer.ReceiveListener() {
#Override
public void onPtrReceive(Printer printer, int i, PrinterStatusInfo printerStatusInfo, String s) {
runOnUiThread(new Runnable() {
#Override
public synchronized void run() {
disconnectPrinter();
new Thread(new Runnable() {
#Override
public void run() {
disconnectPrinter();
}
}).start();
}
});
}
});
return true;
}
public void finalizeObject() {
if (mPrinter == null) {
return;
}
mPrinter.clearCommandBuffer();
mPrinter.setReceiveEventListener(null);
mPrinter = null;
}
public boolean printData(String receiptPrintIP) {
if (mPrinter == null) {
return false;
}
if (!connectPrinter(receiptPrintIP)) {
return false;
}
PrinterStatusInfo status = mPrinter.getStatus();
if (!isPrintable(status)) {
ShowMsg.showMsg(printPOS2Help.makeErrorMessage(status), mContext);
try {
mPrinter.disconnect();
}
catch (Exception ex) {
// Do nothing
}
return false;
}
try {
mPrinter.sendData(Printer.PARAM_DEFAULT);
}
catch (Exception e) {
ShowMsg.showException(e, "sendData", mContext);
try {
mPrinter.disconnect();
}
catch (Exception ex) {
// Do nothing
}
return false;
}
return true;
}
public boolean connectPrinter(String receiptPrintIP) {
boolean isBeginTransaction = false;
if (mPrinter == null) {
return false;
}
try {
mPrinter.connect(receiptPrintIP, Printer.PARAM_DEFAULT);
}
catch (Exception e) {
ShowMsg.showException(e, "connect", mContext);
return false;
}
try {
mPrinter.beginTransaction();
isBeginTransaction = true;
}
catch (Exception e) {
ShowMsg.showException(e, "beginTransaction", mContext);
}
if (isBeginTransaction == false) {
try {
mPrinter.disconnect();
}
catch (Epos2Exception e) {
// Do nothing
return false;
}
}
return true;
}