Android Code Snippets II

Android Studio Code Snippets :-
Build Cradle, Android Studio (Build:App) :-
apply plugin: 'com.android.application'
android { compileSdkVersion 24
buildToolsVersion '25.0.0'
defaultConfig {
 applicationId "com.abc.www.abcapp" // Application ID
minSdkVersion 15 // set sdk versions
targetSdkVersion 24
versionCode 9 // App Code version
versionName "1.8" // App version name }
buildTypes { // build variants debug
{ // debug/testing variant mode ....
minifyEnabled true // reduce/compact code
useProguard false // use proguard for compacting proguardFiles
getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro' // produard file }
release { // release version ....
minifyEnabled true // reduce/compact code
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' // proguard file
applicationVariants.all {
variant -> // compiling the productflavours to produce the final compilied Android distributable file (.apk file)
variant.outputs.each
{ output -> * output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace("app-abcpro-release", "abcprorel"))
output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace("app-acbfree-release","abcfreerel")) } } } }

productFlavors { // setup of the product flavours abcpro
{ applicationId = "com.abc.www.abcpro"
buildConfigField "boolean", "PAID_VERSION", "true" // setup various build switches/flags that can be used in the code to for different product flavours etc
buildConfigField "String", "DB_NAME", '"abc"'
buildConfigField "boolean", "DISPLAY_ADS", "false"
buildConfigField "boolean", "TEST_ADS", "false"
buildConfigField "String", "APP_KEY", '"abc1234"'
buildConfigField "String", "AD_ID", '"abc1234"'
buildConfigField "String", "APP_ID", '"abc1234"'
}
abcfree {
applicationId = "com.cesd.www.abcfree"
buildConfigField "boolean", "PAID_VERSION", "true"
buildConfigField "String", "DB_NAME", '"abc"'
buildConfigField "boolean", "DISPLAY_ADS", "true"
// etc ...... } } }
dependencies {// dependency listings .......
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:mediarouter-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:support-v4:24.2.1'
compile 'com.google.android.gms:play-services:8.4.0'// this can be broken down into various components if code has reached it's max size.
compile 'com.amazon.android:mobile-ads:5.+'
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha1'
compile 'com.adcolony:sdk:3.1.2'
compile 'com.android.support:support-annotations:24.2.1'
testCompile 'junit:junit:4.12'
compile 'com.google.code.ksoap2-android:ksoap2-android:3.6.1' }
Mainifest.xml examples :-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.abc.www.abcpro"
    android:versionCode="10"
    android:versionName="1.9">
// premission settiings .....
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.NFC" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_ROUTING" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="stateHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service                                                // settings for a service ....
            android:name=".MusicService"
            android:enabled="true"
            android:exported="true" />
        <activity                                                                            // settings for Amazon ads
            android:name="com.amazon.device.ads.AdActivity"
            android:configChanges="keyboardHidden|orientation|screenSize" />
        <!-- AppBrain AppLift SDK -->                                        // settings for AppBrain ads  
        <activity
            android:name="com.appbrain.AppBrainActivity"            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
        <receiver
            android:name="com.appbrain.ReferrerReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="com.android.vending.INSTALL_REFERRER" />
            </intent-filter>
        </receiver>
        <service android:name="com.appbrain.AppBrainService" />
        <!-- End of AppLift SDK -->
// settings for Adcolony ads
        <activity android:name="com.adcolony.sdk.AdColonyInterstitialActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:hardwareAccelerated="true"/>
        <activity android:name="com.adcolony.sdk.AdColonyAdViewActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:hardwareAccelerated="true"/>
    </application>
</manifest>

Requesting premissions at runtime ......
// setup values
  public static final int REQUEST_EXTERNAL_STORAGE = 1;
    public  static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
// function
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case cesddb.REQUEST_EXTERNAL_STORAGE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                       // permission granted do function/work here 
                } else {
               //permission denied
                }
                return;
            }
        }
    }


// function call permissions check ....
public void func_test_permissions(){
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // don't have permission, prompt the user
 ActivityCompat.requestPermissions(this,PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE
            );
        }else{
           // call required function ....
        }
    }
