Work manager getworkinfobyliveiddata on changed function not being called - java

This is the implementation of downloadRequestqueue class inside a library .This java file uses work manager inside its add request function.But the work manager getworkinfobyliveId function is not called.I think the problem is because of lifecycle owner of this java class which also I have implemented in this class
public class DownloadRequestQueue extends AppCompatActivity implements LifecycleOwner
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLifecycleRegistry=new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
}
#Override
public void onStart() {
super.onStart();
mLifecycleRegistry=new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.STARTED);
}
#NonNull
#Override
public Lifecycle getLifecycle() {
mLifecycleRegistry=new LifecycleRegistry(this);
Log.d("uu",mLifecycleRegistry+"");
return mLifecycleRegistry;
}
public DownloadRequestQueue(Context context) {
this.context = context;
currentRequestMap = new ConcurrentHashMap<>();
sequenceGenerator = new AtomicInteger();
}
public static void initialize(Context context) {
getInstance(context);
}
public static DownloadRequestQueue getInstance(Context context) {
if (instance == null) {
synchronized (DownloadRequestQueue.class) {
if (instance == null) {
instance = new DownloadRequestQueue(context);
}
}
}
return instance;
}
private int getSequenceNumber() {
return sequenceGenerator.incrementAndGet();
}
public void pause(int downloadId) {
DownloadRequest request = currentRequestMap.get(downloadId);
if (request != null) {
request.setStatus(Status.PAUSED);
}
}
public void resume(int downloadId) {
final Response response = new Response();
final DownloadRequest request = currentRequestMap.get(downloadId);
if (request != null) {
request.setStatus(Status.QUEUED);
request.deliverStartEvent();
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
Log.d("fff",request.getOnProgressListener()+"");
String json = gson.toJson(request);
prefsEditor.putString("SerializableObject", json);
prefsEditor.commit();
Data data = new Data.Builder().putInt("ID", downloadId).build();
final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class).setInputData(data).build();
WorkManager.getInstance().enqueue(workRequest);
WorkManager.getInstance().getWorkInfoByIdLiveData(workRequest.getId()).observe(this, new Observer<WorkInfo>() {
#Override
public void onChanged(#Nullable WorkInfo workInfo) {
if (workInfo != null) {
Log.d("this","dip");
if (workInfo.getState().isFinished()) {
Data data = workInfo.getOutputData();
String output = data.getString("Response");
if (output.equals(Status.CANCELLED + "")) {
response.setCancelled(true);
}
if (output.equals(Status.PAUSED + "")) {
response.setPaused(true);
}
if (output.equals("abc")) {
Error error = new Error();
error.setConnectionError(true);
error.setConnectionException(new Exception());
response.setError(error);
}
if (output.equals("def")) {
Error error = new Error();
error.setServerError(true);
response.setError(error);
}
}
if (response.isSuccessful()) {
request.deliverSuccess();
} else if (response.isPaused()) {
request.deliverPauseEvent();
} else if (response.getError() != null) {
request.deliverError(response.getError());
} else if (!response.isCancelled()) {
request.deliverError(new Error());
}
}
}
});
// request.setFuture(Core.getInstance()
// .getExecutorSupplier()
// .forDownloadTasks()
// .submit(new DownloadRunnable(request)));
}
}
private void cancelAndRemoveFromMap(DownloadRequest request) {
if (request != null) {
request.cancel();
currentRequestMap.remove(request.getDownloadId());
}
}
public void cancel(int downloadId) {
DownloadRequest request = currentRequestMap.get(downloadId);
cancelAndRemoveFromMap(request);
}
public void cancel(Object tag) {
for (Map.Entry<Integer, DownloadRequest> currentRequestMapEntry : currentRequestMap.entrySet()) {
DownloadRequest request = currentRequestMapEntry.getValue();
if (request.getTag() instanceof String && tag instanceof String) {
final String tempRequestTag = (String) request.getTag();
final String tempTag = (String) tag;
if (tempRequestTag.equals(tempTag)) {
cancelAndRemoveFromMap(request);
}
} else if (request.getTag().equals(tag)) {
cancelAndRemoveFromMap(request);
}
}
}
public void cancelAll() {
for (Map.Entry<Integer, DownloadRequest> currentRequestMapEntry : currentRequestMap.entrySet()) {
DownloadRequest request = currentRequestMapEntry.getValue();
cancelAndRemoveFromMap(request);
}
}
public Status getStatus(int downloadId) {
DownloadRequest request = currentRequestMap.get(downloadId);
if (request != null) {
return request.getStatus();
}
return Status.UNKNOWN;
}
public void addRequest(final DownloadRequest request) {
Log.d("did", request.getUrl() + "");
final Response response = new Response();
Log.d("yoii", request.getOnProgressListener()+"");
request.setStatus(Status.QUEUED);
abc=request.getOnProgressListener()+"";
onProgressListener1=request.getOnProgressListener();
currentRequestMap.put(request.getDownloadId(), request);
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
Log.d("fff",request.getOnProgressListener()+"");
request.setOnProgressListener(request.getOnProgressListener());
String json = gson.toJson(request);
ArrayList<Integer> arrayList=new ArrayList<Integer>();
arrayList.add(1);
prefsEditor.putString("SerializableObject", json);
prefsEditor.commit();
if (request != null) {
Log.d("999", currentRequestMap.get(request.getDownloadId()).getUrl() + "");
}
if (request == null) {
Log.d("none", "bro");
}
if (request != null) {
Log.d("all", request.getUrl() + "");
}
if (request == null) {
Log.d("none", "bro");
}
Data data = new Data.Builder().putInt("ID", request.getDownloadId()).putString("status", request.getStatus() + "").build();
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class).setInputData(data).build();
WorkManager.getInstance().enqueue(workRequest);
Log.d("boss", "pls");
WorkManager.getInstance().getWorkInfoByIdLiveData(workRequest.getId()).observe(this, new Observer<WorkInfo>() {
#Override
public void onChanged(#Nullable WorkInfo workInfo) {
Log.d("abd","see");
if(workInfo==null){
Log.d("bug","buggy");
}
if (workInfo != null) {
Log.d("boss2", "pls2");
if (workInfo.getState().isFinished()) {
Log.d("boss3", "pls3");
Data data = workInfo.getOutputData();
String output = data.getString("Response");
Log.d("boss4", output);
if (output.equals(Status.CANCELLED + "")) {
response.setCancelled(true);
}
if (output.equals(Status.PAUSED + "")) {
response.setPaused(true);
}
if (output.equals("succ")) {
response.setSuccessful(true);
}
if (output.equals("abc")) {
Error error = new Error();
error.setConnectionError(true);
error.setConnectionException(new Exception());
response.setError(error);
}
if (output.equals("def")) {
Error error = new Error();
error.setServerError(true);
response.setError(error);
}
}
if (response.isSuccessful()) {
request.deliverSuccess();
} else if (response.isPaused()) {
request.deliverPauseEvent();
} else if (response.getError() != null) {
request.deliverError(response.getError());
} else if (!response.isCancelled()) {
request.deliverError(new Error());
}
}
}
});
}
public void finish(DownloadRequest request) {
currentRequestMap.remove(request.getDownloadId());
}
}
public MyWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
currentRequestMap=new ConcurrentHashMap<>();
mPrefs=PreferenceManager.getDefaultSharedPreferences(context);
}
#NonNull
#Override
public Result doWork() {
int a = getInputData().getInt("ID",2);
String statu = getInputData().getString("status");
Gson gson = new Gson();
String json = mPrefs.getString("SerializableObject", "");
if(json.equals("")){
Log.d("noii","nn");
}
request = gson.fromJson( json, DownloadRequest.class);
Log.d("zoiiii",currentRequestMap.get(a)+"")
if(request!=null){
Log.d("soii",request.getStatus()+"");
}
else{
Log.d("loii","toy");
}
Response response = new Response();
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
try {
Log.d("koko","gogo");
if(request.getOnProgressListener()==null){
Log.d("dope",request.getUrl()+"");
//progressHandler = new ProgressHandler(request.getOnProgressListener());
}
if (request.getOnProgressListener() != null) {
Log.d("toll","lol");
progressHandler = new ProgressHandler(request.getOnProgressListener());
}
Log.d("suppp","ppp");
tempPath = Utils.getTempPath(request.getDirPath(), request.getFileName());
File file = new File(tempPath);
DownloadModel model = getDownloadModelIfAlreadyPresentInDatabase();
Log.d("dupp","nupp");
if (model != null) {
Log.d("love","no");
if (file.exists()) {
request.setTotalBytes(model.getTotalBytes());
request.setDownloadedBytes(model.getDownloadedBytes());
} else {
removeNoMoreNeededModelFromDatabase();
request.setDownloadedBytes(0);
request.setTotalBytes(0);
model = null;
}
}
Log.d("ab","devel");
httpClient = ComponentHolder.getInstance().getHttpClient();
Log.d("ggs","iipu");
httpClient.connect(request);
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
httpClient = Utils.getRedirectedConnectionIfAny(httpClient, request);
responseCode = httpClient.getResponseCode();
eTag = httpClient.getResponseHeader(Constants.ETAG);
Log.d("sipi","kipi");
if (checkIfFreshStartRequiredAndStart(model)) {
model = null;
Log.d("lova","nova");
}
if (!isSuccessful()) {
Log.d("lvv","nppp");
Error error = new Error();
error.setServerError(true);
error.setServerErrorMessage(convertStreamToString(httpClient.getErrorStream()));
error.setHeaderFields(httpClient.getHeaderFields());
error.setResponseCode(responseCode);
response.setError(error);
Data output = new Data.Builder()
.putString("Response","abc")
.build();
return Result.failure(output);
}
setResumeSupportedOrNot();
Log.d("coder","npppp");
totalBytes = request.getTotalBytes();
if (!isResumeSupported) {
deleteTempFile();
}
if (totalBytes == 0) {
totalBytes = httpClient.getContentLength();
request.setTotalBytes(totalBytes);
}
if (isResumeSupported && model == null) {
createAndInsertNewModel();
}
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
Log.d("dodo","soso");
request.deliverStartEvent();
Log.d("coco","momo");
inputStream = httpClient.getInputStream();
byte[] buff = new byte[BUFFER_SIZE];
if (!file.exists()) {
if (file.getParentFile() != null && !file.getParentFile().exists()) {
if (file.getParentFile().mkdirs()) {
//noinspection ResultOfMethodCallIgnored
file.createNewFile();
}
} else {
//noinspection ResultOfMethodCallIgnored
file.createNewFile();
}
}
this.outputStream = FileDownloadRandomAccessFile.create(file);
if (isResumeSupported && request.getDownloadedBytes() != 0) {
outputStream.seek(request.getDownloadedBytes());
}
Log.d("miggy","siggy");
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
do {
Log.d("left","some");
final int byteCount = inputStream.read(buff, 0, BUFFER_SIZE);
if (byteCount == -1) {
break;
}
outputStream.write(buff, 0, byteCount);
request.setDownloadedBytes(request.getDownloadedBytes() + byteCount);
Log.d("now1","one1");
sendProgress();
Log.d("now2","one2");
syncIfRequired(outputStream);
Log.d("common","yessin");
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
sync(outputStream);
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
} while (true);
final String path = Utils.getPath(request.getDirPath(), request.getFileName());
Utils.renameFileName(tempPath, path);
response.setSuccessful(true);
Log.d("yup","dove");
if (isResumeSupported) {
removeNoMoreNeededModelFromDatabase();
}
} catch (IOException | IllegalAccessException e) {
if (!isResumeSupported) {
deleteTempFile();
}
Error error = new Error();
error.setConnectionError(true);
error.setConnectionException(e);
response.setError(error);
Data output = new Data.Builder()
.putString("Response","def")
.build();
return Result.failure(output);
} finally {
closeAllSafely(outputStream);
}
Log.d("final","done");
Data output = new Data.Builder()
.putString("Response","succ")
.build();
return Result.success(output);
}
private void deleteTempFile() {
File file = new File(tempPath);
if (file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
private boolean isSuccessful() {
return responseCode >= HttpURLConnection.HTTP_OK
&& responseCode < HttpURLConnection.HTTP_MULT_CHOICE;
}
private void setResumeSupportedOrNot() {
isResumeSupported = (responseCode == HttpURLConnection.HTTP_PARTIAL);
}
private boolean checkIfFreshStartRequiredAndStart(DownloadModel model) throws IOException,
IllegalAccessException {
if (responseCode == Constants.HTTP_RANGE_NOT_SATISFIABLE || isETagChanged(model)) {
if (model != null) {
removeNoMoreNeededModelFromDatabase();
}
deleteTempFile();
request.setDownloadedBytes(0);
request.setTotalBytes(0);
httpClient = ComponentHolder.getInstance().getHttpClient();
httpClient.connect(request);
httpClient = Utils.getRedirectedConnectionIfAny(httpClient, request);
responseCode = httpClient.getResponseCode();
return true;
}
return false;
}
private boolean isETagChanged(DownloadModel model) {
return !(eTag == null || model == null || model.getETag() == null)
&& !model.getETag().equals(eTag);
}
private DownloadModel getDownloadModelIfAlreadyPresentInDatabase() {
return ComponentHolder.getInstance().getDbHelper().find(request.getDownloadId());
}
private void createAndInsertNewModel() {
DownloadModel model = new DownloadModel();
model.setId(request.getDownloadId());
model.setUrl(request.getUrl());
model.setETag(eTag);
model.setDirPath(request.getDirPath());
model.setFileName(request.getFileName());
model.setDownloadedBytes(request.getDownloadedBytes());
model.setTotalBytes(totalBytes);
model.setLastModifiedAt(System.currentTimeMillis());
ComponentHolder.getInstance().getDbHelper().insert(model);
}
private void removeNoMoreNeededModelFromDatabase() {
ComponentHolder.getInstance().getDbHelper().remove(request.getDownloadId());
}
private void sendProgress() {
if (request.getStatus() != Status.CANCELLED) {
Log.d("ttyl","ggyl");
if (progressHandler != null) {
Log.d("mozz","illa");
progressHandler
.obtainMessage(Constants.UPDATE,
new Progress(request.getDownloadedBytes(),
totalBytes)).sendToTarget();
}
else{
Log.d("maybe","into");
}
}
}
private void syncIfRequired(FileDownloadOutputStream outputStream) {
final long currentBytes = request.getDownloadedBytes();
final long currentTime = System.currentTimeMillis();
final long bytesDelta = currentBytes - lastSyncBytes;
final long timeDelta = currentTime - lastSyncTime;
if (bytesDelta > MIN_BYTES_FOR_SYNC && timeDelta > TIME_GAP_FOR_SYNC) {
sync(outputStream);
lastSyncBytes = currentBytes;
lastSyncTime = currentTime;
}
}
private void sync(FileDownloadOutputStream outputStream) {
boolean success;
try {
outputStream.flushAndSync();
success = true;
} catch (IOException e) {
success = false;
e.printStackTrace();
}
if (success && isResumeSupported) {
ComponentHolder.getInstance().getDbHelper()
.updateProgress(request.getDownloadId(),
request.getDownloadedBytes(),
System.currentTimeMillis());
}
}
private void closeAllSafely(FileDownloadOutputStream outputStream) {
if (httpClient != null) {
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
if (outputStream != null) {
try {
sync(outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
if (outputStream != null)
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String convertStreamToString(InputStream stream) {
StringBuilder stringBuilder = new StringBuilder();
if (stream != null) {
String line;
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(stream));
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException ignored) {
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (NullPointerException | IOException ignored) {
}
}
}
return stringBuilder.toString();
}

Related

TCP socket in Android

My problem is I have implemented a TCP socket client in android which sends continuously "Hello" messages to the server to maintain a client-server connection and receives messages from the server.
In Android, I have initialized a boolean variable that is controlling the thread if my app is in the background I make the "AppConfig.finished" variable true inactivity on pause and on stop method to stop the socket thread and make it false when in on resume state.
But my app is consuming high CPU usage which is making my app slow, I have checked it in android's profiler. Please help me to optimize it.
The code is given below.
public class MyTcp extends Thread{
private BufferedInputStream inputStream;
private BufferedOutputStream outputStream;
private Socket MySock;
private static SocketStatus SS;
private int ConnectAttemptCount = 0;
private CheckConnectionStatus CheckStatus = null;
public boolean FirstAttempt = true;
public boolean Continue = true;
private boolean isDirectChecked = false;
String tempData = "";
private final ArrayBlockingQueue<String> Queue = new ArrayBlockingQueue<>(100);
public MyTcp(SocketStatus SS) {
MyTcp.SS = SS;
MyTcp.SS.isConnected = false;
setDaemon(true);
Thread t = new Thread(new DequeueMessageThread());
t.setName(SS.SocketName + " DequeqeMessageThread");
t.start();
setName(SS.SocketName);
}
public void Dispose() {
try {
Continue = false;
SS.isConnected = false;
if(inputStream != null) {
inputStream.close();
}
if(outputStream !=null) {
outputStream.close();
}
if(MySock != null) {
MySock.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void run() {
if(!Logs.isFinished) {
try {
while (Continue) {
if (SS.isConnected) {
String fromServer = ReceiveMsg();
if (fromServer.compareTo("") != 0) {
Queue.put(fromServer);
}
ConnectAttemptCount = 0;
} else {
if (ConnectAttemptCount < SS.ConnectAttempt) {
println("run>>" + "Connection Attempt" + ConnectAttemptCount);
ConnectAttemptCount++;
Connect();
} else {
println("run>>" + "Unable To Connect to server");
break;
}
}
}
} catch (Exception e) {
println("run Exception>>" + e);
}
}
}
public void Connect() {
if(!Logs.isFinished) {
try {
if (SS.isDoQueueEmptyOnConnect) {
Queue.clear();
tempData = "";
}
if (FirstAttempt) {
FirstAttempt = false;
} else {
Utilities.println("Trying to connect with " + SS.ServerIP + " on Port " + SS.Port);
_fireStatsEvent(Status.Reconnecting, "Trying to connect with " + SS.ServerIP);
Random generator = new Random();
long wait = (long) generator.nextInt(3000) + 500;
Thread.sleep(wait);
}
MySock = (Socket) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
// Start Secure Code
return (new Socket(SS.ServerIP, SS.Port));
// End Secure Code
} catch (Exception e) {
println("Connect Exception>>" + e.toString());
}
return null;
}
});
if (MySock != null) {
SS.isConnected = true;
SocketStatus.MySock = MySock;
inputStream = new BufferedInputStream(MySock.getInputStream());
outputStream = new BufferedOutputStream(MySock.getOutputStream());
Utilities.println("Connection established with " + SS.ServerIP + " on Port " + SS.Port);
if (SocketStatus.EnablePingPong) {
if (CheckStatus != null) {
CheckStatus.Dispose();
}
SS.LastMsgTime = new Date();
CheckStatus = new CheckConnectionStatus(SS, this);
CheckStatus.setName(SS.SocketName + "Connection Status Thread");
CheckStatus.start();
}
}
} catch (Exception e) {
println("Connect>>" + e);
}
int ConnectToIPCount = 0;
if (!SS.isConnected) {
while (!SS.isConnected && ConnectToIPCount < SS.ServerIPList.size()) {
final String IP_ = SS.ServerIPList.get(ConnectToIPCount).toString();
final int Port_ = SS.Port;
println("Connect>>" + "Trying to connect with " + IP_ + " on Port " + Port_);
ConnectToIPCount++;
try {
Thread.sleep(5000);
MySock = (Socket) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
// Start Secure Code
if (!isDirectChecked) {
isDirectChecked = true;
Socket tempSock = new Socket(Proxy.NO_PROXY);
tempSock.connect(new InetSocketAddress(IP_, Port_));
return tempSock;
} else {
return (new Socket(IP_, Port_));
}
// End Secure Code
} catch (Exception e) {
println("Connect Exception>>" + e.toString());
}
return null;
}
});
if (MySock != null) {
SocketStatus.MySock = MySock;
SS.isConnected = true;
inputStream = new BufferedInputStream(MySock.getInputStream());
outputStream = new BufferedOutputStream(MySock.getOutputStream());
Utilities.println("Connection established with " + IP_ + " on port " + Port_);
if (SocketStatus.EnablePingPong) {
if (CheckStatus != null) {
CheckStatus.Dispose();
}
SS.LastMsgTime = new Date();
CheckStatus = new CheckConnectionStatus(SS, this);
CheckStatus.setName(SS.SocketName + "Connection Status Thread");
CheckStatus.start();
}
}
} catch (UnknownHostException e) {
println("Connect UnknownHostException>>" + e.toString());
} catch (IOException e) {
println("Connect IOException>>" + e.toString());
} catch (Exception e) {
println("Connect Exception>>" + e.toString());
}
}
}
}
}
public void SendMsg(String sendMsg) {
if(!Logs.isFinished) {
try {
println("SendMsg>>" + sendMsg);
if (MySock != null && MySock.isConnected()) {
try {
byte[] b = null;
b = sendMsg.getBytes();
outputStream.write(b, 0, b.length);
outputStream.flush();
} catch (SocketException | SocketTimeoutException e) {
if (MySock != null) {
MySock.close();
}
SS.isConnected = false;
} catch (Exception e) {
println("SendMsg Exception>>" + e.toString());
}
}
} catch (Exception e) {
Log.d("TCP Client SendMsg >>", "Unable To Connect to server");
}
}
}
public String ReceiveMsg() {
String recvMsg = "";
if(!Logs.isFinished) {
try {
byte[] b = new byte[8092 * 6];
int recvsz = 0;
if (MySock != null && MySock.isConnected()) {
recvsz = inputStream.read(b, 0, b.length);
if (recvsz > 0) {
try {
byte[] b2 = new byte[recvsz];
System.arraycopy(b, 0, b2, 0, b2.length);
recvMsg = (new String(b2));
if (recvMsg.length() > 0) {
SS.LastMsgTime = new Date();
}
} catch (Exception e) {
println("ReceiveMsg Exception>>" + e.toString());
}
}
}
} catch (Exception e) {
if (SS.isConnected) {
Utilities.handleException(e);
}
SS.isConnected = false;
println("ReceiveMsg Exception>>>" + e.toString());
Log.d("RESPONSE FROM SERVER", "S: Received Message: '" + e.toString() + "'");
}
}
return recvMsg;
}
public void println(String msg) {
if (SS.Debug) {
String strDateFormat1 = "HH:mm:ss";
SimpleDateFormat sdf1 = new SimpleDateFormat(strDateFormat1);
Utilities.println(SS.SocketName + " (" + sdf1.format(new Date()) + ") " + msg);
}
}
private final List<MessageRecieveListner> _listeners = new ArrayList<>();
private final List<MessageRecieveListner> _listenersStrength = new ArrayList<>();
public synchronized void addListener(MessageRecieveListner l) {
_listeners.add(l);
_listenersStrength.add(l);
}
private synchronized void _fireMessageEvent(String msg) {
MessageRecieveEvent MsgEvent = new MessageRecieveEvent(this, msg);
for (MessageRecieveListner listener : _listeners) {
listener.MessageRecieved(MsgEvent);
}
}
public synchronized void _fireStatsEvent(Status status, String msg) {
MessageRecieveEvent MsgEvent = new MessageRecieveEvent(this, status, msg);
for (MessageRecieveListner listener : _listeners) {
listener.ConnectionStatus(MsgEvent);
}
}
private class DequeueMessageThread implements Runnable {
public DequeueMessageThread() {
}
#Override
public void run() {
if(!Logs.isFinished) {
while (Continue) {
if (!Queue.isEmpty()) {
try {
String data = Queue.take().trim();
if (SS.MessageParser.length() > 0) {
if (data.lastIndexOf(SS.MessageParser) == data.length() - 1) {
_fireMessageEvent(tempData + data);
tempData = "";
} else {
if (data.indexOf(SS.MessageParser) > 0) {
String particalCompleteData = tempData + data.substring(0, data.lastIndexOf(SS.MessageParser));
tempData = data.substring(data.lastIndexOf(SS.MessageParser) + 1);
_fireMessageEvent(particalCompleteData);
Utilities.println("incomplete data");
}
}
} else {
_fireMessageEvent(data);
}
} catch (Exception ex) {
ex.printStackTrace();
Continue = false;
}
}
}
}
}
}

How send a ByteBuffer through Socket?

I'm working in a remote ScreenRecord in real time based in this code.
With this code of reference i'm able to record screen of my smartphone with success and saving .mp4 file in some folder previous defined.
But to my project, i need that this content be sent to server (similar to Team View for android).
My last attempt to sent this content to server side was like this:
OutputStream os = clientSocket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream (os);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(encodedData);
oos.flush();
bos.flush();
os.flush();
Reference => this question
but comes a error of:
java.io.NotSerializableException
in this line > oos.writeObject(encodedData);
Then, i want know how solve it or some other way to make this task.
Here is complete code:
/////////////////////////////////////// CLIENTSOCKET ///////////////////////////////////////////
Socket clientSocket;
int SERVERPORT = 60;
String SERVER_IP = "192.168.15.6";
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
clientSocket = new Socket(serverAddr, SERVERPORT);
new Thread(new CommsThread()).start();
} catch (Exception e1) {
System.out.println(e1.toString());
}
}
}
class CommsThread implements Runnable {
#Override
public void run() {
try {
System.out.println("Waiting for server request");
while(clientSocket.isConnected()){
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())),true);
if (reader.ready()) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
if(line != null && !line.trim().isEmpty()) {
if(line.equalsIgnoreCase("screenrecord")){
System.out.println(out.toString());
mMediaProjectionManager = (MediaProjectionManager)getSystemService(android.content.Context.MEDIA_PROJECTION_SERVICE);
Intent permissionIntent = mMediaProjectionManager.createScreenCaptureIntent();
startActivityForResult(permissionIntent, REQUEST_CODE_CAPTURE_PERM);
out.flush();
}
if(line.equalsIgnoreCase("exit")) {
stopRecording();
break;
}
}
}
}
Thread.sleep(100);
}
System.out.println("Shutting down Socket!!");
clientSocket.close();
} catch (Exception e1) {
System.out.println(e1.toString());
}
}
}
////////////////////////////////////// MEDIAPROJECTION /////////////////////////////////////////
private static final int REQUEST_CODE_CAPTURE_PERM = 1234;
private static final String VIDEO_MIME_TYPE = "video/avc";
int VIDEO_WIDTH, VIDEO_HEIGHT;
private boolean mMuxerStarted = false;
private MediaProjectionManager mMediaProjectionManager;
private MediaProjection mMediaProjection;
private Surface mInputSurface;
private MediaMuxer mMuxer;
private MediaCodec mVideoEncoder;
private MediaCodec.BufferInfo mVideoBufferInfo;
private int mTrackIndex = -1;
private final Handler mDrainHandler = new Handler(Looper.getMainLooper());
private Runnable mDrainEncoderRunnable = new Runnable() {
#Override
public void run() {
drainEncoder();
}
};
public void stopRecording(){
releaseEncoders();
}
private void startRecording() {
DisplayManager dm = (DisplayManager)getSystemService(Context.DISPLAY_SERVICE);
Display defaultDisplay = dm.getDisplay(Display.DEFAULT_DISPLAY);
if (defaultDisplay == null) {
throw new RuntimeException("No display found.");
}
DisplayMetrics metrics = getResources().getDisplayMetrics();
int screenWidth = metrics.widthPixels;
int screenHeight = metrics.heightPixels;
int screenDensity = metrics.densityDpi;
VIDEO_WIDTH = screenWidth;
VIDEO_HEIGHT = screenHeight;
prepareVideoEncoder();
mMediaProjection.createVirtualDisplay("Recording Display", screenWidth, screenHeight, screenDensity, 0, mInputSurface, null, null);
drainEncoder();
}
private void prepareVideoEncoder() {
mVideoBufferInfo = new MediaCodec.BufferInfo();
MediaFormat format = MediaFormat.createVideoFormat(VIDEO_MIME_TYPE, VIDEO_WIDTH, VIDEO_HEIGHT);
int frameRate = 30;
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
format.setInteger(MediaFormat.KEY_BIT_RATE, 6000000);
format.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate);
format.setInteger(MediaFormat.KEY_CAPTURE_RATE, frameRate);
format.setInteger(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, 1000000 / frameRate);
format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
try {
mVideoEncoder = MediaCodec.createEncoderByType(VIDEO_MIME_TYPE);
mVideoEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mInputSurface = mVideoEncoder.createInputSurface();
mVideoEncoder.start();
} catch (IOException e) {
releaseEncoders();
}
}
private boolean drainEncoder() {
mDrainHandler.removeCallbacks(mDrainEncoderRunnable);
while (true) {
int bufferIndex = mVideoEncoder.dequeueOutputBuffer(mVideoBufferInfo, 0);
if (bufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
break;
} else if (bufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
} else if (bufferIndex < 0) {
} else {
ByteBuffer encodedData = mVideoEncoder.getOutputBuffer(bufferIndex);
if (encodedData == null) {
throw new RuntimeException("couldn't fetch buffer at index " + bufferIndex);
}
if ((mVideoBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
mVideoBufferInfo.size = 0;
}
if (mVideoBufferInfo.size != 0) {
encodedData.position(mVideoBufferInfo.offset);
encodedData.limit(mVideoBufferInfo.offset + mVideoBufferInfo.size);
try {
OutputStream os = clientSocket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream (os);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(encodedData);
oos.flush();
bos.flush();
os.flush();
} catch (IOException e) {
throw new RuntimeException("couldn't send data to server");
}
} else {
}
mVideoEncoder.releaseOutputBuffer(bufferIndex, false);
}
if ((mVideoBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
break;
}
}
mDrainHandler.postDelayed(mDrainEncoderRunnable, 10);
return false;
}
private void releaseEncoders() {
mDrainHandler.removeCallbacks(mDrainEncoderRunnable);
if (mMuxer != null) {
if (mMuxerStarted) {
mMuxer.stop();
}
mMuxer.release();
mMuxer = null;
mMuxerStarted = false;
}
if (mVideoEncoder != null) {
mVideoEncoder.stop();
mVideoEncoder.release();
mVideoEncoder = null;
}
if (mInputSurface != null) {
mInputSurface.release();
mInputSurface = null;
}
if (mMediaProjection != null) {
mMediaProjection.stop();
mMediaProjection = null;
}
mVideoBufferInfo = null;
mDrainEncoderRunnable = null;
mTrackIndex = -1;
}
////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (REQUEST_CODE_CAPTURE_PERM == requestCode) {
if (resultCode == RESULT_OK) {
mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, intent);
startRecording();
} else {
}
}
}

