Showing posts with label snippet. Show all posts
Showing posts with label snippet. Show all posts

Monday, December 19, 2016

Code Snippet Restricting Orientations

Code Snippet Restricting Orientations


Recent week, I have been hard finding it to restrict orientation to portrait and reverse portrait only. Today, got a solution/workaround. Thought it would be useful to share it.

The concern is to restrict the screen orientation to portrait and reverse portrait. Landscape and reverse landscape should not be supported. Hope you know that setting the screen orientation for activity(screen) can be done in either manifest file or in activity.

There is an attribute called "sensorPortrait"which exactly solves our case, as given in Android Developers forum. The point is ofcourse, its there.Works as expected in many devices. But it doesnt work in either Galaxy S3,S4 or Nexus. There is even a bug raised in google site. The challenge was to fix the orientation in these devices.

Was trying to address the issue with setting the configchanges  for orientation in manifest and trying to handle it in the onConfigurationChanged in activity. None of them worked out. Got insights from one of our old team-mate reg. (OrientationEventListener) and another app(The Ultimate Rotation Control) developer reg. (WindowOrientationListener).

Tried using the first one and referred the web and got a workaround.

PFB the workaround for my issue,
-------------------------------------------------------------------------------------------------------------
import android.os.Bundle;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.hardware.SensorManager;
import android.util.Log;
import android.view.Menu;
import android.view.OrientationEventListener;
import android.widget.Toast;

public class MainActivity extends Activity {
OrientationEventListener orientationListener;
    private static final int THRESHOLD = 10;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(MainActivity.this, "On Create", Toast.LENGTH_SHORT).show();
        orientationListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) {
            public void onOrientationChanged(int orientation) {
            if(isPortrait(orientation)){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }else if(isReversePortrait(orientation)){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
            }
            }
        };
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
@Override
protected void onPause() {
// TODO Auto-generated method stub
orientationListener.disable();

super.onPause();
}


@Override
protected void onResume() {
// TODO Auto-generated method stub
orientationListener.enable();
super.onResume();
}


private boolean isReversePortrait(int orientation){
        return orientation >= (180 - THRESHOLD) && orientation <= (180 + THRESHOLD);
    }

private boolean isPortrait(int orientation){
   return (orientation >= (360 - THRESHOLD) && orientation <= 360) || (orientation >= 0 && orientation <= THRESHOLD);
}

public boolean canShow(int orientation){
   return isReversePortrait(orientation);
}

public boolean canDismiss(int orientation){
   return isPortrait(orientation);
}
    
    
}
-------------------------------------------------------------------------------------------------------------

The values, (180, 360) are for portrait and reverse portrait modes. For Landscape and reverse landscape, you can try up with 90 and 270, where THRESHOLD is nothing but the limit within which the device can be considered as rotated to that position.Example - (360+-THRESHOLD) is portrait.

I have attached the full class file for reference.

References
http://stackoverflow.com/questions/8248274/android-detect-orientation-changed

Available link for download

Read more »

Monday, December 5, 2016

Code Snippet Installed Running Applications List

Code Snippet Installed Running Applications List


Create an Android Project as mentioned here.

List of Installed Apps:
Add the below code to get all the installed apps,

PackageManager packageManager = getPackageManager();
List<ApplicationInfo> appList =                  packageManager.getInstalledApplications(PackageManager.GET_ACTIVITIES);
for(ApplicationInfo info : appList){
    Log.i("AppInstallChecker",info.loadLabel(packageManager).toString());
 }

List of Running Apps:
Use the below code to get the list of running apps,

ActivityManager actvityManager = (ActivityManager) 
                                                                 this.getSystemService( ACTIVITY_SERVICE );
List<RunningAppProcessInfo> procInfos = actvityManager.getRunningAppProcesses();
for(RunningAppProcessInfo info : procInfos){
        Log.i("Running",info.processName);
 }

Check for App installed or not :
protected boolean isAppInstalled(String packageName) {
        Intent mIntent = getPackageManager().getLaunchIntentForPackage(packageName);
        if (mIntent != null) {
            return true;
        }
        else {
            return false;
        }

    }


Courtesy : 
http://stackoverflow.com/questions/13566479/check-app-is-installed-on-device-android-code
http://www.dreamincode.net/forums/topic/138412-android-20-list-of-running-applications/


