JavascriptProva

giovedì 15 marzo 2018

Primo approccio con php

Ripeschiamolo, questo php.
<?php

echo "vaffanculo Antonello"

?> 
Questo è un codice estremamente rudimentale.
Lo metto nel file studio.php e lo spedisco sul server.

Vediamo...

vaffanculo Antonello


Sì, funziona.

giovedì 8 febbraio 2018

Creare una libreria "interna" in Android

Spinoso problema delle librerie android.
Il punto chiave è generare un .aar.

Iniziamo con: Click File > New > New Module.
In the Create New Module window that appears, click Android Library, then click Next.

Give your library a name and select a minimum SDK version for the code in the library, then click Finish.

L'ho chiamata Mia Libreria e l'SDK minimo è 17.

E' stata fatta la sincronizzazione di Gradle.
Il cambiamento della voce apply plugin sul modulo Gradle della libreria è già stato cambiato da c.antonello.studiojar3 a com.android.library.
Ora dovrei salvare il file.
Come?
Boh... faccio "Save All"...

Ma il passo completo è Save the file and click Tools > Android > Sync Project with Gradle Files. Vado a cliccare quanto dovuto...

Bene.
Ora se io clicco "build APK" dovrebbe generarmi un AAR...
Lo deduco da questo: When you want to build the AAR file, select the library module in the Project window and then click Build > Build APK


Proviamo...

Fatto, e vediamo se si è generato un AAR...

Non funziona.
La procedura che funziona per creare l'aar è invece
View -> Tool Windows -> Gradle
Sulla finestra di gradle che si apre a destra si va su mialibreria -> Tasks -> assemble, e si generano due aar: una versione debug e una versione release.

Ora il problema è come usare queste librerie.
Ora, dato che la libreria fa parte di questo progetto, posso fare direttamente questo:
Make sure the library is listed at the top of your settings.gradle file, as shown here for a library named "my-library-module":
include ':app', ':my-library-module'
include ':app', ':mialibreria'
Confermato!
Open the app module's build.gradle file and add a new line to the dependencies block as shown in the following snippet:
dependencies {
    compile project(":my-library-module")
}
Vediamo:
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile project(":mialibreria")
}
Vediamo se sincronizza...

Ha sincronizzato.

Ora, nella mia libreria ho messo un codice estremamente fesso per fare la prova:
public class Classe {
    public Classe(){}
    public void Scrivi(){
        System.out.println("Ciao");
    }
}
Vediamo se si riesce a inserire la funzione.
No.


Anziché modificare manualmente il file app Gradle (parte che ho scritto in rosso) si può procedere con File -> Project Structure
Quindi si seleziona la scheda Dependencies e si aggiunge con il + il riferimento alla libreria.
Il file Gradle app si modifica così:
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation project(':mialibreria')
}
compile è deprecato, l'uso più moderno è di implementation.

sabato 13 gennaio 2018

IP statico? Come accidenti si fa?

Sulle reti non mi sono mai interessato, e comincio da sottozero.
DHCP = Dynamic Host Configuration Protocol.
Se ricordo bene, sarebbe quel giochino secondo il quale quando un computer si connette a una rete gli viene assegnato un IP diverso volta per volta.
Sperimentiamolo (GUH! GUH!) con questo computer. Qual è il mio IP attuale?

   Indirizzo IPv4. . . . . . . . . . . . : 192.168.113.2
   Subnet mask . . . . . . . . . . . . . : 255.255.255.0
   Gateway predefinito . . . . . . . . . :
Ora faccio la disconnessione e la riconnessione.
   Indirizzo IPv4. . . . . . . . . . . . : 192.168.200.1
   Subnet mask . . . . . . . . . . . . . : 255.255.255.0
   Gateway predefinito . . . . . . . . . :
Ecco, l'IP è cambiato.
Questa è la prova che l'IP è dinamico.


E questo è quello che si vede entrando nel router:
 PC-Antonello
192.168.1.109
Questo è l'IP assegnato in questo momento dal router al mio computer.
Come accidenti si fa a renderlo statico? Si può?

domenica 29 ottobre 2017

VB.NET: giocando con le matrici per scomporre un numero nelle sue cifre.

Rispolvero il VB.
L'idea è raccogliere i numeri derivati dalla scomposizione di un numero in unità, decine, centinaia eccetera, in una matrice, per poi scriverli comodamente ognuno in una label.
Vediamo...