Copy files from internal storage to usb storage on Android 6

Until now I could programmatically copy files from the internal memory of the phone to an USB-OTG connected to it. I just had to give root permissions and edit platform.xml. But now my device (Samsung Galaxy S6 Edge +) has been updated to Android 6 and made my code stop working.
I'm getting this error everytime I try to copy files the way I did before:
Caused by java.lang.RuntimeException: java.io.FileNotFoundException: /mnt/media_rw/4265-1803/requiredfiles/Oculus/360Photos/Pisos/Chalet Anna/R0010008.JPG: open failed: EACCES (Permission denied)
String from = Environment.getExternalStorageDirectory() + File.separator + getString(R.string.FOLDER_SDCARD);
String to = Utils.getUsbPath() + File.separator + getString(R.string.FOLDER_USB);
FileManager fileManager = new FileManager(getActivity(), from, to, false);
fileManager.execute(true);
My getUsbPath function
public static String getUsbPath() {
String finalpath = null;
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
String[] patharray = new String[10];
int i = 0;
int available = 0;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
String mount = new String();
if (line.contains("secure"))
continue;
if (line.contains("asec"))
continue;
if (line.contains("fat")) {// TF card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
mount = mount.concat(columns[1] + "/requiredfiles");
patharray[i] = mount;
i++;
// check directory is exist or not
File dir = new File(mount);
if (dir.exists() && dir.isDirectory()) {
// do something here
available = 1;
finalpath = mount;
break;
} else {
}
}
}
}
if (available == 1) {
} else if (available == 0) {
finalpath = patharray[0];
}
} catch (Exception e) {
}
return finalpath;
}
My FileManager.class
public class FileManager extends AsyncTask<Boolean, Integer, Boolean> {
private Context context;
private String from;
private String to;
private ProgressDialog progressDialog;
private int filesCount=0;
private int filesTotal=0;
Boolean completed;
Boolean move;
MainActivity main;
public static final String TAG = "FileManager";
public FileManager(Context context, String from, String to, Boolean move) {
this.context = context;
this.from = from;
this.to = to;
this.move = move;
this.main = (MainActivity) context;
}
#Override
protected Boolean doInBackground(Boolean... params) {
File source = new File(from);
File target = new File(to);
try {
countFiles(source);
copyDirectory(source, target);
if (move) {
deleteFiles(source);
}
completed = true;
} catch (Exception error) {
Log.e(TAG, "doInBackground", error);
completed = false;
try {
throw error;
} catch (IOException e) {
e.printStackTrace();
}
throw new RuntimeException(error.toString());
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
if (move) {
progressDialog.setMessage(context.getString(R.string.moving_files));
} else {
progressDialog.setMessage(context.getString(R.string.copying_files));
}
progressDialog.setIndeterminate(true);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
progressDialog.dismiss();
if (completed) {
if (move) {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.move_completed), Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.copy_completed), Snackbar.LENGTH_LONG).show();
}
} else {
if (move) {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.move_failed), Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.copy_failed), Snackbar.LENGTH_LONG).show();
}
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setIndeterminate(false);
progressDialog.setMax(filesTotal);
progressDialog.setProgress(filesCount);
}
private void copyDirectory(File sourceLocation, File targetLocation) throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdirs();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
}
} else {
if (!targetLocation.exists()) {
filesCount++;
publishProgress();
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
scanFile(targetLocation.getCanonicalPath(), false);
}
}
}
private void countFiles(File file) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < file.listFiles().length; i++) {
countFiles(new File(file, children[i]));
}
} else {
filesTotal++;
}
}
public void deleteFiles(File folder) {
if (folder.isDirectory()) {
File[] list = folder.listFiles();
if (list != null) {
for (int i = 0; i < list.length; i++) {
File tmpF = list[i];
if (tmpF.isDirectory()) {
deleteFiles(tmpF);
}
tmpF.delete();
String path;
try {
path = tmpF.getCanonicalPath();
} catch (Exception error) {
Log.e(TAG, "", error);
path = tmpF.getAbsolutePath();
}
scanFile(path, true);
}
}
}
}
private void scanFile(String path, final boolean isDelete) {
try {
MediaScannerConnection.scanFile(context, new String[] { path },
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
if (isDelete) {
if (uri != null) {
context.getContentResolver().delete(uri,
null, null);
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
How can I solve it?

Not getting location from map

I am making location based reminder app...but when i click on specific location then marker add to this location but when i click on submit it not show the selected location..it is getting only my current longitude and latitude...here is my code....
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_to_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
this.mainClass = (MainClass) getApplication();
this.drawablered = getResources().getDrawable(R.mipmap.mainpin);
final Drawable buttonSelector = getResources().getDrawable(R.drawable.buttonselector);
this.buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
this.buttonShowSearch = (Button) findViewById(R.id.buttonShowSearch);
this.locationTextView = new AutoCompleteTextView(getApplicationContext());
this.buttonSearch = new Button(getApplicationContext());
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
height = displaymetrics.heightPixels;
this.width = displaymetrics.widthPixels;
density = displaymetrics.densityDpi;
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean available = false;
NetworkInfo netInfo = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
available = true;
}
if (!available) {
this.mainClass.setLongToast("Sorry, there is not network connection to display the map");
}
try {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasReadContactPermission = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
if (hasReadContactPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
124);
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (this.locationManager != null) {
this.currentLocation = this.locationManager.getLastKnownLocation("gps");
if (this.currentLocation != null) {
this.currentLatitude = Double.valueOf(this.currentLocation.getLatitude());
this.currentLongitude = Double.valueOf(this.currentLocation.getLongitude());
this.currentPoint = new LatLng((int) (this.currentLatitude.doubleValue() * 1000000.0d), (int) (this.currentLongitude.doubleValue() * 1000000.0d));
locationLat = this.currentLatitude.doubleValue();
locationLong = this.currentLongitude.doubleValue();
} else {
}
} else {
}
this.buttonShowSearch.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AddLocationActivity.this.linearLayout = (LinearLayout) AddLocationActivity.this.findViewById(R.id.layout_search);
AddLocationActivity.this.locationTextView.setHint("Location to search");
//AddLocationActivity.this.locationTextView.setTextColor(getColor(R.color.colorAccent));
AddLocationActivity.this.locationTextView.setWidth((AddLocationActivity.this.width / 4) * 3);
AddLocationActivity.this.locationTextView.setHeight(36);
AddLocationActivity.this.buttonSearch.setWidth(AddLocationActivity.this.width * 0);
AddLocationActivity.this.buttonSearch.setHeight(40);
AddLocationActivity.this.buttonSearch.setBackgroundDrawable(buttonSelector);
AddLocationActivity.this.buttonSearch.setText("Search");
AddLocationActivity.this.buttonSearch.setTextColor(-1);
AddLocationActivity.this.linearLayout.setOrientation(LinearLayout.VERTICAL);
AddLocationActivity.this.linearLayout.setVerticalGravity(16);
AddLocationActivity.this.linearLayout.addView(AddLocationActivity.this.locationTextView);
AddLocationActivity.this.linearLayout.addView(AddLocationActivity.this.buttonSearch);
AddLocationActivity.this.buttonShowSearch.setEnabled(false);
}
});
this.buttonSearch.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AddLocationActivity.this.location = AddLocationActivity.this.locationTextView.getText().toString();
AddLocationActivity.this.location.trim();
if (AddLocationActivity.this.location.compareTo("") != 0) {
AddLocationActivity.this.searchLocation();
AddLocationActivity.this.linearLayout.removeAllViews();
return;
}
AddLocationActivity.this.mainClass.setLongToast("Please enter a location");
}
});
this.buttonSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (AddLocationActivity.locationLat == 0.0d || AddLocationActivity.locationLong == 0.0d) {
AddLocationActivity.this.mainClass.setLongToast("Sorry, failed to submit");
return;
}
AddLocationActivity.this.mainClass.latitude = new StringBuilder(String.valueOf(AddLocationActivity.locationLat)).toString();
AddLocationActivity.this.mainClass.longitude = new StringBuilder(String.valueOf(AddLocationActivity.locationLong)).toString();
AddLocationActivity.this.mainClass.locationName = AddLocationActivity.locationName;
AddLocationActivity.this.finish();
}
});
}
protected void onResume() {
super.onResume();
this.mainClass.favListFlag = false;
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_home_screen, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
return this.mainClass.menuItemClick(item, getBaseContext());
}
protected boolean isRouteDisplayed() {
return false;
}
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
private void searchLocation() {
final Handler Modelhandler = new Handler() {
public void handleMessage(Message msg) {
AddLocationActivity.this.buttonShowSearch.setEnabled(true);
if (msg.obj == "1") {
AddLocationActivity.this.locationTextView.setText("");
AddLocationActivity.this.mainClass.setLongToast("Sorry, this location could not be marked, please mark the point manually");
} else if (msg.obj == "2") {
AddLocationActivity.this.addMarker(AddLocationActivity.this.point, AddLocationActivity.locationName);
}
}
};
new Thread() {
public void run() {
StringBuilder stringBuilder;
Message msg = new Message();
try {
((InputMethodManager) AddLocationActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(AddLocationActivity.this.getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
}
String str = "";
for (int i = 0; i < AddLocationActivity.this.location.length(); i++) {
if (AddLocationActivity.this.location.substring(i, i + 1).equalsIgnoreCase(" ")) {
str = new StringBuilder(String.valueOf(str)).append("+").toString();
} else {
str = new StringBuilder(String.valueOf(str)).append(AddLocationActivity.this.location.substring(i, i + 1)).toString();
}
}
if (str.compareTo("") != 0) {
AddLocationActivity.this.location = str;
}
URL url;
HttpURLConnection connection = null;
String responseStr = "";
try {
url = new URL("http://maps.google.com/maps/api/geocode/json?address=" + AddLocationActivity.this.location + "ka&sensor=false");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(false);
DataOutputStream wr = new
DataOutputStream(connection.getOutputStream());
wr.flush();
wr.close();
// Get Response
int status = connection.getResponseCode();
BufferedInputStream in;
if (status >= 400) {
in = new BufferedInputStream(connection.getErrorStream());
} else {
in = new BufferedInputStream(connection.getInputStream());
}
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
responseStr = response.toString();
Log.d("Server response", responseStr);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(responseStr);
} catch (JSONException e4) {
e4.printStackTrace();
}
Double d = new Double(0.0d);
d = new Double(0.0d);
Double lon1 = 0.0, lat1 = 0.0;
try {
lon1 = Double.valueOf(((JSONArray) jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
lat1 = Double.valueOf(((JSONArray) jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
} catch (JSONException e42) {
e42.printStackTrace();
}
if (lon1.doubleValue() == 0.0d && lat1.doubleValue() == 0.0d) {
msg.obj = "1";
} else {
AddLocationActivity.this.point = new LatLng((int) (lat1.doubleValue() * 1000000.0d), (int) (lon1.doubleValue() * 1000000.0d));
Geocoder geocoder = new Geocoder(AddLocationActivity.this.getApplicationContext(), Locale.getDefault());
try {
StringBuilder _homeAddress = new StringBuilder();
try {
List<Address> addresses = geocoder.getFromLocation(lat1.doubleValue(), lon1.doubleValue(), 1);
for (int index = 0; index < addresses.size(); index++) {
Address address = (Address) addresses.get(index);
AddLocationActivity.locationLat = lat1.doubleValue();
AddLocationActivity.locationLong = lon1.doubleValue();
if (address.getLocality() == null) {
AddLocationActivity.locationName = address.getAddressLine(0);
} else {
AddLocationActivity.locationName = address.getAddressLine(0) + ", " + address.getLocality();
}
}
stringBuilder = _homeAddress;
} catch (Exception e5) {
stringBuilder = _homeAddress;
}
} catch (Exception e6) {
}
msg.obj = "2";
}
Modelhandler.sendMessage(msg);
}
}.start();
}
private void addMarker(LatLng point, String locationName) {
if (mMap != null) {
mMap.clear();
mMap.moveCamera(CameraUpdateFactory.newLatLng(point));
this.itemizedoverlay = new MapItemizedOverlay(this.drawablered, getApplicationContext());
this.itemizedoverlay.addOverlay(this.overlayitem);
this.mapOverlays.add(this.itemizedoverlay);
this.mv.invalidate();
if (!locationName.equals("")) {
View map_popup = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.map_popup, null);
((TextView) map_popup.findViewById(R.id.textViewLocName)).setText(locationName);
this.mainClass.toast = new Toast(getApplicationContext());
this.mainClass.toast.setDuration(Toast.LENGTH_LONG);
this.mainClass.toast.setGravity(48, 0, ((height / 2) - (height / 10)) - 60);
this.mainClass.toast.setView(map_popup);
this.mainClass.toast.show();
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//this.mMap = googleMap;
LatLng sydney = new LatLng(-34.0d, 151.0d);
this.mMap.addMarker(new MarkerOptions().position(sydney).title("Sydney"));
this.mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 10.0f));
this.mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng latLng) {
AddLocationActivity.this.mMap.clear();
AddLocationActivity.locationLat = latLng.latitude;
AddLocationActivity.locationLong = latLng.longitude;
AddLocationActivity.this.mMap.addMarker(new MarkerOptions().position(new LatLng(AddLocationActivity.locationLat, AddLocationActivity.locationLong)).title(BuildConfig.FLAVOR + AddLocationActivity.locationLat + "\n" + AddLocationActivity.locationLong));
AddLocationActivity.this.mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(AddLocationActivity.locationLat, AddLocationActivity.locationLong), 10.9f));
}
});
}
}

