Barcode scanning pause and resume on android - java

I am starting to experience on java in android.
I have 3 EditText on the layout.
I setup a barcode scanning window to scan the barcode.
After getting the first barcode, i pause the scanning and place it on the first EditText View.
Then i resume.
The problem is that after the first scan, the camera does not scan again.
I tried many method, pause then resume and it still does not work.
Can someone help?
The code look like this.
private CompoundBarcodeView barcodeView;
private BarcodeCallback callback = new BarcodeCallback() {
#Override
public void barcodeResult(BarcodeResult result) {
String code = null;
if (result.getText() != null) {
code = result.getText();
if (code != null) {
barcodeView.pause();
job01 = (EditText) findViewById(R.id.jobTicket01);
if (job01.getText().toString().trim().equals("")) {
job01.setText(code);
code = null;
}else {
if (job02.getText().toString().trim().equals("")) {
job02.setText(code);
code = null;
} else{
}
}
}
}
barcodeView.resume();
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
Thank in advance.
Teddy

I just avoid parsing data from the scan for a few seconds.
I set up 2 values one for the data and another for the timestamp.
String barcodeData = "";
Long scanTime = 0L;
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (barcodes.size() != 0) {
txtBarcodeValue.post(new Runnable() {
#Override
public void run() {
if(barcodeData.equals("") && scanTime.equals(0L)){
barcodeData = barcodes.valueAt(0).displayValue;
scanTime = System.currentTimeMillis();
Log.d(TAG, "Barcode" + barcodeData);
}else if (!barcodeData.equals(barcodes.valueAt(0).displayValue)){
barcodeData = barcodes.valueAt(0).displayValue;
scanTime = System.currentTimeMillis();
Log.d(TAG, "New Barcode Scanned" + barcodeData);
}else if (barcodeData.equals(barcodes.valueAt(0).displayValue) && scanTime>(System.currentTimeMillis()-2500)) {
//Do Nothing
Log.d(TAG, "Barcode Ignored ---------------" + barcodeData);
}else{
barcodeData ="";
scanTime = 0L;
}
}
});
}
}

Related

App crashes whenever click button and edit text is empty or filled with short alphabets except url

and this is my code App crashes whenever click button and edit text is empty or filled with short alphabets except url upload solution as fast as you can its but when i add the url correct it downloades the file without crashing my app is for downloading twitter videos .
java.lang.StringIndexOutOfBoundsException: length=0; index=-1
at java.lang.String.substring(String.java:1893)
at com.gabbaraman.statussaver.Models.TwitterVideoDownloader.getVideoId(TwitterVideoDownloader.java:67)
at com.gabbaraman.statussaver.Models.TwitterVideoDownloader.DownloadVideo(TwitterVideoDownloader.java:76)
at com.gabbaraman.statussaver.Activities.Twitter$1.onClick(Twitter.java:31)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22462)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6361)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
public class TwitterVideoDownloader implements VideoDownloader {
public Context context;
private String VideoURL;
private String VideoTitle;
public TwitterVideoDownloader(Context context, String videoURL) {
this.context = context;
VideoURL = videoURL;
}
#Override
public String createDirectory() {
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "My Video Downloader");
File subFolder = null;
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
else {
boolean success1 = true;
subFolder = new File(folder.getPath()+File.separator+"Twitter Videos");
if(!subFolder.exists())
{
success1 = subFolder.mkdirs();
}
}
assert subFolder != null;
return subFolder.getPath();
}
#Override
public String getVideoId(String link) {
if(link.contains("?"))
{
link = link.substring(link.indexOf("status"));
link = link.substring(link.indexOf("/")+1,link.indexOf("?"));
}
else {
link = link.substring(link.indexOf("status"));
link = link.substring(link.indexOf("/")+1);
}
return link;
}
#Override
public void DownloadVideo() {
AndroidNetworking.post("https://twittervideodownloaderpro.com/twittervideodownloadv2/index.php")
.addBodyParameter("id",getVideoId(VideoURL))
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
//Log.e("Hello", response.toString());
String URL = response.toString();
if (URL.isEmpty())
{
Toast.makeText(context,"Empty",Toast.LENGTH_SHORT).show();
}
if(URL.contains("url")){
URL = URL.substring(URL.indexOf("url"));
URL = URL.substring(ordinalIndexOf(URL,"\"",1)+1,ordinalIndexOf(URL,"\"",2));
if(URL.contains("\\"))
{
URL = URL.replace("\\","");
}
//Log.e("HelloURL",URL);
if(URLUtil.isValidUrl(URL))
{
String path = createDirectory();
if(VideoTitle == null || VideoTitle.equals(""))
{
VideoTitle = "TwitterVideo" + new Date().toString()+".mp4";
}
else {
VideoTitle = VideoTitle + ".mp4";
}
File newFile = new File(path, VideoTitle);
try {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
request.allowScanningByMediaScanner();
request.setDescription("Downloading")
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI)
.setDestinationUri(Uri.fromFile(newFile))
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setVisibleInDownloadsUi(true)
.setTitle(VideoTitle);
DownloadManager manager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
assert manager != null;
long downLoadID = manager.enqueue(request);
} catch (Exception e) {
if (Looper.myLooper()==null)
Looper.prepare();
Toast.makeText(context, "Video Can't be downloaded! Try Again", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}
else {
if (Looper.myLooper()==null)
Looper.prepare();
Toast.makeText(context, "No Video Found", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}
else {
if (Looper.myLooper()==null)
Looper.prepare();
Toast.makeText(context, "No Video Found", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}
#Override
public void onError(ANError anError) {
if (Looper.myLooper()==null)
Looper.prepare();
Toast.makeText(context, "Invalid Video URL", Toast.LENGTH_SHORT).show();
Looper.loop();
}
});
}
private static int ordinalIndexOf(String str, String substr, int n) {
int pos = -1;
do {
pos = str.indexOf(substr, pos + 1);
} while (n-- > 0 && pos != -1);
return pos;
}
}
From the exception itself, it appears you are trying to get a substring from something that is either empty or shorter than what you wanted to get a substring from. If I had to guess, your indexOf methods are returning a negative index (-1) and you cannot perform a substring on a negative value.
Except debugging your application, and seeing what the value of VideoURL is, I would advise you to do the following:
In your constructor for the class, TwitterVideoDownloader, check if the videoURL parameter is not null or empty
If it is, decide on a default string to insert into your VideoURL variable.
In your getVideoId, before making any checks the passed parameter, first make sure it is not empty or null

How can I make for loop wait in each iteration?

I am trying to wait after each for loop using Threads in my application but I have a problem. This for loop has to be executed when the film from URL is playing but...
Unfortunately the loop is executed with pauses that I put into the code and later the film starts with text updated. This should start simultaneously. The for loop and the film. During the film the texts should be updated one after another.
NOTE: I shorted the ArrayList dict to make code easier to understand.
NOTE2: The app tries to open video file from URL but it gives me a message:
W/MediaPlayer: Couldn't open (Video URL) : java.io.FileNotFoundException: No content provider: (Video URL).
EDIT: I am putting an entire class code for you.
public class Video extends Activity {
private VideoView videoView;
private TextView englishTrans1;
private TextView polishTrans1;
private TextView englishTrans2;
private TextView polishTrans2;
private TextView englishTrans3;
private TextView polishTrans3;
int j = 0;
int i =0;
public static final String TAG = "My tag";
ArrayList<Translations> dict = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
videoView = findViewById(R.id.video_view1);
MediaController mMedia = new MediaController(this);
mMedia.setMediaPlayer(videoView);
mMedia.setAnchorView(videoView);
videoView.setMediaController(mMedia);
String path1 = (HERE IS VIDEO URL);
Uri uri = Uri.parse(path1);
videoView.setVideoURI(uri);
videoView.start();
englishTrans1 = findViewById(R.id.english_trans1);
polishTrans1 = findViewById(R.id.polish_trans1);
englishTrans2 = findViewById(R.id.english_trans2);
polishTrans2 = findViewById(R.id.polish_trans2);
englishTrans3 = findViewById(R.id.english_trans3);
polishTrans3 = findViewById(R.id.polish_trans3);
dict.add(new Translations("kot","cat"));
dict.add(new Translations("pies","dog"));
dict.add(new Translations("kawa","coffee"));
dict.add(new Translations("herbata","tea"));
dict.add(new Translations("kościół","church"));
dict.add(new Translations("ślub","wedding"));
final Handler h = new Handler() {
#Override
public void handleMessage(#NonNull Message msg) {
for(Translations x : dict){
try {
synchronized (this) {
Thread.sleep(2000);
}
}catch (InterruptedException e){
}
switch (j) {
case 1: {
Log.d(TAG, "First word translated");
englishTrans1.setText(x.getEnglishWord());
polishTrans1.setText(x.getPolishWord());
break;
}
case 2: {
Log.d(TAG, "Second word translated");
englishTrans2.setText(x.getEnglishWord());
polishTrans2.setText(x.getPolishWord());
break;
}
case 3: {
Log.d(TAG, "Third word translated");
englishTrans3.setText(x.getEnglishWord());
polishTrans3.setText(x.getPolishWord());
break;
}
}
if (j < 3) {
j++;
} else {
j = 1;
}
}
}
};
Runnable r = new Runnable() {
#Override
public void run() {
h.sendEmptyMessage(0);
}
};
Thread t = new Thread(r);
t.start();
}
}
Translations.java class with constructor.
public class Translations {
private String polishWord;
private String englishWord;
public Translations(){
}
public Translations(String mPolishWord,String mEnglishWord){
polishWord = mPolishWord;
englishWord = mEnglishWord;
}
public String getPolishWord() {
return polishWord;
}
public void setPolishWord(String polishWord) {
this.polishWord = polishWord;
}
public String getEnglishWord() {
return englishWord;
}
public void setEnglishWord(String englishWord) {
this.englishWord = englishWord;
}
}
Why loop at all, The "subtitles" as that is what the code snippet is doing, are linked to the video.
What if the person scrubs the film and fast forwards or rewinds, Most subtitle setups have the sentence on screen linked with a timecode for the film, so you then have the subtitle triggered on a change of timecode on the playing video, and pass in the timecode so it will get the sentence for that part of the video and display it on screen.
I have found a solution. The issue was that I was trying to sleep the Thread in Handler. The JVM thought that the main thread should be paused, not the "t" Thread. I moved the Thread.sleep() method to run() and the for loop too. I left only switch() in the Handler to change the UI. It works right now.
final Handler h = new Handler() {
#Override
public void handleMessage(#NonNull Message msg) {
Translations x = dict.get(i-1);
switch (j) {
case 1: {
Log.d(TAG, "First word translated");
englishTrans1.setText(x.getEnglishWord());
polishTrans1.setText(x.getPolishWord());
break;
}
case 2: {
Log.d(TAG, "Second word translated");
englishTrans2.setText(x.getEnglishWord());
polishTrans2.setText(x.getPolishWord());
break;
}
case 3: {
Log.d(TAG, "Third word translated");
englishTrans3.setText(x.getEnglishWord());
polishTrans3.setText(x.getPolishWord());
break;
}
}
}
};
Runnable r = new Runnable() {
#Override
public void run() {
for(i = 0;i<dict.size();i++) {
try {
Thread.sleep(2000);
}catch (InterruptedException e){
}
if (j < 3) {
j++;
} else {
j = 1;
}
h.sendEmptyMessage(0);
}
}
};
Thread t = new Thread(r);
t.start();
}
}

NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true

I Implemented code for download Expansion file from play store, My file in getting download but in between downloading .OBB file I am getting below Error
NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
Code :
public class SampleDownloaderActivity extends Activity implements IDownloaderClient {
private static final String LOG_TAG = "LVLDownloader";
private ProgressBar mPB;
private TextView mStatusText;
private TextView mProgressFraction;
private TextView mProgressPercent;
private TextView mAverageSpeed;
private TextView mTimeRemaining;
private View mDashboard;
private View mCellMessage;
private Button mPauseButton;
private Button mWiFiSettingsButton;
private boolean mStatePaused;
private int mState;
private IDownloaderService mRemoteService;
private IStub mDownloaderClientStub;
private void setState(int newState) {
if (mState != newState) {
mState = newState;
mStatusText.setText(Helpers.getDownloaderStringResourceIDFromState(newState));
}
}
private void setButtonPausedState(boolean paused) {
mStatePaused = paused;
int stringResourceID = paused ? R.string.text_button_resume :
R.string.text_button_pause;
mPauseButton.setText(stringResourceID);
}
private static class XAPKFile {
public final boolean mIsMain;
public final int mFileVersion;
public final long mFileSize;
XAPKFile(boolean isMain, int fileVersion, long fileSize) {
mIsMain = isMain;
mFileVersion = fileVersion;
mFileSize = fileSize;
}
}
private static final XAPKFile[] xAPKS = {
new XAPKFile(
true, // true signifies a main file
1, // the version of the APK that the file was uploaded
// against
40257 // the length of the file in bytes
),
new XAPKFile(
false, // false signifies a patch file
1, // the version of the APK that the patch file was uploaded
// against
0L // the length of the patch file in bytes
)
};
boolean expansionFilesDelivered() {
for (XAPKFile xf : xAPKS) {
String fileName = Helpers.getExpansionAPKFileName(this, xf.mIsMain, xf.mFileVersion);
if (!Helpers.doesFileExist(this, fileName, xf.mFileSize, false))
return false;
}
return true;
}
void validateXAPKZipFiles() {
AsyncTask<Object, DownloadProgressInfo, Boolean> validationTask = new AsyncTask<Object, DownloadProgressInfo, Boolean>() {
#Override
protected void onPreExecute() {
mDashboard.setVisibility(View.VISIBLE);
mCellMessage.setVisibility(View.GONE);
mStatusText.setText(R.string.text_verifying_download);
mPauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCancelValidation = true;
}
});
mPauseButton.setText(R.string.text_button_cancel_verify);
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Object... params) {
for (XAPKFile xf : xAPKS) {
String fileName = Helpers.getExpansionAPKFileName(
SampleDownloaderActivity.this,
xf.mIsMain, xf.mFileVersion);
if (!Helpers.doesFileExist(SampleDownloaderActivity.this, fileName,
xf.mFileSize, false))
return false;
fileName = Helpers
.generateSaveFileName(SampleDownloaderActivity.this, fileName);
ZipResourceFile zrf;
byte[] buf = new byte[1024 * 256];
try {
zrf = new ZipResourceFile(fileName);
ZipEntryRO[] entries = zrf.getAllEntries();
/**
* First calculate the total compressed length
*/
long totalCompressedLength = 0;
for (ZipEntryRO entry : entries) {
totalCompressedLength += entry.mCompressedLength;
}
float averageVerifySpeed = 0;
long totalBytesRemaining = totalCompressedLength;
long timeRemaining;
/**
* Then calculate a CRC for every file in the Zip file,
* comparing it to what is stored in the Zip directory.
* Note that for compressed Zip files we must extract
* the contents to do this comparison.
*/
for (ZipEntryRO entry : entries) {
if (-1 != entry.mCRC32) {
long length = entry.mUncompressedLength;
CRC32 crc = new CRC32();
DataInputStream dis = null;
try {
dis = new DataInputStream(
zrf.getInputStream(entry.mFileName));
long startTime = SystemClock.uptimeMillis();
while (length > 0) {
int seek = (int) (length > buf.length ? buf.length
: length);
dis.readFully(buf, 0, seek);
crc.update(buf, 0, seek);
length -= seek;
long currentTime = SystemClock.uptimeMillis();
long timePassed = currentTime - startTime;
if (timePassed > 0) {
float currentSpeedSample = (float) seek
/ (float) timePassed;
if (0 != averageVerifySpeed) {
averageVerifySpeed = SMOOTHING_FACTOR
* currentSpeedSample
+ (1 - SMOOTHING_FACTOR)
* averageVerifySpeed;
} else {
averageVerifySpeed = currentSpeedSample;
}
totalBytesRemaining -= seek;
timeRemaining = (long) (totalBytesRemaining / averageVerifySpeed);
this.publishProgress(
new DownloadProgressInfo(
totalCompressedLength,
totalCompressedLength
- totalBytesRemaining,
timeRemaining,
averageVerifySpeed)
);
}
startTime = currentTime;
if (mCancelValidation)
return true;
}
if (crc.getValue() != entry.mCRC32) {
Log.e(Constants.TAG,
"CRC does not match for entry: "
+ entry.mFileName);
Log.e(Constants.TAG,
"In file: " + entry.getZipFileName());
return false;
}
} finally {
if (null != dis) {
dis.close();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
return true;
}
#Override
protected void onProgressUpdate(DownloadProgressInfo... values) {
onDownloadProgress(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
mDashboard.setVisibility(View.VISIBLE);
mCellMessage.setVisibility(View.GONE);
mStatusText.setText(R.string.text_validation_complete);
mPauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
mPauseButton.setText(android.R.string.ok);
} else {
mDashboard.setVisibility(View.VISIBLE);
mCellMessage.setVisibility(View.GONE);
mStatusText.setText(R.string.text_validation_failed);
mPauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
mPauseButton.setText(android.R.string.cancel);
}
super.onPostExecute(result);
}
};
validationTask.execute(new Object());
}
/**
* If the download isn't present, we initialize the download UI. This ties
* all of the controls into the remote service calls.
*/
private void initializeDownloadUI() {
mDownloaderClientStub = DownloaderClientMarshaller.CreateStub
(this, SampleDownloaderService.class);
setContentView(R.layout.main);
mPB = (ProgressBar) findViewById(R.id.progressBar);
mStatusText = (TextView) findViewById(R.id.statusText);
mProgressFraction = (TextView) findViewById(R.id.progressAsFraction);
mProgressPercent = (TextView) findViewById(R.id.progressAsPercentage);
mAverageSpeed = (TextView) findViewById(R.id.progressAverageSpeed);
mTimeRemaining = (TextView) findViewById(R.id.progressTimeRemaining);
mDashboard = findViewById(R.id.downloaderDashboard);
mCellMessage = findViewById(R.id.approveCellular);
mPauseButton = (Button) findViewById(R.id.pauseButton);
mWiFiSettingsButton = (Button) findViewById(R.id.wifiSettingsButton);
final ImageView image = (ImageView) findViewById(R.id.image);
mPauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mStatePaused) {
mRemoteService.requestContinueDownload();
} else {
mRemoteService.requestPauseDownload();
}
setButtonPausedState(!mStatePaused);
}
});
mWiFiSettingsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
});
Button resumeOnCell = (Button) findViewById(R.id.resumeOverCellular);
resumeOnCell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mRemoteService.setDownloadFlags(IDownloaderService.FLAGS_DOWNLOAD_OVER_CELLULAR);
mRemoteService.requestContinueDownload();
mCellMessage.setVisibility(View.GONE);
}
});
final OnObbStateChangeListener mEventListener = new OnObbStateChangeListener() {
#Override
public void onObbStateChange(String path, int state) {
Log.d("", "path=" + path + "; state=" + state);
if (state == OnObbStateChangeListener.MOUNTED) {
Log.d("", "OPEN");
} else {
Log.d("", "ERROR");
}
}
};
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String packageName = getPackageName();
File root = Environment.getExternalStorageDirectory();
File expPath = new File(root.toString() + "/Android/obb/" + packageName);
try {
/* if (expPath.exists()) {
String strMainPath = expPath + File.separator + "main." + getPackageManager().getPackageInfo(getPackageName(), 0).versionCode + "." + packageName + ".obb";
File f = new File(strMainPath);
if (f.exists()) {
Log.e("Path ", "=====>Exists");
} else {
Log.e("Path ", "=====> Not Exists");
}
ZipResourceFile zip = new ZipResourceFile(strMainPath);
InputStream iStream = zip.getInputStream("stage1_popup");
BitmapFactory.Options option = new BitmapFactory.Options();
option.inPurgeable = true;
File imageFile = new File("/storage/emulated/0/Android/obb/mintshowapp/com/fileexpansionexample/main/3/mintshowapp/com/fileexpansionexample/obb/stage1_popup.gif");
if(imageFile.exists()){
String path=imageFile.getAbsolutePath();
Bitmap bitmap=BitmapFactory.decodeFile(path);
image.setImageBitmap(bitmap);
}
Glide.with(SampleDownloaderActivity.this).load(imageFile).into(image);
}*/
StorageManager mSM = (StorageManager) getApplicationContext().getSystemService(STORAGE_SERVICE);
File file = Environment.getExternalStorageDirectory();
String mObbPath = new File(file, "main.1.app.com.expanson.obb").getPath();
/*if (mObbPath != null && mObbPath.startsWith("/")) {
mObbPath = mObbPath.substring(1);
}*/
if (mSM.mountObb(mObbPath, null, mEventListener)) {
Log.d("", "MAIN");
} else {
Log.d("", "ERROR");
}
String path = mSM.getMountedObbPath(mObbPath);
System.out.print(path);
Glide.with(SampleDownloaderActivity.this).load(path + "/stage1_popup.gif").into(image);
} catch (Exception e) {
}
}
});
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeDownloadUI();
if (!expansionFilesDelivered()) {
try {
Intent launchIntent = SampleDownloaderActivity.this
.getIntent();
Intent intentToLaunchThisActivityFromNotification = new Intent(
SampleDownloaderActivity
.this, SampleDownloaderActivity.this.getClass());
intentToLaunchThisActivityFromNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction());
if (launchIntent.getCategories() != null) {
for (String category : launchIntent.getCategories()) {
intentToLaunchThisActivityFromNotification.addCategory(category);
}
}
// Build PendingIntent used to open this activity from
// Notification
PendingIntent pendingIntent = PendingIntent.getActivity(
SampleDownloaderActivity.this,
0, intentToLaunchThisActivityFromNotification,
PendingIntent.FLAG_UPDATE_CURRENT);
// Request to start the download
int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
pendingIntent, SampleDownloaderService.class);
if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
// The DownloaderService has started downloading the files,
// show progress
initializeDownloadUI();
return;
} // otherwise, download not needed so we fall through to
// starting the movie
} catch (NameNotFoundException e) {
Log.e(LOG_TAG, "Cannot find own package! MAYDAY!");
e.printStackTrace();
}
} else {
validateXAPKZipFiles();
}
}
/**
* Connect the stub to our service on start.
*/
#Override
protected void onStart() {
if (null != mDownloaderClientStub) {
mDownloaderClientStub.connect(this);
}
super.onStart();
}
/**
* Disconnect the stub from our service on stop
*/
#Override
protected void onStop() {
if (null != mDownloaderClientStub) {
mDownloaderClientStub.disconnect(this);
}
super.onStop();
}
#Override
public void onServiceConnected(Messenger m) {
mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);
mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
}
#Override
public void onDownloadStateChanged(int newState) {
setState(newState);
boolean showDashboard = true;
boolean showCellMessage = false;
boolean paused;
boolean indeterminate;
switch (newState) {
case IDownloaderClient.STATE_IDLE:
// STATE_IDLE means the service is listening, so it's
// safe to start making calls via mRemoteService.
paused = false;
indeterminate = true;
break;
case IDownloaderClient.STATE_CONNECTING:
case IDownloaderClient.STATE_FETCHING_URL:
showDashboard = true;
paused = false;
indeterminate = true;
break;
case IDownloaderClient.STATE_DOWNLOADING:
paused = false;
showDashboard = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_FAILED_CANCELED:
case IDownloaderClient.STATE_FAILED:
case IDownloaderClient.STATE_FAILED_FETCHING_URL:
case IDownloaderClient.STATE_FAILED_UNLICENSED:
paused = true;
showDashboard = false;
indeterminate = false;
break;
case IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION:
case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION:
showDashboard = false;
paused = true;
indeterminate = false;
showCellMessage = true;
break;
case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
paused = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_PAUSED_ROAMING:
case IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE:
paused = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_COMPLETED:
showDashboard = false;
paused = false;
indeterminate = false;
validateXAPKZipFiles();
return;
default:
paused = true;
indeterminate = true;
showDashboard = true;
}
int newDashboardVisibility = showDashboard ? View.VISIBLE : View.GONE;
if (mDashboard.getVisibility() != newDashboardVisibility) {
mDashboard.setVisibility(newDashboardVisibility);
}
int cellMessageVisibility = showCellMessage ? View.VISIBLE : View.GONE;
if (mCellMessage.getVisibility() != cellMessageVisibility) {
mCellMessage.setVisibility(cellMessageVisibility);
}
mPB.setIndeterminate(indeterminate);
setButtonPausedState(paused);
}
/**
* Sets the state of the various controls based on the progressinfo object
* sent from the downloader service.
*/
#Override
public void onDownloadProgress(DownloadProgressInfo progress) {
mAverageSpeed.setText(getString(R.string.kilobytes_per_second,
Helpers.getSpeedString(progress.mCurrentSpeed)));
mTimeRemaining.setText(getString(R.string.time_remaining,
Helpers.getTimeRemaining(progress.mTimeRemaining)));
progress.mOverallTotal = progress.mOverallTotal;
mPB.setMax((int) (progress.mOverallTotal >> 8));
mPB.setProgress((int) (progress.mOverallProgress >> 8));
mProgressPercent.setText(Long.toString(progress.mOverallProgress
* 100 /
progress.mOverallTotal) + "%");
mProgressFraction.setText(Helpers.getDownloadProgressString
(progress.mOverallProgress,
progress.mOverallTotal));
}
#Override
protected void onDestroy() {
this.mCancelValidation = true;
super.onDestroy();
}
}
LOG:
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
10-01 11:32:04.453 12394-12414/app.com.expanson I/zygote64: Do full code cache collection, code=125KB, data=69KB
10-01 11:32:04.454 12394-12414/app.com.expanson I/zygote64: After code cache collection, code=123KB, data=62KB
10-01 11:32:04.611 12394-12473/app.com.expanson I/RequestAddCookies: Cookie store not available in HTTP context
10-01 11:32:04.702 12394-12473/app.com.expanson I/ResponseProcessCookies: Cookie store not available in HTTP context
10-01 11:32:04.877 12394-12414/app.com.expanson I/zygote64: Do partial code cache collection, code=125KB, data=66KB
After code cache collection, code=125KB, data=66KB
Increasing code cache capacity to 512KB
10-01 11:32:04.936 12394-12473/app.com.expanson I/RequestAddCookies: Cookie store not available in HTTP context
10-01 11:32:04.964 12394-12473/app.com.expanson I/ResponseProcessCookies: Cookie store not available in HTTP context
10-01 11:32:05.177 12394-12473/app.com.expanson D/CancellableIntentService: stopSelf
10-01 11:32:05.179 12394-12473/app.com.expanson D/CancellableIntentService: afterStopSelf
10-01 11:32:05.209 12394-12394/app.com.expanson D/CancellableIntentService: onDestroy
Check the internet on Emulator. I have a problem because internet d'not worked on my emulator. For more information how to enable internet:
Android emulator not able to access the internet