Per ridimensionare le matrici dinamiche in VB ho costruito questo codice:
If (matrice(0) <> Nothing) Then ReDim Preserve matrice(UBound(matrice) + 1)
che dovrebbe funzionare.
Ora metto dei numeri consecutivi da 1 a 10 in una matrice dinamica che inizia con lunghezza 1 (uBound = 0) e si allunga progressivamente a seconda della quantità di elementi che possiederà alla fine.

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim matrice(0) As Integer

        For n = 1 To 10
            If matrice(0) <> Nothing Then ReDim Preserve matrice(matrice.Length)
            matrice(UBound(matrice)) = n
        Next

        For n = 0 To UBound(matrice)
            Debug.Print(matrice(n))
        Next

    End Sub
End Class
1
2
3
4
5
6
7
8
9
10
Posso cambiare liberamente anche la quantità dei dati da immettere nella matrice:
Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim matrice(0) As Integer

        For n = 1 To 15
            If matrice(0) <> Nothing Then ReDim Preserve matrice(matrice.Length)
            matrice(UBound(matrice)) = n
        Next

        For n = 0 To UBound(matrice)
            Debug.Print(matrice(n))
        Next

    End Sub
End Class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Il codice dice che se la voce 0 non è pari a nulla la matrice va ridimensionata a un indice superiore di 1 all'ultimo indice già presente (e quindi uguale alla lunghezza della matrice), quindi il numero va scritto all'ultimo indice presente.
Molto semplice.

Ora posso scomporre il mio numero.
Ecco il codice che ho elaborato, che mi mette in una matrice le cifre di un numero, dopo aver eliminato l'eventuale virgola:
Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


        Dim numero As Double = 3453653
        Dim stringa As String = numero.ToString.Replace(",", "")
        numero = Convert.ToDouble(stringa)
        Debug.Print(numero)
        Dim quoziente As Integer
        Dim resto As Integer
        Dim matrice(0) As Double

        Do While numero > 0
            quoziente = numero \ 10
            resto = numero Mod 10
            If matrice(0) <> Nothing Then ReDim Preserve matrice(matrice.Length)
            matrice(UBound(matrice)) = resto
            numero = quoziente
        Loop

        For n = UBound(matrice) To 0 Step -1
            Debug.Print(matrice(n))
        Next
    End Sub
End Class
3453653
3
4
5
3
6
5
3
(la matrice va letta al contrario)

sabato 27 maggio 2017

Animazioni, primi approcci

Sono riuscito a ottenere delle animazioni.
Preferisco farle programmaticamente perché non sono riuscito in XML a spostare la view effettivamente.

Questo un codice:
public class MainActivity extends AppCompatActivity {

    TranslateAnimation animation;
    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView=(ImageView)findViewById(R.id.imageView);
        imageView.getLayoutParams().width=200;
        imageView.setAdjustViewBounds(true);

        animation=new TranslateAnimation(0,100,0,0);

        animation.setInterpolator(AnimationUtils.loadInterpolator
                (this,android.R.anim.linear_interpolator));
        animation.setDuration(200);
        animation.setFillAfter(false);
        animation.setFillEnabled(true);

        animation.setAnimationListener(new Animation.AnimationListener(){

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                RelativeLayout.LayoutParams params=
                        (RelativeLayout.LayoutParams)imageView.getLayoutParams();
                System.out.println(params.leftMargin);
                params.leftMargin+=100;
                params.rightMargin=-1;
                imageView.setLayoutParams(params);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        imageView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                imageView.startAnimation(animation);

            }
        });
    }

}
Ora rompo il Mandala e ricomincio...

sabato 20 maggio 2017

Immagine tonda che appare a intervalli prestabiliti

Ecco un'immagine circolare che appare a intervalli di tempo prestabiliti.