onPostExecute is only sometimes called in AsyncTask

My AsyncTask is executed in my MainActivity, but it doesn't call onPostExecute. The method doInBackground is finished until the return statement (checked with System.out)!
The Call:
#Override
protected void onStart() {
super.onStart();
if (playIntent == null) {
playIntent = new Intent(this, MusicService.class);
if (CheckPermissions()) {
Prepare();
}
}
}
private void Prepare() {
MusicStore musicStore = new MusicStore(getApplicationContext());
sSongs = musicStore.getSongs();
StoreParcel storeParcel = new StoreParcel(StoreParcel.StoreAction.READ_PLAYLISTS, this);
musicStore.execute(storeParcel);
if (sSongs.length < 1) {
fabPlayPause.hide();
snbInformation = Snackbar.make(recyclerView, getString(R.string.snb_Information) + "Music.", Snackbar.LENGTH_INDEFINITE);
snbInformation.show();
}
else {
fabPlayPause.show();
}
bindService(playIntent, musicServiceConn, BIND_AUTO_CREATE);
startService(playIntent);
}
The AsyncTask:
public class MusicStore extends AsyncTask<StoreParcel, Void, StoreParcel> {
private Context mContext;
public MusicStore(Context context) {
mContext = context;
}
//region AsyncTask
#Override
protected StoreParcel doInBackground(StoreParcel... params) {
StoreParcel parcel = params[0];
StoreParcel storeParcel = new StoreParcel(parcel.getAction(), parcel.getPlaylistInterface());
switch (parcel.getAction()) {
case WRITE_PLAYLISTS:
WritePlaylists(parcel.getPlaylists());
break;
case READ_PLAYLISTS:
storeParcel.setPlaylists(ReadPlaylists());
break;
}
return storeParcel;
}
#Override
protected void onPostExecute(StoreParcel storeParcel) {
if (storeParcel.getAction() == StoreParcel.StoreAction.READ_PLAYLISTS) {
storeParcel.getPlaylistInterface().SyncPlaylists(storeParcel.getPlaylists());
}
super.onPostExecute(storeParcel);
}
//region Methods
private void WritePlaylists(Playlist[] playlists) {
File dir = new File(mContext.getFilesDir() + Preferences.dirPlaylists);
if (!dir.exists()) {
dir.mkdirs();
}
for (File f : dir.listFiles()) {
f.delete();
}
if (playlists == null) return;
String sFilename;
File file;
for (int i = 0; i < playlists.length; i++) {
sFilename = playlists[i].getName();
try {
file = new File(dir, sFilename + ".json");
file.createNewFile();
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
Gson gson = new GsonBuilder().create();
gson.toJson(playlists[i], writer);
writer.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
private Playlist[] ReadPlaylists() {
Playlist[] playlists;
File dir = new File(mContext.getFilesDir() + Preferences.dirPlaylists);
File[] files = dir.listFiles();
if (files == null) return null;
playlists = new Playlist[files.length];
Reader reader = null;
try {
for (int i = 0; i < files.length; i++) {
reader = new InputStreamReader(new FileInputStream(files[i]));
Gson gson = new GsonBuilder().create();
playlists[i] = gson.fromJson(reader, Playlist.class);
}
if (reader != null) reader.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return playlists;
}
//endregion
//endregion
}
The StoreParcel is a class created by me! It only countains an Interface, and an Enum-Value!
I think you should run the task in onResume so you are the ui exists. You can do UI stuff in onStart and onPostExecute has to run on UI thread.
#Override
protected void onStart() {
super.onStart();
if (playIntent == null) {
playIntent = new Intent(this, MusicService.class);
}
}
#Override
protected void onStart() {
super.onStart();
if (CheckPermissions()) {
Prepare();
}
}

Categories

Resources