AccessAbiltyService not working when screen turn off android

I develop a android app here hava a accessabilty service for read window text from ussd dial.
I am success for do it and it working nice. But when screen light turn off and get locked The accessAbiltyService not working.
I provide my coding here of access ability service
please see and give me suggestion how I solve it that it working for screen on/off.
public class USSDService extends AccessibilityService {
public static String TAG = USSDService.class.getSimpleName();
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
AccessibilityNodeInfo source = event.getSource();
/* if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && !event.getClassName().equals("android.app.AlertDialog")) { // android.app.AlertDialog is the standard but not for all phones */
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && !String.valueOf(event.getClassName()).contains("AlertDialog")) {
return;
}
if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && (source == null || !source.getClassName().equals("android.widget.TextView"))) {
return;
}
if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && TextUtils.isEmpty(source.getText())) {
return;
}
List<CharSequence> eventText;
if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
eventText = event.getText();
} else {
eventText = Collections.singletonList(source.getText());
}
String text = processUSSDText(eventText);
if( TextUtils.isEmpty(text) ) return;
// Close dialog
performGlobalAction(GLOBAL_ACTION_BACK); // This works on 4.1+ only
if (source != null) {
//capture the EditText simply by using FOCUS_INPUT (since the EditText has the focus), you can probably find it with the viewId input_field
AccessibilityNodeInfo inputNode = source.findFocus(AccessibilityNodeInfo.FOCUS_INPUT);
if (inputNode != null) {//prepare you text then fill it using ACTION_SET_TEXT
//saff 1
if (text.indexOf("Default") >= 0) {
Bundle arguments = new Bundle();
arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE,"0");
inputNode.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
//"Click" the Send button
List<AccessibilityNodeInfo> list = source.findAccessibilityNodeInfosByText("Send");
for (AccessibilityNodeInfo node : list) {
node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
}
}
//staf 2
if (text.indexOf("topUp") >= 0) {
Bundle arguments = new Bundle();
arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE,"1");
inputNode.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
//"Click" the Send button
List<AccessibilityNodeInfo> list = source.findAccessibilityNodeInfosByText("Send");
for (AccessibilityNodeInfo node : list) {
node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
}
}
}
}
Log.d(TAG, text);
// Handle USSD response here
}
private String processUSSDText(List<CharSequence> eventText) {
for (CharSequence s : eventText) {
String text = String.valueOf(s);
// Return text if text is the expected ussd response
if( true ) {
return text;
}
}
return null;
}
#Override
public void onInterrupt() {
}
#Override
protected void onServiceConnected() {
super.onServiceConnected();
Log.d(TAG, "onServiceConnected");
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.flags = AccessibilityServiceInfo.DEFAULT;
info.packageNames = new String[]{"com.android.phone"};
info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
setServiceInfo(info);
}
}
Thanks
For help

