I have implemented autoUpdate functionality which downloads the new app if update available and removes the old app and installs a new app. but After target SDK 24 or updating Phone os above API Level 2 this functionality not working Whenever I install it shows package parsing error. because of an old app is already there and we are trying to install a new app.
public class UpdateActivity extends AppCompatActivity implements
AppConstants {
public static final String TAG = UpdateActivity.class.getSimpleName();
private String appName = "demo.apk";
private int UNINSTALL_REQUEST_CODE = 1;
private final Handler mHideHandler = new Handler();
private View mContentView;
private BiColoredProgress numberProgressBar;
private Runnable backgroundRunnable;
private Runnable finishRunnable;
private Handler handler;
private static final int INSTALL = 1;
private static final int DOWNLOAD = 0;
private static int flag = 0;
private String updateUrl = "";
private class BackgroundDownloadRunnable implements Runnable {
BackgroundDownloadRunnable() {
}
public void run() {
DownloadFileFromURL d = new DownloadFileFromURL();
d.execute();
return;
}
}
private class FinishDownloadRunnable implements Runnable {
FinishDownloadRunnable() {
}
public void run() {
uninstallApp();
}
}
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
flag = getIntent().getIntExtra("flag", 0);
updateUrl = getIntent().getStringExtra("updateUrl");
StrictMode.setThreadPolicy(new
StrictMode.ThreadPolicy.Builder().permitAll().build());
handler = new Handler();
mContentView = findViewById(R.id.fullscreen_content);
mHideHandler.post(mHidePart2Runnable);
finishRunnable = new BackgroundDownloadRunnable();
backgroundRunnable = new FinishDownloadRunnable();
numberProgressBar = findViewById(R.id.numberbar8);
try {
if (flag == DOWNLOAD) {
DownloadFileFromURL d = new DownloadFileFromURL();
d.execute();
flag = 1;
} else if (flag == INSTALL) {
installApp();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class DownloadFileFromURL extends AsyncTask<String, Integer,
String> {
DownloadFileFromURL() {
}
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... f_url) {
try {
HttpURLConnection c = (HttpURLConnection) new
URL(updateUrl).openConnection();
c.setRequestMethod("POST");
c.setDoOutput(false);
c.connect();
int lengthOfFile = c.getContentLength();
File file = new
File(Environment.getExternalStorageDirectory().getPath() + "/Download/");
file.mkdirs();
File outputFile = new File(file, appName);
if (outputFile.exists()) {
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] data = new
byte[AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT];
long total1 = 0;
while (true) {
int count = is.read(data);
if (count == -1) {
break;
}
total1 += (long) count;
Integer[] strArr = new Integer[1];
strArr[0] = DOWNLOAD_COUNT + ((int) ((100 * total1) /
((long) lengthOfFile)));
publishProgress(strArr);
fos.write(data, 0, count);
}
fos.close();
is.close();
installApp();
new Thread(backgroundRunnable, "VersionChecker").start();
//uninstallApp();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
try {
if (progress[0] > 0 && progress[0] <= 20) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#d63232"));
}
if (progress[0] > 20 && progress[0] <= 40) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#F1E84B"));
}
if (progress[0] > 40 && progress[0] <= 60) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#2CACE3"));
}
if (progress[0] > 60 && progress[0] <= 80) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#4CBB17"));
}
if (progress[0] > 80 && progress[0] <= 100) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#39FF14"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onPostExecute(String file_url) {
numberProgressBar.setVisibility(View.GONE);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == this.UNINSTALL_REQUEST_CODE && resultCode != -1) {
if (resultCode == 0) {
super.onBackPressed();
startActivity(intent);
} else if (resultCode == 1) {
super.onBackPressed();
}
}
}
private void uninstallApp() {
Intent intentDEl = new Intent("android.intent.action.DELETE");
intentDEl.setData(Uri.parse("package:com.demo"));
startActivityForResult(intentDEl, UNINSTALL_REQUEST_CODE);
}
private void installApp() {
File apkFile = new
File(Environment.getExternalStorageDirectory().getPath() + "/Download/",
appName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkFile),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
Related
I want to show Toast (or progress bar) when clicking on the button "btnSearchImg". If before upload image, button clicked say "first pick image from gallary" and if after upload image clicked say "waiting". the toast before uploading image work fine but after uploading didn't work fine! my entire Activity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_by_image);
Toasty.Config.getInstance().setTextSize(15).apply();
mSharedPreferences = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
mEditor.putString(PREF_SKIP,null);
if(mSharedPreferences.contains(PREF_SKIP)){
Log.i("payment", "true");
} else {
try {
}catch (Exception e){
Toast.makeText(getApplicationContext(), "ERORR", Toast.LENGTH_LONG).show();
}
}
context = getApplicationContext();
pbImgRetrvialProccess = (ProgressBar)findViewById(R.id.pbImgRetrvialProccess);
tvPermissionLoadImg = (TextView)findViewById(R.id.tvPermissionLoadImg);
tvPermissionLoadImg.setTypeface(Base.getIranSansFont());
TextView tvSearchImageToolBarText = (TextView) findViewById(R.id.tvSearchImageToolBarText);
tvSearchImageToolBarText.setTypeface(Base.getIranSansFont());
ivGalleryImgLoad = (ImageView) findViewById(R.id.ivGalleryImgLoad);
btnSearchImgLoad = (Button) findViewById(R.id.btnSearchImgLoad);
btnSearchImg = (Button) findViewById(R.id.btnSearchImg);
btnSearchImgLoad.setOnClickListener(this);
btnSearchImg.setOnClickListener(this);
}
public StringBuilder uniformQuantization( File filePath ){...}
private StringBuilder chHistogram( Mat newImage ){...}
private void CopyAssets(String filename){...}
private void copyFile(InputStream in, OutputStream out) throws IOException {...}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearchImgLoad:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_IMAGE);}
OpenGallery();
break;
case R.id.btnSearchImg:
Toasty.success(getBaseContext(), "Waiting...", Toast.LENGTH_LONG).show();
FindSimilarRequestedImage();
break;
}
}
private void OpenGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
private void FindSimilarRequestedImage() {
if (ivGalleryImgLoad.getDrawable() != null) {
File loadedImageFilePath = new File(getRealPathFromURI(selectedImageUri));
queryFeatureX = uniformQuantization(loadedImageFilePath);
dateiLesenStringBuilder();
} else {
Toasty.error(getBaseContext(), "first pick image from gallary", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE && data != null) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_IMAGE);
} else {
selectedImageUri = data.getData();
ivGalleryImgLoad.setImageURI(selectedImageUri);
tvPermissionLoadImg.setVisibility(View.INVISIBLE);
}
}
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private void dateiLesenStringBuilder() {
FEATURE_PATH = context.getCacheDir().getPath() + "/" + FEATURE_NAME;
try {
FileOutputStream out = new FileOutputStream(FEATURE_PATH);
InputStream in = context.getAssets().open("coins/"+FEATURE_NAME);
byte[] buffer = new byte[1024];
int ch;
while ((ch = in.read(buffer)) > 0){
out.write(buffer, 0, ch);
}
out.flush();
out.close();
in.close();
}catch (Exception e){
System.out.println(e);
}
final File featureList = new File(FEATURE_PATH);
Runnable runner = new Runnable() {
BufferedReader in = null;
#Override
public void run() {
try {
String sCurrentLine;
int lines = 0;
BufferedReader newbw = new BufferedReader(new FileReader(featureList.getAbsolutePath()));
while (newbw.readLine() != null)
lines++;
in = new BufferedReader(new FileReader(featureList.getAbsolutePath()));
ArrayList<Double> nDistVal = new ArrayList<Double>();
ArrayList<String> nImagePath = new ArrayList<String>();
int count = 0;
while ((sCurrentLine = in.readLine()) != null) {
String[] featX = sCurrentLine.split(";")[1].split(" ");
nImagePath.add(sCurrentLine.split(";")[0]);
nDistVal.add(Distance.distL2(featX, queryFeatureX.toString().split(" ")));
count++;
}
ArrayList<Double> nstore = new ArrayList<Double>(nDistVal); // may need to be new ArrayList(nfit)
double maxDistVal = Collections.max(nDistVal);
Collections.sort(nDistVal);
sortedNImagePath = new ArrayList<String>();
for (int n = 0; n < nDistVal.size(); n++) {
int index = nstore.indexOf(nDistVal.get(n));
sortedNImagePath.add(nImagePath.get(index));
sortedNImageDistanceValues.add(String.valueOf(nDistVal.get(n) / maxDistVal));
String filePath = sortedNImagePath.get(0);
String minDistanceImg = sortedNImageDistanceValues.get(n);
FileNameFromPath = filePath.substring(filePath.lastIndexOf("/") + 1);
System.out.println("Distance values -> " + FileNameFromPath.toString());
System.out.println("Distance values -> " + minDistanceImg.toString());
}
} catch (Exception ex) {
String x = ex.getMessage();
System.out.println("ERORR" + x);
}
if (in != null) try {
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
Intent imgSearchedCoinNameIntent = new Intent(SearchByImageActivity.this, ImageSearchedCoinActivity.class);
imgSearchedCoinNameIntent.putExtra("imgSearchedCoinName", FileNameFromPath);
startActivity(imgSearchedCoinNameIntent);
}
}
};
Thread t = new Thread(runner, "Code Executer");
t.start();
}
}
If I put the "Waiting..." Toast after the FindSimilarRequestedImage() the toast will show up, but I need the toast show immediately after clicking on the btnSearchImg.
NOTE: Also in the dateiLesenStringBuilder() I removed the thread t that this part of code runs in normal flow and serial, but nothing changes!
Instead of toast use logcat to see if they run sequentially or not, maybe toast takes time to run
I solved this problem by putting the part of code in delay like below:
private void FindSimilarRequestedImage() {
if (ivGalleryImgLoad.getDrawable() != null) {
pbImgRetrvialProccess.setVisibility(View.VISIBLE);
Toasty.success(getBaseContext(), "Waiting ...", Toast.LENGTH_LONG).show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
File loadedImageFilePath = new File(getRealPathFromURI(selectedImageUri));
queryFeatureX = uniformQuantization(loadedImageFilePath);
dateiLesenStringBuilder();
}
}, 5000);
} else {
Toasty.error(getBaseContext(), "first pick image from gallary", Toast.LENGTH_LONG).show();
}
}
Now before destroying activity throw functions, I first show the toast, then run other functions!
to be able using a remote service through localhost IP (to hide real address from users in other intents) I am using this service to port-forwarding :
public class PortForward extends Service implements Runnable {
private static final String TAG = "Port Forward";
private int localPort;
private int remotePort;
private String remoteHost;
private boolean running = false;
private int lastUp = -1;
private int lastDown = -1;
private int bUp = 0;
private int bDown = 0;
LocalBroadcastManager bm;
private Thread t;
ServerSocketChannel serverSocketChannel = null;
public Handler sendBroadcastHandler = new Handler() {
public void handleMessage(Message msg) {
Intent i = new Intent().setAction(MainActivity.USAGE_UPDATE);
i.putExtra("bUp", bUp);
i.putExtra("bDown", bDown);
bm.sendBroadcast(i);
}
};
public Handler sendDeathHandler = new Handler() {
public void handleMessage(Message msg) {
Bundle b = msg.getData();
String causeOfDeath = b.getString("causeOfDeath", "unknown");
Notification note = new Notification.Builder(PortForward.this)
.setContentTitle("TCP forwarding thread dead")
.setContentText("Cause of death: " + causeOfDeath)
.setSmallIcon(R.drawable.ic_launcher).build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.notify(1338, note);
}
};
private void updateCounts() {
updateCounts(false);
}
private void updateCounts(boolean force) {
if (!force && (bUp - lastUp < 10000 && bDown - lastDown < 10000)) {
return;
}
lastUp = bUp;
lastDown = bDown;
Message msg = sendBroadcastHandler.obtainMessage();
sendBroadcastHandler.sendMessage(msg);
}
#Override
public void onDestroy() {
Log.d(TAG, "Service onDestroy");
if (t != null) {
t.interrupt();
try {
t.join();
} catch (InterruptedException e) {
Log.d(TAG, "couldn't join forwarder-thread");
System.exit(1);
}
}
Log.d(TAG, "Killed it");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Service onStart");
if (running){
updateCounts(true);
return START_REDELIVER_INTENT;
}
running = true;
bm = LocalBroadcastManager.getInstance(this);
localPort = intent.getIntExtra("localPort", -1);
remotePort = intent.getIntExtra("remotePort", -1);
remoteHost = intent.getStringExtra("remoteHost");
t = new Thread(this);
t.start();
Log.d(TAG, "launching a thread");
Notification note = new Notification.Builder(this)
.setContentTitle("Forwarding TCP Port")
.setContentText(String.format(
"localhost:%s -> %s:%s", localPort, remoteHost, remotePort))
.setSmallIcon(R.drawable.ic_launcher)
.build();
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
note.contentIntent = pi;
note.flags |= Notification.FLAG_NO_CLEAR;
startForeground(1337, note);
Log.d(TAG, "doing startForeground");
updateCounts(true);
return START_REDELIVER_INTENT;
}
private void reportException(Exception e){
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
Message msg = sendDeathHandler.obtainMessage();
Bundle b = msg.getData();
b.putString("causeOfDeath", sw.toString());
sendDeathHandler.sendMessage(msg);
}
private void finish(Selector s){
try {
serverSocketChannel.close();
} catch (IOException e){ }
Set<SelectionKey> selectedKeys = s.keys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
closeConnectionForKey(keyIterator.next());
}
}
private void closeChannel(SocketChannel c){
if (c != null){
try {
if (c != null){
c.close();
}
} catch (IOException e){ }
}
}
private void closeConnectionForKey(SelectionKey key){
PFGroup g = null;
try {
g = (PFGroup)key.attachment();
} catch (Exception e){
return;
}
if (g == null) {return;}
closeChannel(g.iChannel);
closeChannel(g.oChannel);
}
#Override
public void run() {
String causeOfDeath = null;
System.out.println("Server online");
Selector selector = null;
try {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(localPort));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
reportException(e);
return;
}
System.out.println("Server socket bound.");
while (true) {
System.out.println("Waiting for conn");
updateCounts();
int readyChannels = 0;
try {
readyChannels = selector.select();
} catch (IOException e) {
reportException(e);
continue;
}
if (Thread.currentThread().isInterrupted()) {
finish(selector);
return;
}
if (readyChannels == 0) {
continue;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
//System.out.println("Ready on " + readyChannels);
SelectionKey key = keyIterator.next();
keyIterator.remove();
if (!key.isValid()) {
continue;
} else if (key.isAcceptable()) {
System.out.println("Acceptable!");
PFGroup g = new PFGroup();
// 512KB buffers
g.iBuffer = ByteBuffer.allocate(512000);
g.oBuffer = ByteBuffer.allocate(512000);
boolean iConnected = false;
try {
g.iChannel = serverSocketChannel.accept();
iConnected = g.iChannel.finishConnect();
if (iConnected){
g.sidesOn++;
}
g.iChannel.configureBlocking(false);
g.iKey = g.iChannel.register(selector, 0, g);
g.oChannel = SocketChannel.open();
g.oChannel.configureBlocking(false);
g.oChannel.connect(new InetSocketAddress(remoteHost, remotePort));
g.oKey =g.oChannel.register(selector, SelectionKey.OP_CONNECT, g);
} catch (IOException e) {
continue;
}
} else if (key.isConnectable()) {
System.out.println("connectable!");
try {
SocketChannel c = (SocketChannel) key.channel();
PFGroup g = (PFGroup)key.attachment();
if (!c.finishConnect()) {
System.out.println("couldn't finish conencting");
continue;
}
g.sidesOn++;
System.out.println("Initilized the bidirectional forward");
key.interestOps(SelectionKey.OP_READ);
g.iKey = g.iChannel.register(selector, SelectionKey.OP_READ, g);
} catch (IOException e) {
continue;
}
} else if (key.isReadable()) {
try {
ByteBuffer b = null;
SocketChannel from = null;
SocketChannel to = null;
PFGroup g = (PFGroup)key.attachment();
String label = null;
if (key.channel() == g.iChannel){
from = g.iChannel;
to = g.oChannel;
b = g.iBuffer;
label = "incoming";
} else if (key.channel() == g.oChannel){
from = g.oChannel;
to = g.iChannel;
b = g.oBuffer;
label = "outgoing";
}
int i = from.read(b);
b.flip();
while (b.hasRemaining()) {
int bytes = to.write(b);
if(label.equals("incoming")){
bUp += bytes;
} else {
bDown += bytes;
}
}
b.clear();
if (i == -1) {
key.cancel();
g.sidesOn--;
if (g.sidesOn == 0){
System.out.println("Done, closing keys");
closeConnectionForKey(key);
}
}
} catch (IOException e){
Log.d(TAG, "closing connection for key.");
closeConnectionForKey(key);
}
}
}
}
}
public class PFGroup {
public ByteBuffer iBuffer;
public ByteBuffer oBuffer;
public SocketChannel iChannel;
public SocketChannel oChannel;
public int sidesOn = 0;
SelectionKey iKey;
SelectionKey oKey;
}
}
and in my main activity i used it like this:
Intent i=new Intent(this, PortForward.class)
.putExtra("localPort", 1195)
.putExtra("remotePort", port)
.putExtra("remoteHost", address);
startService(i);
but it does not work. when app is in background i can not use address:port through 127.0.0.1:1195 .
and also no related log appeasers in logcat.
There is a memory leak reported by LeakCanary in my Android App. I have Googled and studied for days and cannot find any solution. The leaked object is an instance of Activity called "MakeFire". It seems to be related to android.view.WindowManagerGlobal. Can anyone point out how the leak happened, and how to fix it?
Here is the LeakCanary ScreenCap
Here is the source code of the MakeFire Activity
public class MakeFire extends SharedMethod implements StatusBarFragment.OnFragmentInteractionListener,
DayTimeFragment.OnFragmentInteractionListener, BackButtonFragment.OnFragmentInteractionListener {
private Button firePlough;
private Button bowDrill;
private TextView makeFireWithBowDrillTime;
private TextView requirementTextview;
private Button performButton;
private String selectedButton;
private boolean firePloughOn;
private boolean bowDrillOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_fire);
firePlough = (Button) findViewById(R.id.firePlough);
bowDrill = (Button) findViewById(R.id.bowDrill);
makeFireWithBowDrillTime = (TextView) findViewById(R.id.makeFireWithBowDrillTime);
requirementTextview = (TextView) findViewById(R.id.requirementTextview);
performButton = (Button) findViewById(R.id.performButton);
}
#Override
public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MyApplication.getRefWatcher(this);
refWatcher.watch(this);
}
#Override
public void onBackPressed() {
Bundle extra = new Bundle();
extra.putString("classToGoBack", getClass().getName());
Intent intent = new Intent(this, InGameMenu.class);
intent.putExtras(extra);
startActivity(intent);
}
#Override
public void onResume() {
super.onResume();
GameData.useImmersiveModeSticky(this);
}
#Override
public void onStop() {
super.onStop();
try {
//save on the latest save file
FileOutputStream latestSavedGame = openFileOutput("latestSavedGame", Context.MODE_PRIVATE);
ObjectOutputStream latestGameData = new ObjectOutputStream(latestSavedGame);
latestGameData.writeObject(GameData.GDI);
latestSavedGame.close();
} catch (Exception e) {
//TODO - delete it before uploading the app
GameData.GDI.showPlainMsg("sharedMethodProblem!", this);
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
e.printStackTrace(pw);
GameData.GDI.showPlainMsg(sw.getBuffer().toString(), this);
}
boolean savedGameIsFine;
try {
FileInputStream latestSavedGame = openFileInput("latestSavedGame");
ObjectInputStream latestGameData = new ObjectInputStream(latestSavedGame);
savedGameIsFine = (latestGameData.readObject() != null);
latestSavedGame.close();
} catch (Exception e) {
savedGameIsFine = false;
}
if (savedGameIsFine) {
try {
//save on the latest save file
FileOutputStream latestSavedGame = openFileOutput("latestSavedGameBackup", Context.MODE_PRIVATE);
ObjectOutputStream latestGameData = new ObjectOutputStream(latestSavedGame);
latestGameData.writeObject(GameData.GDI);
latestSavedGame.close();
} catch (Exception e) {
}
} else {
}
}
#Override
protected void onStart() {
super.onStart();
updateAllViews();
requirementTextview.setVisibility(View.INVISIBLE);
performButton.setVisibility(View.INVISIBLE);
}
//method for updating all amendable views in the page
private void updateAllViews() {
//visibility of fire plough button
if (GameData.GDI.anyThisInventoryAvailable(GameData.FIRE_PLOUGH) &&
GameData.GDI.anyThisInventoryAvailable(GameData.TINDER) &&
(!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock)
) {
firePlough.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_fireplow_3_f,0,0);
firePlough.setTextColor(ContextCompat.getColor(this, R.color.buttonOnColour));
firePloughOn = true;
}
else {
firePlough.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_fireplow_3_f_o,0,0);
firePlough.setTextColor(ContextCompat.getColor(this, R.color.buttonOffColour));
firePloughOn = false;
}
//visibility of bow drill button
if (GameData.GDI.bowDrillUnlocked) {
bowDrill.setVisibility(View.VISIBLE);
makeFireWithBowDrillTime.setVisibility(View.VISIBLE);
if (GameData.GDI.anyThisInventoryAvailable(GameData.BOW_DRILL) &&
GameData.GDI.anyThisInventoryAvailable(GameData.TINDER) &&
(!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock)
) {
bowDrill.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_bow_drill_3_f,0,0);
bowDrill.setTextColor(ContextCompat.getColor(this, R.color.buttonOnColour));
bowDrillOn = true;
}
else {
bowDrill.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_bow_drill_3_f_o,0,0);
bowDrill.setTextColor(ContextCompat.getColor(this, R.color.buttonOffColour));
bowDrillOn = false;
}
}
updateStatusBarFragment();
updateDayTimeFragment();
}
public void makeFireWithFirePlough(View view) {
if (firePloughOn) {
performButton.setVisibility(View.VISIBLE);
}
else {
performButton.setVisibility(View.INVISIBLE);
}
requirementTextview.setVisibility(View.VISIBLE);
requirementTextview.setText(R.string.makeFireWithFirePloughRqm);
selectedButton = "fire plough";
}
public void makeFireWithBowDrill(View view) {
if (bowDrillOn) {
performButton.setVisibility(View.VISIBLE);
}
else {
performButton.setVisibility(View.INVISIBLE);
}
requirementTextview.setVisibility(View.VISIBLE);
requirementTextview.setText(R.string.makeFireWithBowDrillRqm);
selectedButton = "bow drill";
}
public void perform(View view){
if (!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock){
switch (selectedButton){
case "fire plough":
String msgToShow = "";
String extraInfo = "";
String[] timePassMsg;
Bundle extras = new Bundle();
//timepass method must run before the fireToLast method
timePassMsg = GameData.GDI.timePass(30, 1, 1, 1, this);
if (GameData.GDI.anyThisInventoryInBackpack(GameData.TINDER)) {
GameData.GDI.setInventoryAmount(GameData.TINDER, true, -1);
}
else {
GameData.GDI.setInventoryAmount(GameData.TINDER, false, -1);
}
extras.putString("toolUsed", getString(R.string.usedTinderMsg));
//update tool durability
GameData.GDI.firePloughDurability = GameData.GDI.updateInventoryDurability(GameData.FIRE_PLOUGH, GameData.GDI.firePloughDurability, GameData.FIRE_PLOUGH_MAX_DURABILITY);
//Because in GameCamp.updateInventoryDurability, if the tool broke, it will reset the durability to its maxDurability;
//so if these 2 numbers equal, the tool just broke
if (GameData.GDI.firePloughDurability == GameData.FIRE_PLOUGH_MAX_DURABILITY) {
extraInfo += getString(R.string.firePloughBreakMsg) + "\n\n";
}
GameData.GDI.bowDrillUnlockCounter += 1;
if (Math.random() < 0.75) {
GameData.GDI.currentLocation.fireOn = true;
GameData.GDI.currentLocation.fireToLast += 10;
msgToShow += getString(R.string.success) + "\n";
extras.putString("className", "Fire");
}
else {
msgToShow += getString(R.string.fail) + "\n";
if (!GameData.GDI.bowDrillUnlocked) {
if (GameData.GDI.bowDrillUnlockCounter >= 3) {
extraInfo += getString(R.string.bowDrillUnlockMsg) + "\n\n";
GameData.GDI.bowDrillUnlocked = true;
GameData.GDI.setCraftingAlertIcon(3);
}
}
extras.putString("className", "Make Fire");
}
Intent intent = new Intent(this, LoadingPage.class);
extras.putString("actionName", getString(R.string.makingFireWithFirePlough));
extras.putInt("timeNeeded", 30);
extras.putString("msgToShow", msgToShow);
extras.putString("extraInfo", extraInfo);
extras.putString("timePassMsg", timePassMsg[0]);
extras.putString("deathReason", timePassMsg[1]);
intent.putExtras(extras);
startActivity(intent);
break;
case "bow drill":
String msgToShow1 = "";
String extraInfo1 = "";
String[] timePassMsg1;
Bundle extras1 = new Bundle();
//timepass method must run before the fireToLast method
timePassMsg1 = GameData.GDI.timePass(10, 1, 1, 1, this);
if (GameData.GDI.anyThisInventoryInBackpack(GameData.TINDER)) {
GameData.GDI.setInventoryAmount(GameData.TINDER, true, -1);
}
else {
GameData.GDI.setInventoryAmount(GameData.TINDER, false, -1);
}
extras1.putString("toolUsed", getString(R.string.usedTinderMsg));
//update tool durability
GameData.GDI.bowDrillDurability = GameData.GDI.updateInventoryDurability(GameData.BOW_DRILL, GameData.GDI.bowDrillDurability, GameData.BOW_DRILL_MAX_DURABILITY);
//Because in GameCamp.updateInventoryDurability, if the tool broke, it will reset the durability to its maxDurability;
//so if these 2 numbers equal, the tool just broke
if (GameData.GDI.bowDrillDurability == GameData.BOW_DRILL_MAX_DURABILITY) {
extraInfo1 += getString(R.string.bowDrillBreakMsg) + "\n\n";
}
if (Math.random() < 0.95) {
GameData.GDI.currentLocation.fireOn = true;
GameData.GDI.currentLocation.fireToLast += 10;
msgToShow1 += getString(R.string.success) + "\n";
extras1.putString("className", "Fire");
}
else {
msgToShow1 += getString(R.string.fail) + "\n";
extras1.putString("className", "Make Fire");
}
Intent intent1 = new Intent(this, LoadingPage.class);
extras1.putString("actionName", getString(R.string.makingFireWithBowDrill));
extras1.putString("className", "Fire");
extras1.putInt("timeNeeded", 10);
extras1.putString("msgToShow", msgToShow1);
extras1.putString("extraInfo", extraInfo1);
extras1.putString("timePassMsg", timePassMsg1[0]);
extras1.putString("deathReason", timePassMsg1[1]);
intent1.putExtras(extras1);
startActivity(intent1);
break;
}
}
else {
GameData.GDI.showPlainMsg(getString(R.string.cannotMakeFireInStormMsg), this);
}
}
//fragment method
public void updateStatusBarFragment() {
StatusBarFragment statusBarFragment = (StatusBarFragment)getSupportFragmentManager().findFragmentById(R.id.statusBarFragment);
statusBarFragment.updateStatusBar();
}
public void updateDayTimeFragment() {
DayTimeFragment dayTimeFragment = (DayTimeFragment)getSupportFragmentManager().findFragmentById(R.id.dayTimeFragment);
dayTimeFragment.updateDayTimeView();
}
public void backButton(View view){
Intent intent = new Intent(this, Fire.class);
startActivity(intent);
}
}
I have three activities: MainActivity, DownloadServiceTest, ViewDetailDownload. Now, i want download files using Service (IntentService).
Corporeality :
MainActivity have buttons. When i click button_1 it to start a service (DownloadServiceTestextends IntentSerive ) perform download and I want when click button_2 it will startup ViewDetailDownload and update progress.
But when i start ViewDetailDownload i don't receive data(percent download, speed ) from DownloadServiceTest
My code here.
class MainActivity :
public class MainActivity extends Activity implements OnClickListener {
private final String LINK_MP3 = "http://data.chiasenhac.com/downloads/1471/5/1470643-c6ef1a26/320/Vo%20Hinh%20Trong%20Tim%20Em%20-%20Mr%20Siro%20%5BMP3%20320kbps%5D.mp3";
Activity activity;
Button btnDownload_1, btnDownload_2, btnDownload_3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_control);
activity = MainActivity.this;
btnDownload_1 = (Button) findViewById(R.id.btn_startdownload_1);
btnDownload_2 = (Button) findViewById(R.id.btn_startdownload_2);
btnDownload_3 = (Button) findViewById(R.id.btn_startdownload_3);
btnDownload_1.setOnClickListener(this);
btnDownload_2.setOnClickListener(this);
btnDownload_3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_startdownload_1) {
Intent intent = new Intent(activity, DownloadServiceTest.class);
intent.putExtra(DownloadServiceTest.REQUEST_STRING, LINK_MP3);
startService(intent);
}
if (v.getId() == R.id.btn_startdownload_2) {
Intent intent = new Intent(MainActivity.this,
ViewDetailDownload.class);
startActivity(intent);
}
}
}
class DownloadServiceTest :
public class DownloadServiceTest extends IntentService {
public static final String REQUEST_STRING = "REQUEST_LINK";
public static final String PROGRESS_UPDATE_ACTION = DownloadServiceTest.class
.getName() + ".progress_update";
private LocalBroadcastManager mLocalBroadcastManager;
private String mUrl_mp3;
public DownloadServiceTest(String name) {
super(name);
}
public DownloadServiceTest() {
super("DownloadService");
}
#Override
public void onCreate() {
mLocalBroadcastManager = LocalBroadcastManager
.getInstance(DownloadServiceTest.this);
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
protected void onHandleIntent(Intent intent) {
mUrl_mp3 = intent.getStringExtra(REQUEST_STRING);
DownloadTask task = new DownloadTask();
if (mUrl_mp3 != null) {
task.execute(mUrl_mp3);
}
}
private void onProgressUpdateReceiver(int progress, int speed) {
Intent intent = new Intent();
intent.setAction(PROGRESS_UPDATE_ACTION);
intent.putExtra("progress", progress);
intent.putExtra("speed", speed);
Log.i("", "abc onProgressUpdateReceiver progress "+progress);
Log.i("", "abc onProgressUpdateReceiver speed "+speed);
mLocalBroadcastManager.sendBroadcast(intent);
}
private class DownloadTask extends AsyncTask<String, Void, Void> {
String filename;
int mProgress;
int mSpeed;
private int checkExist;
File SDCardRoot;
private FileOutputStream fileOut;
private InputStream fileIn;
File file;
#Override
protected void onPreExecute() {
filename = mUrl_mp3.substring(mUrl_mp3.lastIndexOf("/") + 1);
try {
filename = URLDecoder.decode(filename, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
int contentLengh = 0;
try {
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
if (HttpURLConnection.HTTP_OK == urlConnection
.getResponseCode()) {
contentLengh = urlConnection.getContentLength();
Log.i("", "abc " + contentLengh);
fileIn = urlConnection.getInputStream();
SDCardRoot = Environment.getExternalStorageDirectory();
file = new File(Environment.getExternalStorageDirectory()
+ "/Blog Radio");
boolean success = true;
if (!file.exists()) {
success = file.mkdir();
}
String getTypeFile = filename.substring(filename
.indexOf("."));
if (success) {
file = new File(SDCardRoot.getAbsolutePath()
+ "/Blog Radio/" + filename);
if (file.exists()) {
checkExist++;
String PATH = Environment
.getExternalStorageDirectory()
+ "/Blog Radio/"
+ filename.replace(filename
.substring(filename.indexOf(".")),
"")
+ "_"
+ checkExist
+ getTypeFile;
file = new File(PATH);
}
} else {
file = new File(SDCardRoot.getAbsolutePath()
+ "/Blog Radio/" + filename);
if (file.exists()) {
checkExist++;
String PATH = Environment
.getExternalStorageDirectory()
+ "/Blog Radio/"
+ filename.replace(filename
.substring(filename.indexOf(".")),
"")
+ "_"
+ checkExist
+ getTypeFile;
file = new File(PATH);
}
}
fileOut = new FileOutputStream(file);
int downloadSize = 0;
byte[] buffer = new byte[8192];
long tempTotal = 0;
long startTime = System.currentTimeMillis();
int bufferLengh = 0;
while ((bufferLengh = fileIn.read(buffer)) != -1) {
long interval = System.currentTimeMillis() - startTime;
if (isCancelled()) {
fileIn.close();
}
if (contentLengh > 0) {
downloadSize += bufferLengh;
tempTotal += bufferLengh;
mProgress = (int) ((downloadSize * 100L) / contentLengh);
if (interval >= 1000) {
Log.i("now = ", String.valueOf(System
.currentTimeMillis()));
Log.i("last = ", String.valueOf(startTime));
Log.i("currentDump = ",
String.valueOf(tempTotal));
mSpeed = (int) (tempTotal * 1000 / interval / 1024);
startTime = System.currentTimeMillis();
tempTotal = 0;
}
fileOut.write(buffer, 0, bufferLengh);
onProgressUpdateReceiver(mProgress, mSpeed);
}
}
fileOut.flush();
fileOut.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
class ViewDetailDownload :
public class ViewDetailDownload extends Activity {
TextView tv_Title, tv_Info;
ProgressBar progressBar;
ImageView img;
MyRequestReceiver receiver;
IntentFilter intentToReceiveFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_service_layout);
img = (ImageView) findViewById(R.id.img);
tv_Title = (TextView) findViewById(R.id.title);
tv_Info = (TextView) findViewById(R.id.info);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
intentToReceiveFilter = new IntentFilter();
intentToReceiveFilter
.addAction(DownloadServiceTest.PROGRESS_UPDATE_ACTION);
receiver = new MyRequestReceiver();
}
#Override
protected void onResume() {
registerReceiver();
super.onResume();
}
private void registerReceiver() {
this.registerReceiver(receiver, intentToReceiveFilter);
}
#Override
protected void onPause() {
unregisterReceiver();
super.onPause();
}
protected void onProgressUpdate(int progress, int speed) {
progressBar.setProgress(progress);
tv_Info.setText(speed);
}
protected void onProgressUpdateOneShot(int progresses, int speeds) {
int progress = progresses;
int speed = speeds;
onProgressUpdate(progress, speed);
}
private void unregisterReceiver() {
this.unregisterReceiver(receiver);
}
public class MyRequestReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
DownloadServiceTest.PROGRESS_UPDATE_ACTION)) {
int progresses = intent.getIntExtra("progress", -1);
int speeds = intent.getIntExtra("speed", -1);
Log.i("", "abc progresses onReceive" + progresses);
Log.i("", "abc speeds onReceive" + speeds);
onProgressUpdateOneShot(progresses, speeds);
}
}
}
}
I need help !
If you know... please give example.
Thanks all
add this in DownloadServiceTest.java in onCreate() method.
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
String mname =(String) b.getString("LINK_MP3");
}
Now you can use this string mname anywhere in your DownloadServiceTest
I have a some thread that opens progress dialog and downloads a file. While thread downloads the file, it update progress bar. But if progress dialog was hidden, thread creates a notification and updating progress bar in the notification. I wanna make this: when user click on the notification, Android opens Activity and showing progress dialog.
How can I do this?
That is my method that downloading a file:
public void downloadAction(int id) {
if(id<0 || id>data.length) { IO.showNotify(MusicActivity.this, getResources().getStringArray(R.array.errors)[4]); return; }
final int itemId = id;
AsyncTask<Void, Integer, Boolean> downloadTask = new AsyncTask<Void, Integer, Boolean>() {
ProgressDialog progressDialog = new ProgressDialog(MusicActivity.this);
String error = null;
int nId = -1;
int progressPercent = 0;
boolean notificated = false;
int urlFileLength;
String FILE_NAME = fileName(data.getName(itemId));
#Override
protected void onPreExecute() {
progressDialog.setTitle(data.getName(itemId));
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
cancel(true);
}
});
progressDialog.setButton(Dialog.BUTTON_POSITIVE, getResources().getString(R.string.hide), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
progressDialog.hide();
}
});
progressDialog.setButton(Dialog.BUTTON_NEGATIVE, getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(progressDialog.isShowing()) { cancel(true); progressDialog.dismiss();}
}
});
progressDialog.show();
progressDialog.setProgressNumberFormat("");
}
#Override
protected Boolean doInBackground(Void... params) {
int localFileLength, len;
int fullProgress = 0;
byte[] bytes = new byte[1024];
File rootDir = new File(PATH);
if(!rootDir.isDirectory()) rootDir.mkdir();
try {
URLConnection urlConnection = new URL(data.getUrl(itemId)).openConnection();
urlConnection.setConnectTimeout(20000);
urlConnection.setReadTimeout(60000);
localFileLength = (int) new File(FILE_NAME).length();
urlFileLength = urlConnection.getContentLength();
if (urlFileLength == 169 || urlFileLength == 0 || urlFileLength == -1) {
error = getResources().getStringArray(R.array.errors)[5];
return false;
}
if (urlFileLength == localFileLength) {
error = getResources().getString(R.string.file_exist);
return false;
} else {
publishProgress(0, urlFileLength);
InputStream in = urlConnection.getInputStream();
OutputStream out = new FileOutputStream(FILE_NAME);
while((len=in.read(bytes))!=-1) {
if(!isCancelled()) {
out.write(bytes, 0, len);
fullProgress += len;
publishProgress(fullProgress);
} else {
new File(FILE_NAME).delete();
error = getResources().getString(R.string.stopped);
return false;
}
}
}
} catch (MalformedURLException e) {
new File(FILE_NAME).delete();
error = getResources().getStringArray(R.array.errors)[2];
} catch (IOException e) {
new File(FILE_NAME).delete();
error = getResources().getStringArray(R.array.errors)[3];
}
return true;
}
#Override
protected void onProgressUpdate(Integer ... progress) {
int tmp;
if (progress.length==2) {
progressDialog.setProgress(progress[0]);
progressDialog.setMax(progress[1]);
} else if(progress.length==1) {
if(!progressDialog.isShowing()) {
if(!notificated) {
nId = NotificationUtils.getInstace(MusicActivity.this).createDownloadNotification(data.getName(itemId));
notificated = true;
} else {
tmp = (int) (progress[0]/(urlFileLength*0.01));
if(progressPercent!=tmp) {
progressPercent = tmp;
NotificationUtils.getInstace(MusicActivity.this).updateProgress(nId, progressPercent);
}
}
} else {
progressDialog.setProgress(progress[0]);
}
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result==true && error == null) {
if(progressDialog.isShowing()) {
IO.showNotify(MusicActivity.this, getResources().getString(R.string.downloaded) + " " + PATH);
progressDialog.dismiss();
} else if (nId!=-1) {
NotificationUtils.getInstace(MusicActivity.this).cancelNotification(nId);
NotificationUtils.getInstace(MusicActivity.this).createMessageNotification(data.getName(itemId) + " " + getResources().getString(R.string.finished));
}
} else {
if(progressDialog.isShowing()) {
IO.showNotify(MusicActivity.this, error);
progressDialog.dismiss();
} else if (nId!=-1){
NotificationUtils.getInstace(MusicActivity.this).cancelNotification(nId);
NotificationUtils.getInstace(MusicActivity.this).createMessageNotification(getResources().getString(R.string.error) + "! " + error);
}
}
}
#Override
protected void onCancelled() {
IO.showNotify(MusicActivity.this, getResources().getString(R.string.stopped));
}
};
if(downloadTask.getStatus().equals(AsyncTask.Status.PENDING) || downloadTask.getStatus().equals(AsyncTask.Status.FINISHED))
downloadTask.execute();
}
And that is two methods thats creating notification:
public int createDownloadNotification(String fileName) {
String text = context.getString(R.string.notification_downloading).concat(" ").concat(fileName);
RemoteViews contentView = createProgressNotification(text, text);
contentView.setImageViewResource(R.id.notification_download_layout_image, android.R.drawable.stat_sys_download);
return lastId++;
}
private RemoteViews createProgressNotification(String text, String topMessage) {
Notification notification = new Notification(android.R.drawable.stat_sys_download, topMessage, System.currentTimeMillis());
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification_download_layout);
contentView.setProgressBar(R.id.notification_download_layout_progressbar, 100, 0, false);
contentView.setTextViewText(R.id.notification_download_layout_title, text);
notification.contentView = contentView;
notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_ONLY_ALERT_ONCE;
Intent notificationIntent = new Intent(context, NotificationUtils.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;
manager.notify(lastId, notification);
notifications.put(lastId, notification);
return contentView;
}
Help me please...
I am not sure, but in my code of notification I have no notification.contentIntent = contentIntent; and you seem to be missing this before the manager.notify(lastId, notification); line:
notification.setLatestEventInfo(context, MyNotifyTitle, MyNotifiyText, contentIntent );
MyNotifyTitle is the Title of the Notification, MyNotifyText is the text. Add them before the contentIntent as
MyIntent.putExtra("extendedTitle", notificationIntent );
MyIntent.putExtra("extendedText" , notificationIntent );
Hope this helps.