Available link for download

Read more »

Tuesday, October 11, 2016

Code Snippet SD Cards Network check

Code Snippet SD Cards Network check


In many occassions, we may find a need to check for online condition and download files to our sd card.

PFB the code to check for network availability,

public boolean isNetworkAvailable() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;

}

PFB the code for SD Card mount check,

private boolean isSDCardMounted() {
String sdCardStatus = android.os.Environment.getExternalStorageState();
return sdCardStatus.equals(android.os.Environment.MEDIA_MOUNTED);
}

PFB the code that returns available space in SD Card,

public int getFreeExtMemory()
{
    StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
    int free  =  ((statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1024);
    Log.i("AppInstallChecker", "Available Space : " + free + " KB, Required Space : "+APPSIZE_KB+" KB");
    return free;
}

Note : The methods getAvailableBlocks() & getBlockSize() from the above method/snippet is deprecated after api 18, so put a check if needed.

References :
http://stackoverflow.com/questions/5474089/how-to-check-currently-internet-connection-is-available-or-not-in-android
http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts
http://stackoverflow.com/questions/7429228/check-whether-the-sd-card-is-available-or-not-programatically
http://stackoverflow.com/questions/3394765/how-to-check-available-space-on-android-device-on-mini-sd-card


Available link for download

Read more »

Monday, October 10, 2016

Code Snippet Download and install apk file programmatically

Code Snippet Download and install apk file programmatically


Downloading a file can be done in many ways.

either using httpurlconnection or httpclient or download manager in android.

using httpurlconnection

String result = "";
try {
URL url = new URL(this.url);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();

File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.apk");

FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();

byte[] buffer = new byte[1024];
int bufferLength = 0;

while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
result = "done";

catch (MalformedURLException e) {
e.printStackTrace();
catch (IOException e) {
e.printStackTrace();
}
return result;


using download manager works from api 9,

Uri src_uri = Uri.parse("http://your.url.here/File.apk");
Uri dst_uri = Uri.parse("file:///mnt/sdcard/download/File.apk");

DownloadManager.Request req = new DownloadManager.Request(src_uri);
req
.setDestinationUri(dst_uri);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm
.enqueue(req);
There is another one line technique,
org.apache.commons.io.FileUtils.copyURLToFile(URL, File)

Below is an example,

class InstallTask extends AsyncTask<Void, Void, String> {
ProgressDialog mProgressDialog;

Context context;
String url;

public InstallTask(Context context, String url) {
this.context = context;

this.url = url;

}

protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(context,
"Download", " Downloading in progress..");
}

private String downloadapk() {
String result = "";
try {
URL url = new URL(this.url);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();

File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.apk");

FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();

byte[] buffer = new byte[1024];
int bufferLength = 0;

while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
result = "done";

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}

protected String doInBackground(Void... params) {
String result = downloadapk();
return result;
}

protected void onPostExecute(String result) {
if (result.equals("done")) {
mProgressDialog.dismiss();
installApk();
} else {
Toast.makeText(context, "Error while downloading",
Toast.LENGTH_LONG).show();

}
}

private void installApk() {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File("/sdcard/filename.apk"));
intent.setDataAndType(uri, "application/vnd.android.package-archive");
context.startActivity(intent);
}

}


just paste the above code to use it as an asynctask.

Make sure to add write external storage and internet permission.

You can add this code before calling installApk(), if you may want to check for corrupted/incomplete apk files.

private boolean isApkCorrupted() {
        boolean corruptedApkFile = false;
        try {
             new JarFile(new File("/sdcard/filename.apk"));
        } catch (Exception ex) {
             corruptedApkFile = true;
        }
        return corruptedApkFile;
    } 


Courtesy
http://bpsinghrajput.blogspot.in/2012/07/how-to-download-and-install-apk-from.html
http://gafurbabu.wordpress.com/2012/02/29/download-file-in-android-by-using-asynctask-in-background-operations/
http://stackoverflow.com/questions/11121121/android-download-an-application-using-the-downloadmanager-class
http://stackoverflow.com/questions/8338786/is-there-a-way-to-be-notified-when-apk-fails-to-being-installed

Available link for download

Read more »