Android Broadcast Receiver as inner static class Passing a String

Probably you want to jump to Update 2 and check the code if needed
I am building a barcode scanner and having difficulty in passing data that I have captured from an inner class that extends BroadcastReceiver to MainActivity class, I do understand the difference between static and non static objects, but I got stuck.
Cant invoke my logic method from the inner class.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
protected void onCreate(Bundle savedInstanceState){...}
public void Logic(String result){// Do something...}
//Inner Class
public static class ScanResultReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {...
// data here captured fine!
// Here I want to send my data to MainActivity Logic(result)
Logic(result);
}
}
If I make "Logic()" as Static method, I get a lot of errors regards to calling non static from static method from Toaster/variables..etc
Update
This method is inside MainActivity, I do want to call it from the inner class
public void Logic(String result) throws Exception {
//prepare the results
if (mDecodeResult.decodeValue.substring(0, 1).equals("{") && mDecodeResult.decodeValue.substring(mDecodeResult.decodeValue.length() - 1).equals("}")) {
if (!(mDecodeResult.decodeValue.equals("SCAN AGAIN"))) {
mDecodeResult.decodeValue = mDecodeResult.decodeValue.substring(1);
mDecodeResult.decodeValue = mDecodeResult.decodeValue.substring(0, mDecodeResult.decodeValue.length() - 1);
}
}
if (mDecodeResult.decodeValue.equals("SCAN AGAIN")) {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received! Please Scan Again", Toast.LENGTH_SHORT);
toast.show();
} else if (mDecodeResult.decodeValue != null && tourFlag) {
String formattedDate = getTime();
String scanContent = mDecodeResult.decodeValue;
boolean found = false;
if (ForcedOrRandom.equals("Random")) {
String[] b;
for (String l : ToBeScanned) {
b = l.split(":");
if (scanContent.equals(b[0])) {
Log.d("remove", "scanned: " + scanContent);
Log.d("remove", "remove : " + b[0]);
found = true;
}
}
} else if (ForcedOrRandom.equals("Forced")) {
String[] b;
for (String I : FTobeScannedNext) {
b = I.split(":");
if (scanContent.equals(b[0])) {
Log.d("remove", "scanned: " + scanContent);
Log.d("remove", "remove : " + b[0]);
found = true;
}
}
}// end Skip/Forced
if (listLoaded && found) {
theResult[resultCount].setTourID(currentTourId);
theResult[resultCount].setBarcode(scanContent);
BarcodeObject a = getBarcodeInfo(scanContent);
if (ForcedOrRandom.equals("Random")) {
} else {
if (myTimer != null) {
myTimer.cancel();
Timer = (TextView) findViewById(R.id.timertext);
Timer.setText("");
PlayOrPause.setVisibility(View.INVISIBLE);
}
boolean isTimed = a.getForceNextBarCode().equals("");
if (!(isTimed)) {
PlayOrPause = (ImageButton) findViewById(R.id.PlayPause);
PlayOrPause.setVisibility(View.VISIBLE);
PlayOrPause.setImageResource(R.drawable.pause);
final AlertDialog.Builder timealert = new AlertDialog.Builder(this);
PlayOrPause.setEnabled(true);
long duration = Integer.parseInt(a.getForceNextBarCode());
duration = duration * 60000;
myTimer = new CountDownTimer(duration, 1000) {
#Override
public void onTick(long millisuntilFinished) {
int seconds = (int) (millisuntilFinished / 1000) % 60;
int minutes = (int) ((millisuntilFinished / (1000 * 60)) % 60);
Timer = (TextView) findViewById(R.id.timertext);
Timer.setText(minutes + ":" + seconds);
timeLeft = millisuntilFinished;
}
String value = "";
#Override
public void onFinish() {
Timer = (TextView) findViewById(R.id.timertext);
theResult[resultCount].setScanstatus(scanStatusTimeElapsed);
timealert.setTitle("Site Secure");
timealert.setMessage("Time Elapsed! Enter reason");
// Set an EditText view to get user input
final EditText input = new EditText(MainActivity.this);
timealert.setView(input);
timealert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
value = input.getText().toString();
// Do something with value!
while (value.equals("")) {
timealert.setView(input);
timealert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
value = input.getText().toString();
}
});
}
theResult[resultCount].setComments(value);
}
});
timealert.setIcon(android.R.drawable.ic_dialog_alert);
timealert.show();
Timer.setText(R.string.Time_Elapsed);
}
};
myTimer.start();
}
}
theResult[resultCount].setBarcodeID(a.getBarCodeId());
theResult[resultCount].setDateScanned(formattedDate);
theResult[resultCount].setSkipped(getResources().getString(R.string.Scanned));
}// end big if listLoaded && found
contentTxt.setText(scanContent);
Toaster(getResources().getString(R.string.TScan_Complete));
if (mainScanCounter == 0) {
if (tourDecider(scanContent)) {//tour decider is called to determine if this is boolJanamScanner random or forced tour
tourId = scanContent;
if (!(readFileOffline(siteSecurePath + "/doneTourNumber.txt").equals(""))) {
SYNC.setEnabled(true);
}
}
} else if (mainScanCounter > 0) {
if (ForcedOrRandom.equals("Random")) {
ListManager(scanContent);
} else {
ForcedListManager(scanContent);
}
}
} else if (mDecodeResult.decodeValue != null && officerScanFlag) {
TextView officertextview = (TextView) findViewById(R.id.officerid);
UserObject theofficer = getUserInfo(mDecodeResult.decodeValue);
if (theofficer == null) {
popUps("Error", "Invalid Officer ID, Please Rescan", "TITLE");
officerScan.setEnabled(true);
} else if (theofficer != null) {
// officer ID found need to store it for backup
officerId = theofficer.getOfficerid();
makeFileOffline(officerId, "officerID");
officertextview.setText(theofficer.getUsername());
officerScanFlag = false;
startTimersOfficerID = getTime();
tourBtn.setEnabled(true);
}
}
if (mDecodeResult.decodeValue != null && exceptionFlag) {
Log.d("check", "exception was clicked");
String ex_result = mDecodeResult.decodeValue;
for (int i = 0; i < theExceptions.length; i++) {
if (!(theExceptions[i].getBarcode().equals(ex_result))) {
String refnum = theExceptions[i].getRefNum();
i = theExceptions.length;
theResult[resultCount - 1].setException(refnum);
}
}
exceptionFlag = false;
Toaster(getResources().getString(R.string.TScan_Complete));
}
} // Logic Ends
Update 2
Not sure if I need to have another thread for this but I will put what I have found, my issue have narrowed to the following:
I am waiting on an intent called
<action android:name="device.scanner.USERMSG" />
with a permission
android:permission="com.permission.SCANNER_RESULT_RECEIVER"
now my issue
if a user tap button and released in less than .5 second onKeyup() event will be fired before my onReceive() that is inside the static class which is extends BroadcastReceiver, and that causes problem because Logic() will be invoked before updating the String inside onReceive()
if user hold the button long enough, onReceive will be invoked and everything is good and happy.
How can I make sure that onReceive() always invoked first?
public boolean onKeyUp(int keycode, KeyEvent event) {
if (keycode == 221 || keycode == 220 || keycode == 222) {
Logic(result);
}
return true;
}
Move this line of code:
public void Logic(String result){// Do something...}
inside your class ScanResultReceiver and it will work for sure. Your code should look like this:
public static class ScanResultReceiver extends BroadcastReceiver {
public ScanResultReceiver() {
//empty constructor
}
#Override
public void onReceive(Context context, Intent intent) {...
// data here captured fine!
// Here I want to send my data to MainActivity Logic(result)
Logic(result);
}
public void Logic(String result){/* ... */}
}

Categories

Resources