Wednesday, 15 April 2015

Android Install APK by prommatically




call this method  where u needed or u can use the broadcast receiver when the new updated APK is uploaded.
-----------------------------------------------------------------------------------------------

private void update() {

new updateAPK().execute();
System.out.println("updating..done");


}
---------------------------------------------------------------------------------------------
use the asyntask

class updateAPK extends AsyncTask<String, Void, String>{

@Override
protected String doInBackground(String... params) {
downloadapk();
return null;
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
installApk();
}

}


-----------------------------------------------------------------------------
download the APK

private void downloadapk(){
   try {
       URL url = new URL("http://bluetaxi.in/apk/Spot.apk");
       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();
    //   this.checkUnknownSourceEnability();
     //  this.initiateInstallation();

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

---------------------------------------------------------------------------------------------
install by programm

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

Monday, 13 April 2015

Android auto update apk implementation

public class UpdateApp extends AsyncTask<String,Void,Void>{
private Context context;
public void setContext(Context contextf){
    context = contextf;
}

@Override
protected Void doInBackground(String... arg0) {
      try {
            URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = "/mnt/sdcard/Download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "update.apk");
            if(outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
            context.startActivity(intent);


        } catch (Exception e) {
            Log.e("UpdateAPP", "Update error! " + e.getMessage());
        }
    return null;
}}
To use it, in your main activity call by this way:
            atualizaApp = new UpdateApp();
            atualizaApp.setContext(getApplicationContext());
            atualizaApp.execute("http://serverurl/appfile.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
    .setDataAndType(Uri.parse("file:///path/to/your.apk"), 
                    "application/vnd.android.package-archive");
startActivity(promptInstall); 
Intent goToMarket = new Intent(Intent.ACTION_VIEW)
    .setData(Uri.parse("market://details?id=com.package.name"));
startActivity(goToMarket);

References:

  1. http://stackoverflow.com/questions/4967669/android-install-apk-programmatically
  2. http://stackoverflow.com/questions/4604239/install-application-programmatically-on-android

Sunday, 12 April 2015

In android, we can easily check whether GPS is enabled in device or not using LocationManager.

public void turnGPSOn()
{
     Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
     intent.putExtra("enabled", true);
     this.ctx.sendBroadcast(intent);

    String provider = Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(!provider.contains("gps")){ //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        this.ctx.sendBroadcast(poke);


    }
}
// automatic turn off the gps
public void turnGPSOff()
{
    String provider = Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        this.ctx.sendBroadcast(poke);
    }
}

Thursday, 2 April 2015

Android Sart and Stop Service from Alaram Manager every 30 second

package com.example.alarmmanagerexample;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class AlarmManagerExample extends Activity {
   
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_manager_example);
       
       
        Button buttonStart=(Button)findViewById(R.id.buttonStart);
        Button buttonStop=(Button)findViewById(R.id.buttonStop);
       
       
        buttonStart.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                startCall();
            }

            private void startCall() {
               
                Log.d("****", "Start");
                Calendar calendar = Calendar.getInstance();
                Intent intent = new Intent(AlarmManagerExample.this, MyService.class);
                PendingIntent pintent = PendingIntent.getService(AlarmManagerExample.this, 0, intent, 0);
                AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10*1000, pintent);
                Log.d("****", "Start");
               
            }
        });
       
        //stop service
       
        buttonStop.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
               
                stopService(new Intent(getBaseContext(), MyService.class));
            }
        });
       
       
    }

   
}

Sunday, 15 March 2015

android read name and phone n umbers from the addressbok

private void getCont() {

// TODO Auto-generated method stub
        ArrayList<String> contacts = new ArrayList<String>();

        Cursor c = getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                null, null, null);
        while (c.moveToNext()) {

            String contactName = c
                    .getString(c
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phNumber = c
                    .getString(c
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            contacts.add(contactName + ":" + phNumber);
           
            Log.d("contactName", ""+contactName);
            Log.d("phNumber", ""+phNumber);

        }
        c.close();
}