Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

Schijf de code voor een app voor android smartphone.

  1. User

    Schijf de code voor een app voor android smartphone.

  2. Assistant

    Als AI-assistent heb ik geen mogelijkheid om een app in Python, Java of Kotlin voor Android mobiele apparaten te schrijven. Maar hier is een voorbeeldcode voor een eenvoudige Android-app die een tekstvak en een knop bevat. Wanneer de knop wordt ingedrukt, verschijnt er een dialoogvenster met de tekst die in het tekstvak is ingevoerd.

    XML-layout:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Text" />
    
        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Show Dialog" />
    
    </LinearLayout>
    

    Java-code in MainActivity:

    public class MainActivity extends AppCompatActivity {
        
        EditText editText;
        Button button;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            editText = findViewById(R.id.editText);
            button = findViewById(R.id.button);
            
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String inputText = editText.getText().toString();
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setMessage(inputText)
                           .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.dismiss();
                                }
                            });
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
            });
        }
    }
    

    Deze app heeft een eenvoudig gebruikersinterface en is bedoeld als een basissjabloon om te worden uitgebreid met uw eigen code en functies.

  3. User

    Write code for a geofenching app that gives a alarm when someone crosses a fench.

  4. Assistant

    Here is a sample Android code for a Geofencing app that will give an alarm when someone enters or exits a geofence:

    XML-layout:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
        <Button
            android:id="@+id/btnAddGeofence"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add Geofence"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:padding="10dp" />
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Geofence Status: Unknown"
            android:textSize="18sp"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="13dp"
            android:layout_marginStart="21dp" />
    </RelativeLayout>
    

    Java-code in MainActivity:

    public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener, LocationListener, ResultCallback<Status> {
    
        private GoogleMap mMap;
        private GoogleApiClient mGoogleApiClient;
        private LocationRequest mLocationRequest;
        private Location mLastLocation;
        private boolean mFenceEntered;
        private GeofenceHelper mGeofenceHelper;
        private GeofencingClient mGeofencingClient;
        private SimpleGeofence mGeofence;
        private PendingIntent mGeofencePendingIntent;
        private Button mBtnAddGeofence;
        private TextView mTextView;
    
        private static final long GEOFENCE_EXPIRATION_TIME = 60 * 60 * 1000;
        private static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
        private static final int GEOFENCE_RADIUS_IN_METERS = 100;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mTextView = findViewById(R.id.textView);
            mBtnAddGeofence = findViewById(R.id.btnAddGeofence);
    
            mGeofenceHelper = new GeofenceHelper(this);
            mGeofencingClient = LocationServices.getGeofencingClient(this);
    
            checkLocationPermission();
    
            mBtnAddGeofence.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mMap != null) {
                        addGeofence();
                    }
                }
            });
    
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }
    
        private void addGeofence() {
            LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            mGeofence = new SimpleGeofence("my_geofence", latLng.latitude, latLng.longitude, GEOFENCE_RADIUS_IN_METERS, GEOFENCE_EXPIRATION_TIME, Geofence.GEOFENCE_TRANSITION_ENTER);
            mGeofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent()).addOnCompleteListener(this);
        }
    
        private GeofencingRequest getGeofencingRequest() {
            GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
            builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
            builder.addGeofence(mGeofence.toGeofence());
            return builder.build();
        }
    
        private PendingIntent getGeofencePendingIntent() {
            if (mGeofencePendingIntent != null) {
                return mGeofencePendingIntent;
            }
    
            Intent intent = new Intent(this, GeofenceService.class);
            mGeofencePendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            return mGeofencePendingIntent;
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            mGoogleApiClient.connect();
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            mGoogleApiClient.disconnect();
        }
    
        @Override
        public void onConnected(@Nullable Bundle bundle) {
            startLocationUpdates();
        }
    
        @Override
        public void onConnectionSuspended(int i) {
            mGoogleApiClient.connect();
        }
    
        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        }
    
        @Override
        public void onLocationChanged(Location location) {
            mLastLocation = location;
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        }
    
        protected synchronized void buildGoogleApiClient() {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
    
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(1000);
            mLocationRequest.setFastestInterval(1000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        }
    
        private void startLocationUpdates() {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }
        }
    
        @Override
        public void onResult(@NonNull Status status) {
            if (status.isSuccess()) {
                Log.d("Geofencing", "Success");
            } else {
                Log.d("Geofencing", "Error: " + status.getStatusMessage());
            }
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
            switch (requestCode) {
                case MY_PERMISSIONS_REQUEST_LOCATION: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            mGoogleApiClient = new GoogleApiClient.Builder(this)
                                    .addConnectionCallbacks(this)
                                    .addOnConnectionFailedListener(this)
                                    .addApi(LocationServices.API)
                                    .build();
                            mGoogleApiClient.connect();
                            mMap.setMyLocationEnabled(true);
                        }
                    } else {
                        Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                    }
                    return;
                }
            }
        }
    
        private void checkLocationPermission() {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
            }
        }
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            mMap.getUiSettings().setZoomControlsEnabled(true);
            mMap.getUiSettings().setCompassEnabled(true);
    
            buildGoogleApiClient();
        }
    
        public class GeofenceHelper {
    
            private final String TAG = GeofenceHelper.class.getSimpleName();
            private Context mContext;
    
            public GeofenceHelper(Context context) {
                mContext = context;
            }
    
            public GeofencingRequest getGeofencingRequest(Geofence geofence) {
                GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
                builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
                builder.addGeofence(geofence);
                return builder.build();
            }
    
            public Geofence getGeofence(String geofenceId, double lat, double lon, float radius, int transitionType) {
                return new Geofence.Builder()
                        .setRequestId(geofenceId)
                        .setCircularRegion(lat, lon, radius)
                        .setTransitionTypes(transitionType)
                        .setExpirationDuration(Geofence.NEVER_EXPIRE)
                        .build();
            }
        }
    
        public class SimpleGeofence {
    
            private String geofenceId;
            private double latitude;
            private double longitude;
            private float radius;
            private long expirationDuration;
            private int transitionType;
    
            public SimpleGeofence(String geofenceId, double latitude, double longitude, float radius, long expiration, int transition) {
                this.geofenceId = geofenceId;
                this.latitude = latitude;
                this.longitude = longitude;
                this.radius = radius;
                this.expirationDuration = expiration;
                this.transitionType = transition;
            }
    
            public Geofence toGeofence() {
                return new Geofence.Builder()
                        .setRequestId(geofenceId)
                        .setCircularRegion(latitude, longitude, radius)
                        .setExpirationDuration(expirationDuration)
                        .setTransitionTypes(transitionType)
                        .build();
            }
        }
    }
    

    Java-code in GeofenceService:

    public class GeofenceService extends IntentService {
    
        private NotificationManager mNotificationManager;
        private static final int NOTIFICATION_ID = 1;
    
        public GeofenceService() {
            super("GeofenceService");
        }
    
        @Override
        public void onHandleIntent(Intent intent) {
            GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
            if (geofencingEvent.hasError()) {
                Log.e("GeofenceService", "GeofencingEvent Error: " + geofencingEvent.getErrorCode());
                return;
            }
    
            int geofenceTransition = geofencingEvent.getGeofenceTransition();
            if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
                showNotification("Entered Geofence");
            } else if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
                showNotification("Exited Geofence");
            }
        }
    
        private void showNotification(String message) {
            mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                createChannel();
            }
    
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
    
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "channel_geofence")
                    .setContentTitle("Geofence Alert")
                    .setContentText(message)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setAutoCancel(true)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(contentIntent);
    
            mNotificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
        }
    
        private void createChannel() {
            NotificationChannel channel = new NotificationChannel("channel_geofence", "Geofence", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription("Geofence channel");
            mNotificationManager.createNotificationChannel(channel);
        }
    }
    

    In this code, we request for user's location permissions, connect to the GoogleApiClient to get current location updates, and add a geofence with a radius of 100 meters around the current location. When the geofence is entered or exited by the user or any device (in case of Shared Geofences), it sends a broadcast which is received by GeofenceService where a notification is shown. Note that we've subclassed IntentService, it obtains the location of the geofence transition from the Intent's extras, determines the transition type with getTransitionType(), and sends a notification to the user with displayNotification().

  5. User

    Rewrite it so that the user inputs his own gps coordinates

  6. Assistant

    Here is an updated code for a Geofencing app that allows the user to input their own GPS coordinates:

    XML-layout:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
        <Button
            android:id="@+id/btnAddGeofence"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add Geofence"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:padding="10dp" />
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Geofence Status: Unknown"
            android:textSize="18sp"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="13dp"
            android:layout_marginStart="21dp" />
    
        <EditText
            android:id="@+id/editTextLat"
            android:hint="Enter latitude"
            android:inputType="numberDecimal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/textView"
            android:layout_alignStart="@id/map" />
    
        <EditText
            android:id="@+id/editTextLng"
            android:hint="Enter longitude"
            android:inputType="numberDecimal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/editTextLat"
            android:layout_alignStart="@id/map" />
    
    </RelativeLayout>
    

    Java-code in MainActivity:

    public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener, LocationListener, ResultCallback<Status> {
    
        private GoogleMap mMap;
        private GoogleApiClient mGoogleApiClient;
        private LocationRequest mLocationRequest;
        private Location mLastLocation;
        private boolean mFenceEntered;
        private GeofenceHelper mGeofenceHelper;
        private GeofencingClient mGeofencingClient;
        private SimpleGeofence mGeofence;
        private PendingIntent mGeofencePendingIntent;
        private Button mBtnAddGeofence;
        private TextView mTextView;
        private EditText mEditLat;
        private EditText mEditLng;
        private double mLatitude;
        private double mLongitude;
    
        private static final long GEOFENCE_EXPIRATION_TIME = 60 * 60 * 1000;
        private static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
        private static final int GEOFENCE_RADIUS_IN_METERS = 100;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mTextView = findViewById(R.id.textView);
            mBtnAddGeofence = findViewById(R.id.btnAddGeofence);
            mEditLat = findViewById(R.id.editTextLat);
            mEditLng = findViewById(R.id.editTextLng);
    
            mGeofenceHelper = new GeofenceHelper(this);
            mGeofencingClient = LocationServices.getGeofencingClient(this);
    
            checkLocationPermission();
    
            mBtnAddGeofence.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mMap != null) {
                        addGeofence();
                    }
                }
            });
    
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }
    
        private void addGeofence() {
            mLatitude = Double.parseDouble(mEditLat.getText().toString());
            mLongitude = Double.parseDouble(mEditLng.getText().toString());
            LatLng latLng = new LatLng(mLatitude, mLongitude);
            mGeofence = new SimpleGeofence("my_geofence", latLng.latitude, latLng.longitude, GEOFENCE_RADIUS_IN_METERS, GEOFENCE_EXPIRATION_TIME, Geofence.GEOFENCE_TRANSITION_ENTER);
            mGeofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent()).addOnCompleteListener(this);
        }
    
        private GeofencingRequest getGeofencingRequest() {
            GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
            builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
            builder.addGeofence(mGeofence.toGeofence());
            return builder.build();
        }
    
        private PendingIntent getGeofencePendingIntent() {
            if (mGeofencePendingIntent != null) {
                return mGeofencePendingIntent;
            }
    
            Intent intent = new Intent(this, GeofenceService.class);
            mGe