I need to deploy and update various enterprise applications to Android devices given to a limited number of users.
These applications are not supposed to be published on Google Play but must be distributed via a separate channel.
What I need to do is an "enterprise package manager" application to automatically check for new apps/updates and automatically trigger installation of new or updated APKs without asking user consent first.
I know that, by design, Android doesn't allow 3rd party applications to interact with installed applications. I also know that rooted phones don't have this problem because you can inject any APK into the device.
If I cook a ROM (even based on CWM) with the "enterprise package manager" installed as system application, but without su binary (it's still an enterprise phone...), will that program be able to install new apps automatically?
How am I supposed to install an application without asking for consent? I mean, I need a basic code sample and permissions, if required
Anyway, do system apps run as root user? I remember so
If you want to check for your application which is on somewhere on your server you have to check for Update in every 24 hour once, if there is any update available then it will navigate to the async task where your updated version build will get installed
public void checkforUpdate() {
/* Get Last Update Time from Preferences */
SharedPreferences prefs = getPreferences(0);
lastUpdateTime = prefs.getLong("lastUpdateTime", 0);
if ((lastUpdateTime + CommonString.timeCheckDuration) < System.currentTimeMillis() && System.currentTimeMillis()>lastUpdateTime) {
// Asynch task
new VersionCheckTask().execute();
}
else{
// do nothing
}
}
now it will navigate to:
private class VersionCheckTask extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
progressDialog = new ProgressDialog(Login.this, android.R.style.Theme_Holo_Light_Dialog);
//progressDialog.setTitle("AppName");
progressDialog.setMessage("Checking for updates...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected Void doInBackground(Void... params) {
/**
* Simulates a background job.
*/
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
HashMap<String, String> map = new HashMap<String, String>();
map.put("build",CommonString.buildVersion);
map.put("en", CommonString.en);
responce = CommonFunction.PostRequest("updateCheck", map);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
if(!CommonFunction.isNetworkAvailable()){
Toast.makeText(ClaimColonyApplication.getAppContext(), CommonString.NO_NETWORK, Toast.LENGTH_SHORT).show();
return;
}
ParseUpdateResponse(responce);
if(rCodeUpdate == 100 && ApkLink.length() >0){
new AlertDialog.Builder(Login.this,android.R.style.Theme_Holo_Light_Dialog)
.setIcon(R.drawable.ic_launcher)
.setTitle("Update Available")
.setMessage(""+UpdateMessage)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//User clicked OK so do some stuff
new VersionCheckTaskDialog().execute();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//User clicked Cancel
finish();
}
})
.show();
}else{
if(rCodeUpdate == 100){
lastUpdateTime = System.currentTimeMillis();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putLong("lastUpdateTime", lastUpdateTime);
editor.commit();
}
}
super.onPostExecute(result);
}
}
private class VersionCheckTaskDialog extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialogUpdate;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
progressDialogUpdate = new ProgressDialog(Login.this, android.R.style.Theme_Holo_Light_Dialog);
//progressDialog.setTitle("AppName");
progressDialogUpdate.setMessage("Fetching updates...");
progressDialogUpdate.setCancelable(false);
progressDialogUpdate.setIndeterminate(true);
progressDialogUpdate.show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected Void doInBackground(Void... params) {
/**
* Simulates a background job.
*/
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
File file = new File(folder, "AppName."+"apk");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
/**
* replace url to ApkLink
*/
//DownloadFile(ApkLink, file);
DownloadFile("URL", file);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialogUpdate != null && progressDialogUpdate.isShowing())
progressDialogUpdate.dismiss();
if(!CommonFunction.isNetworkAvailable()){
Toast.makeText(ClaimColonyApplication.getAppContext(), CommonString.NO_NETWORK, Toast.LENGTH_SHORT).show();
return;
}
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/pdf/" + "AppName.apk")), "application/vnd.android.package-archive");
startActivity(intent);
lastUpdateTime = System.currentTimeMillis();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putLong("lastUpdateTime", lastUpdateTime);
editor.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Exception in start intent for launch app-------: "+e.toString());
e.printStackTrace();
}
super.onPostExecute(result);
}
}
I am checking for update once in 24 hours, if there is any update available then it will show pop up to upgrade your application otherwise will save your last checking time in Preferences.
Now this will allow you to update and install your application and this will check for next update after 24 hours, you may need to work on conditions to check for update. Please change name of your .apk file and URL.
You will need following permissions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Best of luck.
Related
Does anyone know how to create folder programatically using dropbox api for android??I am not using sync api.I have managed to upload images and files but I am unable to create folder.
This is my upload asynctask:
public class UploadFile extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> mApi;
private String mPath;
private File mFile;
private long mFileLen;
private UploadRequest mRequest;
private Context mContext;
private ProgressDialog mDialog;
final static private String ACCOUNT_PREFS_NAME = "prefs";
private String mErrorMsg;
public UploadFile(Context context, DropboxAPI<?> api, String dropboxPath,
File file) {
mContext = context;
mFileLen = file.length();
mApi = api;
mPath = dropboxPath;
mFile = file;
mDialog = new ProgressDialog(context);
mDialog.setMax(100);
mDialog.setMessage("Uploading " + file.getName());
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton("Cancel", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// This will cancel the putFile operation
mRequest.abort();
}
});
mDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
// By creating a request, we get a handle to the putFile operation,
// so we can cancel it later if we want to
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + mFile.getName();
mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}
#Override
public void onProgress(long bytes, long total) {
publishProgress(bytes);
}
});
if (mRequest != null) {
mRequest.upload();
return true;
}
} catch (DropboxUnlinkedException e) {
// This session wasn't authenticated properly or user unlinked
mErrorMsg = "This app wasn't authenticated properly.";
} catch (DropboxFileSizeException e) {
// File size too big to upload via the API
mErrorMsg = "This file is too big to upload";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Upload canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
e.printStackTrace();
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
} catch (FileNotFoundException e) {
}
return false;
}
#Override
protected void onProgressUpdate(Long... progress) {
int percent = (int) (100.0 * (double) progress[0] / mFileLen + 0.5);
mDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("Successfully uploaded");
// mApi.getSession().unlink();
//
// // Clear our stored keys
// clearKeys();
} else {
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
private void clearKeys() {
SharedPreferences prefs = mContext.getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
}
Please help.
According to dropbox documentation
try {
// creating folder
val fo = client.files().createFolderV2(File.separator + folderPath)
} catch (ex: CreateFolderErrorException) {
if (ex.errorValue.isPath && ex.errorValue.pathValue.isConflict) {
// folder already exist
}
}
You can simply give like this for creating a folder! its very simple
dropbox.putFile("Mynumber2/myregion2/"+"/"+"A"+"/"+"B"+"/"+"ENTRY.db", fileInputStream,file.length(), null, null);
if you do, mynumber2-->myregion2-->A-->B will be your folder structure created on dropbox!
You want the createFolder method of DropboxAPI. See https://www.dropbox.com/static/developers/dropbox-android-sdk-1.6.1-docs/com/dropbox/client2/DropboxAPI.html#createFolder(java.lang.String).
Use the following for DIR:
"/your_folder_name/"
The first time my app runs it creates a database in which it loads 6,000 rows from a file in /res/raw. I can't do this asynchronously as the app depends on it entirely. It runs rapidly on my phone - a Moto X - but it's really slow in all my emulators and I'm concerned it could be a bit slower on slower devices thus making the user stare at a blank screen for a few seconds before the app does anything.
Is there a way to put a progress bar while running the overrided SQLiteOpenHelper's onCreate() methood and have it update the progress bar with how far along it is, with a message saying something like "Initializing data for first use!"?
I solved this problem by starting an AsyncTask in onCreate and then only loading the layout at the end of the 'AsyncTask` (or if the data had previously been loaded). It works beautifully as a loading screen. I followed this tutorial http://www.41post.com/4588/programming/android-coding-a-loading-screen-part-1 (which explains the details more) then changed it a bit for my needs (such as loading a raw resource).
I should say that although it does it asynchronously because the main layout hasn't loaded the user has to wait for the loading to complete before he or she can continue, so hopefully that means it doing it asynchronously won't be a problem for you with the app depending on the database.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
dataAddedToDB = (sharedPref.getBoolean(PXS_RXS_UPDATE, false));
if (!dataAddedToDB) {
new LoadViewTask(this).execute();
} else {
setContentView(R.layout.activity_main);
}
}
In the AsyncTask it loads the database showing how far it has got and showing your message and then only goes on to show the layout at the end. (BTW, it is helpful to lock the screen orientation while doing this to stop it messing it up).
EDIT: publishProgress(counter); passes the value of where the task has got to to onProgressUpdate().
private class LoadViewTask extends AsyncTask<Void, Integer, Void> {
private Context context;
public LoadViewTask(Context context) {
this.context = context.getApplicationContext();
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle("Loading...");
progressDialog.setMessage("Initializing data for first use!");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
// this counts how many line to be added to the database so it can later tell how far it has got.
final Resources resources2 = context.getResources();
InputStream inputStream2 = resources2.openRawResource(R.raw.rawherbaldata);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream2));
int lineCount = 0;
try {
String line;
while ((line = reader.readLine()) != null) {
lineCount++;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
progressDialog.setMax(lineCount);
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
HerbalDatabaseOpenHelper mHerbalDbHelper = new HerbalDatabaseOpenHelper(MainActivity.this);
SQLiteDatabase db = mHerbalDbHelper.getWritableDatabase();
int counter = 0;
final Resources resources2 = context.getResources();
InputStream inputStream2 = resources2.openRawResource(R.raw.rawherbaldata);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream2));
db.beginTransaction();
try {
int lineNumber = 1;
String line;
while ((line = reader.readLine()) != null) {
// CODE FOR ENTERING LINE INTO DATABASE
// EDIT: the following keeps the task updated on where it has got to, passing the count to onProgressUpdate()
counter++;
publishProgress(counter);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
db.setTransactionSuccessful();
db.endTransaction();
db.close();
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
pxsRxsUpdate = true;
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(PXS_RXS_UPDATE, pxsRxsUpdate);
editor.commit();
// initialize the View
setContentView(R.layout.activity_main);
}
}
You could use another intermediate activity which would show the progress dialog and then send you back to the main activity when done.
First you'll need a static method that a boolean if the DB has already been create.
Then inside of your activity's onCreate call the middleman if necessary:
DbHelper mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!DbHelper.isDbCreated()) {
Intent intent = new Intent(this, DbActivity.class);
startActivity(intent);
finish();
return;
}
// Do normal stuff like instantiating the helper and so on
mDbHelper = new DbHelper();
...
}
Then inside of this "middleman" activity show the ProgressDialog and create the database.
Once you're done, hide the dialog and go back to your main activity:
mProgress.dismiss();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
return;
If your static method isDbCreated() is created properly, you won't reveal the MainActivity's content until the database is created.
EDIT:
Here's the method I use to check for the database. Perhaps it will help you.
public boolean isDbCreated() {
String sDatabasePath = context.getDatabasePath(DB_NAME).getPath();
SQLiteDatabase tmpDb = null;
if (mContext.getDatabasePath(DB_NAME).exists()) {
try {
tmpDb = SQLiteDatabase.openDatabase(sDatabasePath, null,
SQLiteDatabase.OPEN_READONLY);
tmpDb.close();
} catch (SQLiteException e) {
e.printStackTrace();
}
} else {
Log.e(TAG, "DB file doesn't exist.");
// If the parent dir doesn't exist, create it
File parentDir = new File(mContext.getDatabasePath(DB_NAME).getParent());
if (!parentDir.exists()) {
if (parentDir.mkdirs()) {
Log.d(TAG, "Successfully created the parent dir:" + parentDir.getName());
} else {
Log.e(TAG, "Failed to create the parent dir:" + parentDir.getName());
}
}
}
return (tmpDb != null);
}
I am testing the Drive API for Android to upload a file that can show uploaded progress and be able to resume the upload if it fails (Files size > 30 MB.)
With the following questions:
Uploading Downloading of large size file to Google Drive giving error,
Upload progress listener not fired (Google drive API)
I was able to get the upload progress and they mention those are resumable uploads. However, I don't see any code that looks for an upload error and resume logic, thus if I kill the application and "resume" the upload, it simply starts from the beginning.
This is my code:
public class DriveScreen extends BaseDriveActivity {
private Drive service;
private Context context;
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
context = this;
//https://stackoverflow.com/questions/17429798/usingoauth2-deprecated
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(this, Arrays.asList(DriveScopes.DRIVE_FILE));
credential.setSelectedAccountName("accountNameHERE");
service = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
UploadFile();
}
public void UploadFile() {
AsyncTask<Void, Long, String> task = new AsyncTask<Void, Long, String>() {
java.io.File fileContent;
FileContent mediaContent;
com.google.api.services.drive.model.File body;
com.google.api.services.drive.model.File file;
private ProgressDialog mDialog;
long mFileLen;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mDialog = new ProgressDialog(context);
mDialog.setMax(100);
mDialog.setMessage("Uploading ");
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
});
mDialog.show();
}
class FileUploadProgressListener implements MediaHttpUploaderProgressListener {
#Override
public void progressChanged(MediaHttpUploader uploader) throws IOException {
Log.d("Percent ", String.valueOf(uploader.getProgress()));
switch (uploader.getUploadState()) {
case INITIATION_STARTED:
System.out.println("Initiation Started");
break;
case INITIATION_COMPLETE:
System.out.println("Initiation Completed");
break;
case MEDIA_IN_PROGRESS:
System.out.println("Upload in progress");
System.out.println("Upload percentage: " + uploader.getProgress());
mDialog.setProgress((int) (uploader.getProgress()*100));
break;
case MEDIA_COMPLETE:
System.out.println("Upload Completed!");
break;
case NOT_STARTED:
System.out.println("Upload Not Started!");
break;
}
}
}
#Override
protected String doInBackground(Void... arg0) {
try {
File folder = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
);
File UPLOAD_FILE = new File(folder, "filePathHERE");
fileContent = new File(folder, "filePathHERE");
mFileLen = fileContent.length();
InputStreamContent mediaContent2 = new InputStreamContent("application/zip", new FileInputStream(UPLOAD_FILE));
mediaContent2.setLength(UPLOAD_FILE.length());
body = new com.google.api.services.drive.model.File();
body.setTitle(fileContent.getName());
body.setMimeType("application/zip");
//String parentId = null;
//int x = Files.List.setQ("mimeType = 'application/vnd.google-apps.folder' and title = 'ShareHim'");
//body.setParents(Arrays.asList(new ParentReference().setId(uploadFile.getFileHostFolderId())));
Files.Insert mInsert = service.files().insert(body, mediaContent2);
if(mFileLen > 5 * 1024 * 1024)
{
MediaHttpUploader uploader = mInsert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(false);
uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE);
uploader.setProgressListener(new FileUploadProgressListener());
file = mInsert.execute();
if (file != null) {
}
}
else {
mInsert.execute();
}
} catch (UserRecoverableAuthIOException e) {
System.out.println("login error");
Log.d("Error", "not login " + e);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
mDialog.dismiss();
};
};
task.execute();
}
}
Now, it is uploading by chunks, but how can we resume the upload from the last chunk sent. My first impression after watching Google Drive talks on youtube was that the resumable upload was handled automatically, but it doesn't seem to be the case.
Am I approaching this the wrong way? Is it worth considering using a DriveSyncAdapter to upload a file as an alternative? (Sorry for the bad code, this is just a test)
It looks like you are using the Java REST-ful API. If you use the Android-specific API, this is all handled for you. Just hand over the file, and the API will do resumable upload as appropriate. See creating files.
I have 2 Asynctask, 1 for get data (location) from server then set a marker on map with this location and another call 1st Asyntask in a loop for updating location.
Here my code:
public class AsynComp extends AsyncTask<Void, Void, Void> {
ProgressDialog taxiDialog;
#Override
protected Void doInBackground(Void... params) {
jsonComp = new JSONComp(find_url);
find_status = jsonComp.getJsonStatus(txt_search);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (find_status.equals("2013")) {
Toast.makeText(getBaseContext(), "no result",
Toast.LENGTH_SHORT).show();
} else if (find_status.equals("2012")) {
for (Marker marker:markers){
if(marker.getTitle().equals(compFollow)){
marker.remove();
}
}
for (int i=0; i<number;i++){
comp = new Comp(jsonComp.getJsondata(i));
SetMarkerComp(comp);
try {
Thread.sleep(1400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class AsynFollow extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (!taxiFollow.equals("")) {
number = 1;
txt_search = compFollow;
find_url = "http://192.111.125.80:8001/Default.aspx?username="
+ Id + "&password=" + Pass + "&sohieuxe="+txt_search;
while (!stop){
new AsynComp().execute();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
taxiFollow = "";
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!compFollow.equals("")) {
Toast.makeText(getBaseContext(), "Follow "+compFollow, Toast.LENGTH_SHORT).show();
} else {
iv_theodoi.setVisibility(View.VISIBLE);
iv_theodoif.setVisibility(View.GONE);
Toast.makeText(getBaseContext(), "Plz choose a marker", Toast.LENGTH_SHORT).show();
}
}
}
And i have 2 buuton, 1 to call AsynFollow.execute(), another to stop it.
This code can run but app will force close after awhile.
Any solution? thanks.
P/s: i'm a newbie in android.
You shoulnd you asyncTask for this. For repetitive action, like changing status in some interval, use Timer class. In this way you can implement repetitive action which can be repeated in intervals.
In this way you can stop this time by on click listener. You can run two times and specify it's realtions using other variables.
If you're newbe, you should read about multitasking in Android: Timer, AsyncTask, Handler.
In my opinion this docs will tell you much more than thousands of comments in stackoverflow.
progressDialog = ProgressDialog.show(GetResponse.this, "", "Loading...");
new Thread()
{
public void run()
{
try
{
// inside i have written code for making connection to the server using SSL connection.
}catch (Exception e)
{
progressDialog.dismiss();
exception(e.getMessage())
}.start();
}
private void exception(String msg)
{
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
this.finish();
Intent i = new Intent(getBaseContext(), LoginPage.class);
startActivity(i);
}
my LoginPage.java is previous activity.
If the connection is successfull it goes to the next activity ot doesnt give any error,
But if der is any prob with connection then i want progress bar should be stopped and go back to the LoginPage activity and also i want the error msg to be displayed.
From the above im getting some error.. Please help me out on this
Pass in and use the context from LoginPage. Also, use the 101010 button to format your code as code in your posts.
you can go up by using try catch mechanism where in your catch place your toast message and u can do it also by asynchronous task,
here simple code
private class Task_News_ArticleView extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(
Bru_Sports_View.this);
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
//here the condition to check login details
}
} catch (Exception e) {
}
return null;
}
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
and u can also use try,catch in catch block you can place your toast message
with finsih() method