Menu Options:-
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_abc, menu);
        try{
            if(BuildConfig.DISPLAY_ADS) { // check build if display appbrain menu link
                AdService ads = AppBrain.getAds();
                MenuItem item = menu.add(ads.getOfferWallButtonLabel(this));
                ads.setOfferWallMenuItemClickListener(this, item);
            }
        } catch(Exception e){
// e.message
        }
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        Intent intent;
        switch (item.getItemId()) {
            case R.id.action_filedate:
// call a function
                return true;
            case R.id.action_enum:
// call a new intent class/screen
                intent = new Intent(this, ENumbers.class);
                startActivity(intent);
                return true;
            case R.id.action_pri:
                try{// start a website link via external browser ....
                intent = new Intent(Intent.ACTION_VIEW);
                intent.setType("*/*");
                intent.setData(Uri.parse(getResources().getString(R.string.lb_link_pri))); // your link goes here don't forget to add http://
                startActivity(new Intent(Intent.createChooser(intent, "Open webpage with:")));
                } catch(Exception e){
// e.message
                }
                return true;
               case R.id.action_quest:
              // display an popup alert box .... layout
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Help Notes :");
                // Get the layout inflater
                LayoutInflater inflater = this.getLayoutInflater();
                final View Genview = inflater.inflate(R.layout.view_info, null);
                TextView txt_str = (TextView) Genview.findViewById(R.id.txt_inst_details1); // find control on layout
                txt_str.setText(R.string.lb_maininstructs);
                builder.setView(Genview)
                        // Add action buttons
                        .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                // export the data .....
                                dialog.dismiss();
                            }
                        });
               builder.create(); // create the aleart
                builder.show(); // display the alert
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
General:
//types of imports .....
import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.Button;
import android.widget.EditText;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import com.adcolony.sdk.AdColony;
import com.adcolony.sdk.AdColonyInterstitial;
import com.adcolony.sdk.AdColonyInterstitialListener;
import com.amazon.device.ads.Ad;
import com.amazon.device.ads.AdError;
import com.amazon.device.ads.AdLayout;
import com.amazon.device.ads.AdProperties;
import com.amazon.device.ads.AdRegistration;
import com.amazon.device.ads.AdTargetingOptions;
import com.amazon.device.ads.DefaultAdListener;
import com.amazon.device.ads.InterstitialAd;
import com.appbrain.AdId;
import com.appbrain.AdService;
import com.appbrain.AppBrain;
import com.appbrain.AppBrainUserData;
import com.appbrain.AppBrainUserData.Gender;
import com.appbrain.InterstitialBuilder;
import com.appbrain.InterstitialListener;
import com.appbrain.RemoteSettings;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckedTextView;
import android.widget.MultiAutoCompleteTextView;
// types of definitions ....
acbdb cabcdb = new abcdb(this); // passing context to class
    ProgressBar pg;  // reference progress bar
    String str_display = "";
    webservice abcwebserv = new webservice(); // defined webservice class
    private AdLayout adview;   // Amazon adlayout 
    private InterstitialAd interstitialAd;   // Amazon InterstitialAd 
    private ArrayList<String> array_data = new ArrayList<String>();
    private String[] temp; // string array

Yeah, I've built a few apps along the way. You may find them useful. My official site is : chemistry chemical engineer solvers equations lotto android sports sudoku

Education/Profession based (Engineering,Chemistry,Maths,Unit Conversion....):- : -
chemistry chemical engineer solvers equations  Chemical Engineering Data Plus  Engineering Tools  Unit Conversions Engineering, General  Maths Linear Equations Solvers Plus

Health and Nutrition:-
 Nutrition and Health  Health maintain records
Sports:-
 Tennis game scorer and keeper  Aussie Rules predictor, team stats, year fixture,ladder updated per round  Racquet games scorer and keeper  Table Tennis game scorer and keeper  Badminton game scorer and stats keeper  Squash Game scorer and stats keeper
Games/Lotto :-
 Sudoku games Plus  Random Number Generator Plus  Pay Time monitor what you make every minute
onLine Radio :-
 onLine Radio world wide stations
Windows Applications(Engineering,Chemistry,Maths,Unit Conversion....):-
 ChemMaths for Windows  DataPro for Windows. Chemistry,Chemical Engineering Data.  EquationsPro for Windows.   GraphsProSim for Windows.  ChemPlayer. Media player for Windows.

Comments

Popular Posts