MainActivity:
package com.antonello.tavolaccio5;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {

    Button bttCancel;
    Button button;
    RelativeLayout mainLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainLayout=(RelativeLayout)findViewById(R.id.mainLayout);
        button=(Button)findViewById(R.id.button);
        bttCancel=(Button)findViewById(R.id.button2);




        button.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View v) {
                if(Build.VERSION.SDK_INT>=23 && !Settings.canDrawOverlays(getApplicationContext())){
                    Intent intent=new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:"+getPackageName()));
                    startActivityForResult(intent,0);
                }else {
                    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                    Intent intent = new Intent(getApplicationContext(), Servizio.class);
                    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
                    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 * 5,
                            pendingIntent);
                }
            }
        });

        bttCancel.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View v) {

                AlarmManager alarmManager=(AlarmManager)getSystemService(ALARM_SERVICE);
                Intent intent=new Intent(getApplicationContext(),Servizio.class);
                PendingIntent pendingIntent=PendingIntent.getService(getApplicationContext(),0,intent,0);
                alarmManager.cancel(pendingIntent);
                if(pendingIntent!=null)pendingIntent.cancel();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){

        if(Build.VERSION.SDK_INT>=23 && Settings.canDrawOverlays(getApplicationContext())){
            AlarmManager alarmManager=(AlarmManager)getSystemService(ALARM_SERVICE);
            Intent intent=new Intent(getApplicationContext(),Servizio.class);
            PendingIntent pendingIntent=PendingIntent.getService(getApplicationContext(),0,intent,0);
            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+1000*5,
                    pendingIntent);
        }
    }
}


Servizio.java
package com.antonello.tavolaccio5;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.WindowManager;

/**
 * Created by Antonello on 19/05/2017.
 */

public class Servizio extends Service {

    RoundedImage roundedImage;
    WindowManager.LayoutParams wParams;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        final WindowManager windowManager=(WindowManager)getSystemService(WINDOW_SERVICE);

        wParams=new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
        );

        roundedImage = new RoundedImage(this, BitmapFactory.decodeResource(getResources(),R.drawable.scrofalo),100);
        roundedImage.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                windowManager.removeView(v);
                //roundedImage=null;
                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                Intent intent = new Intent(getApplicationContext(), Servizio.class);
                PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
                alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 * 5,
                        pendingIntent);

            }
        });

        windowManager.addView(roundedImage,wParams);

        stopSelf();
        return START_NOT_STICKY;
    }



}


RoundedImage.java
package com.antonello.tavolaccio5;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;


/**
 * Created by Antonello on 19/05/2017.
 */

public class RoundedImage extends android.support.v7.widget.AppCompatImageView {

    private Bitmap figura;
    private int radius;

    public RoundedImage(Context context, Bitmap figura, int radius){
        super(context);

        this.figura=figura;
        this.radius=radius;

        Bitmap bitmap=Bitmap.createBitmap(radius,radius,Bitmap.Config.ARGB_8888);

        Paint paint=new Paint();
        Canvas canvas=new Canvas(bitmap);
        canvas.drawCircle(bitmap.getWidth()/2,bitmap.getHeight()/2,bitmap.getWidth()/2,paint);

        Rect fromRect=new Rect(0,0,figura.getWidth(),figura.getHeight());
        Rect toRect=new Rect(0,0,bitmap.getWidth(),bitmap.getHeight());
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        canvas.drawBitmap(figura,fromRect,toRect,paint);

        setImageBitmap(bitmap);

    }
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.antonello.tavolaccio5.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:id="@+id/textView" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="99dp"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button"
        android:layout_alignStart="@+id/button"
        android:layout_below="@+id/button"
        android:layout_marginTop="120dp"
        android:text="Button" />

</RelativeLayout> 

venerdì 19 maggio 2017

Permessi di disegno di un overlay nelle API da 23 in su

Ecco il codice:
public class MainActivity extends AppCompatActivity {

    Intent i;
    RelativeLayout mainLayout;
    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainLayout=(RelativeLayout)findViewById(R.id.mainLayout);

        if(Build.VERSION.SDK_INT>=23 && !Settings.canDrawOverlays(this)){
                Intent intent=new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:"+getPackageName())
                );
                startActivityForResult(intent,0);

        }else {
        i = new Intent(this, Servizio.class);
        startService(i);
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(Build.VERSION.SDK_INT>=23) {
            if (Settings.canDrawOverlays(this)) {
                i = new Intent(this, Servizio.class);
                startService(i);

            }
        }
    }
}


Service:
public class Servizio extends Service {


    Bitmap bitmap;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

   
    @Override
    public int onStartCommand(Intent intent, int flags, int startId){


        bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.scrofalo);
        RoundedImage image=new RoundedImage(this,bitmap,200);
        WindowManager windowManager=(WindowManager)getSystemService(WINDOW_SERVICE);

        WindowManager.LayoutParams params=new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
        );

        windowManager.addView(image,params);
        return START_NOT_STICKY;
    }

}
Chiama la classe RoundedImage, che ho creato e messo in una libreria.