public class MyService extends Service { //create binder private final IBinder myBinder = new MyBinder(); //set state to 0 private int state = 0; //set activity to null to avoid exception private Activity myActivity = null; //set two views for our text view private View light1, light2; //hold sequence of light private State[] myStates; //set mode to 0 private int mode = 0;
//since when services is created, he run it's default c'tor, we override it with our c'tor public MyService() { //get the first sequence myStates = setPolice(); //create new thread, which run separated from our main thread new Thread(new Runnable() { @Override public void run() { //will run until we set the activity to nu while (true) { //get state state = (state + 1) % myStates.length; Log.d("TESTING", "state=" + state); if (myActivity != null) { //since we are inside a thread, and we can not access to other thread, we run it on ui thre myActivity.runOnUiThread(new Runnable() {
@Override public void run() { //set the colour light1.setBackgroundColor(myStates[state].color1); light2.setBackgroundColor(myStates[state].color2); } }); } try { //make thread some sleep, for biker effect Thread.sleep(myStates[state].delay); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); }
//our sequence builders public State[] setPolice() { State[] police = new State[12]; police[0] = new State(Color.RED, Color.BLACK, 120); police[1] = new State(Color.BLACK, Color.BLACK, 50); police[2] = new State(Color.RED, Color.BLACK, 120); police[3] = new State(Color.BLACK, Color.BLACK, 50); police[4] = new State(Color.RED, Color.BLACK, 120); police[5] = new State(Color.BLACK, Color.BLACK, 70);
police[6] = new State(Color.BLACK, Color.BLUE, 120); police[7] = new State(Color.BLACK, Color.BLACK, 50); police[8] = new State(Color.BLACK, Color.BLUE, 120); police[9] = new State(Color.BLACK, Color.BLACK, 50); police[10] = new State(Color.BLACK, Color.BLUE, 120); police[11] = new State(Color.BLACK, Color.BLACK, 70);
return police; }
public State[] setPolice1() { State[] police = new State[12]; police[0] = new State(Color.BLUE, Color.BLACK, 120); police[1] = new State(Color.BLACK, Color.BLACK, 50); police[2] = new State(Color.BLUE, Color.BLACK, 120); police[3] = new State(Color.BLACK, Color.BLACK, 50); police[4] = new State(Color.BLUE, Color.BLACK, 120); police[5] = new State(Color.BLACK, Color.BLACK, 70);
police[6] = new State(Color.BLACK, Color.BLUE, 120); police[7] = new State(Color.BLACK, Color.BLACK, 50); police[8] = new State(Color.BLACK, Color.BLUE, 120); police[9] = new State(Color.BLACK, Color.BLACK, 50); police[10] = new State(Color.BLACK, Color.BLUE, 120); police[11] = new State(Color.BLACK, Color.BLACK, 70);
return police; }
public State[] setFire() { State[] fire = new State[12]; fire[0] = new State(Color.RED, Color.BLACK, 120); fire[1] = new State(Color.BLACK, Color.BLACK, 50); fire[2] = new State(Color.RED, Color.BLACK, 120); fire[3] = new State(Color.BLACK, Color.BLACK, 50); fire[4] = new State(Color.RED, Color.BLACK, 120); fire[5] = new State(Color.BLACK, Color.BLACK, 70);
fire[6] = new State(Color.BLACK, Color.RED, 120); fire[7] = new State(Color.BLACK, Color.BLACK, 50); fire[8] = new State(Color.BLACK, Color.RED, 120); fire[9] = new State(Color.BLACK, Color.BLACK, 50); fire[10] = new State(Color.BLACK, Color.RED, 120); fire[11] = new State(Color.BLACK, Color.BLACK, 70);
return fire; }
//handle our binder @Nullable @Override
public IBinder onBind(Intent intent) { return myBinder; }
//we use inner class for less coding public class MyBinder extends Binder { public MyService getService() { return MyService.this; }
}
//return activity public Activity getActivity() { return myActivity; }
//set pointers to activity xml, which we provide from main activity public void setActivity(Activity activity, View light1, View light2) { this.myActivity = activity; this.light1 = light1; this.light2 = light2; }
//clear activity and pointers for garbage collector public void setNoActivity() { this.myActivity = null; this.light1 = null; this.light2 = null; }
//inner class for better sequance builder private class State { int color1; int color2; int delay;
public State(int color1, int color2, int delay) { this.color1 = color1; this.color2 = color2; this.delay = delay; } }
//changeing modes.... public void changeMode() { mode = (mode + 1) % 3; switch (mode) { case 0: myStates = setPolice(); break; case 1: myStates = setFire(); break; case 2: myStates = setPolice1(); break; } } }
//we use onclick & onLonclick listener for implementing the methods here public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener { //declare of our bounded services private MyService myService; //a boolean which indicates if the service is bounded or not private boolean isBound = false;
private void setPointer() { //since we need only declare of click events, we don't need to create an instanc findViewById(R.id.llyBack).setOnClickListener(this); findViewById(R.id.llyBack).setOnLongClickListener(this); }
@Override public void onClick(View v) { //if service is null, we will create it, else, we set null so garbage collector will clean the memory if (myService.getActivity() == null) { //we send here the activity, and pointers to our layout elements myService.setActivity(this, findViewById(R.id.tvLight1), findViewById(R.id.tvLight2)); } else { myService.setNoActivity(); } }
@Override protected void onStart() { //when activity is started, bound the service super.onStart(); bind(); }
private void bind() { // Bind to LocalService Intent intent = new Intent(this, MyService.class); //create the service automatic by the connection and send the intent bindService(intent, myConnection, Context.BIND_AUTO_CREATE); }
/** * Defines callbacks for service binding, passed to bindService() */ private ServiceConnection myConnection = new ServiceConnection() {
@Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to MyService, cast the IBinder and get MyService instance MyService.MyBinder myBinder = (MyService.MyBinder) service; myService = myBinder.getService(); isBound = true; }
private void setPointer() { this.context=this; this.btnSnack=findViewById(R.id.btnSnackBar); this.btnNotAdv=findViewById(R.id.btnSimpleNotAdv); btnSnack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String message = "sale on red pills"; int myDuration = 5000; Snackbar.make(v,message,Snackbar.LENGTH_LONG) //create the snack bar .setAction("got ya", new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "red pill vendor on his way to you", Toast.LENGTH_SHORT).show(); } }) .setDuration(myDuration) .setActionTextColor(Color.GREEN) .show(); } }); btnNotAdv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createNotificationWithAction(70,R.drawable.pill,"red pill party", "order now"); } }); }
private void createNotificationWithAction(int nId, int icon, String title, String msg) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext(), "notify_001"); Intent ii = new Intent(context.getApplicationContext(), buf.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, ii, 0);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle(); bigText.bigText("hadouken"); bigText.setBigContentTitle("Today's red pill"); bigText.setSummaryText("Text in detail");
public class Eng extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.e("buf", "onReceive: all you need is Buf!!" ); } }
public class rus extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.e("rus", "onReceive: HE TPOHb 3APA3A !!!!" ); } }
public class MainActivity extends AppCompatActivity { Context context; private String myLng="ar"; // all receiver classes set to this channel will activate public static Button btnDynamic; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setPointer(); setRecivers(); }
private void setRecivers() { registerReceiver(new Eng(), new IntentFilter("en")); // broadcast channel = en registerReceiver(new heb(), new IntentFilter("he")); registerReceiver(new rus(), new IntentFilter("ru")); registerReceiver(new Arabic(), new IntentFilter("ar")); }
sendBroadcast(new Intent(myLng)); // activate all receivers set to myLng channel } }); btnDynamic=findViewById(R.id.btnDynamic); } }
BroadcastReceivers
_________________ MB over and out
Moti Barski super
Posts : 498 Join date : 2011-08-02
Subject: android studio backendless sereis login and register user Sun Aug 05, 2018 7:32 pm
backendless is a 3rd party service that enables you to perform server style jutsus such as login, registration, use DBs, send push notifications and more
in the main on creat from there I added the above prev code that registers and logs in a user.
key note : in the BE site click : help, documentation to see more of the available jutsus/
_________________ MB over and out
Moti Barski super
Posts : 498 Join date : 2011-08-02
Subject: android backendless database Mon Aug 06, 2018 7:54 pm
in the data tab you can see the registered users and manage them, also to create a new DB table : + to create new DB table , new (in schema tab ) to add columns.
dl the DB java class at :
code generation tab, java classes for defined data tables, dl and take out the dbname.java and add it to the project
in this example I created a dic table with keyer and content string columns.
private void register() { BackendlessUser user = new BackendlessUser(); user.setProperty("email",txtUser.getText().toString()); String userName[] = txtUser.getText().toString().split("@"); user.setProperty("name",userName[0]); user.setPassword(txtPass.getText().toString());
Backendless.UserService.register(user, new AsyncCallback<BackendlessUser>() { @Override public void handleResponse(BackendlessUser response) { pb.setVisibility(View.INVISIBLE); Toast.makeText(context, "all is OK", Toast.LENGTH_LONG).show(); }
//region region name stuff (code or comments) //endregion
and so the stuff is conveniently collapsable
Open Region Shortcut: control+shift+ (plus +) Close Region Shortcut: control+shift+ (minus -)
_________________ MB over and out
Admin Admin
Posts : 140 Join date : 2011-08-01
Subject: backendless android studio almighty push notifications with action no jutsu Mon Aug 13, 2018 10:50 am
1 Gradle Setup If your project uses Gradle, you can add the following configuration to your build.gradle file: dependencies { implementation group: 'com.backendless', name: 'backendless', version: '5.0.+'
// required for real-time database and real-time messaging implementation ('io.socket:socket.io-client:1.0.0') { // excluding org.json which is provided by Android exclude group: 'org.json', module: 'json' } }
key notes for main java : // from develop.backendless.com dashboard (home tab)Application ID p1, secret key = Android API key p2 // see where you get these key vars after java classes in this tutorial // respective vars parameters: Backendless.initApp(this, "p1", "p2");
// p3 = sender id you got from firebase Backendless.Messaging.registerDevice("p3","hadouken", new AsyncCallback<Void>() {
private void createNotification(int nId, int icon, String msg, String title, Context context) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext(), "notify_001"); Intent ii = new Intent(context.getApplicationContext(), buf.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, ii, 0);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle(); bigText.bigText(msg); bigText.setBigContentTitle(msg); bigText.setSummaryText("Text in detail");
public class MyPushReceiver extends BackendlessBroadcastReceiver { @Override public Class<? extends BackendlessPushService> getServiceClass() { return MyPushService.class; } }
console firebase console.firebase.google.com add project, cog wheel, project settings, cloud messaging save sender key, server key. go to backendless, manage tab, app settings, mobile settings (scroll down) android, add keys paste server key, check all channelsm save
key note : in the manifest notice : android:permission="android.permission.BIND_JOB_SERVICE" and "android.permission.BIND_JOB_SERVICE"
running the app at this stage you should see the hadouken channel at backendless messaging tab under channels
to send messages : backendless, messaging, channels, +
business logic tab, API service +, codeless, new service, give it a name sendPush
REST operation : GET methode parameters : channel String title String msg String save.
click the now appeared service name under deployed services still in the business logic tab. click edit, click messaging API, drag publish push notification into API service "yourServiceName", and drag the methode Arguments into the corresponding slots in said publish push notification block. deploy, continue, done.
to send messages : at the right side of the just build API you will have the url for sending messages. go to that url but add methode params at the end of the url : ?channel=channelName&title=title&msg=message
as a device works the app a channel will be added at backendless, messages tab you can send push notis from there to selected channels or from business logic tab.
msg at : public boolean onMessage( Context context, Intent intent ) from its java class
public class Fragment1 extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //return my view as inflated view to the fragment return inflater.inflate(R.layout.activity_main, container, false); } }
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //we don't need to set view, our fragment will handle it //setContentView(R.layout.activity_main);
//Create instance of Fragment manager to handle our fragments FragmentManager fm = getFragmentManager(); //create instance of Fragment transaction to handle fragment replace and animation FragmentTransaction ft = fm.beginTransaction();
int displayMode = getResources().getConfiguration().orientation;
if (displayMode==1) { //create instance of first fragment Fragment1 f1 = new Fragment1(); //change content of the whole screen to our new fragment ft.replace(android.R.id.content,f1); } else { //create instance of second fragment Fragment2 f2 = new Fragment2(); //change content of the entire screen to our new fragment ft.replace(android.R.id.content,f2); } //choose animation ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); //commit all changes to screen fragments ft.commit(); } }
run the app and flip the device :nice:
_________________ MB over and out
Last edited by Moti Barski on Mon Aug 20, 2018 2:33 pm; edited 1 time in total
Moti Barski super
Posts : 498 Join date : 2011-08-02
Subject: android studio dynamic fragment Mon Aug 20, 2018 11:28 am
public class Frag2 extends Fragment { public ListView vicList; String victimName; List<String> myList; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { //inflate view for our fragment View rootView = inflater.inflate(R.layout.frag2, container, false); //pointer to our list view vicList = rootView.findViewById(R.id.victimList); //create adapter, getActivity()-> return the context of the calling activity VictimAdapter adapter = new VictimAdapter(createList(), getActivity()); //attach the adapter vicList.setAdapter(adapter); vicList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { victimName=myList.get(position); } }); return rootView; }
public class Frag3 extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.frag3,container,false); } public Frag3(){} }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //create fragment manager fm = getFragmentManager(); //create fragment transaction //ft = fm.beginTransaction(); fg2=new Frag2(); findViewById(R.id.btnFrag1).setOnClickListener(this); findViewById(R.id.btnFrag2).setOnClickListener(this); findViewById(R.id.btnFrag3).setOnClickListener(this); findViewById(R.id.nextScreen).setOnClickListener(this); }
@Override public void onClick(View v) { Log.e("frag", "onClick: me here" ); switch (v.getId()) { case R.id.btnFrag1: setMyFrag(new Frag1()); break; case R.id.btnFrag2: setMyFrag(fg2); break; case R.id.btnFrag3: setMyFrag(new Frag3()); break; case R.id.nextScreen: startActivity(new Intent(this,Main2Activity.class)); break; } }
private void setMyFrag(Fragment myFrag) { //load the specific fragment ft = fm.beginTransaction(); //set transition animation ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); //replace the fragment ft.replace(R.id.container,myFrag); //commit the change ft.commit(); } }
Subject: android studio GPS google map get coordinates of your location and street name no jutsu Tue Aug 21, 2018 9:35 pm
when you open a new project choose google map instead of empty activity in the now opened google_maps_api.xml the first link will get you an app key from google which you paste at google_maps_api.xml at <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">app key here</string>
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener, View.OnClickListener { final int ACCESS_FINE_LOCATION =1; final int ACCESS_COARSE_LOCATION =1; private GoogleMap mMap; Location myLocation; LocationManager locationManager; final LatLng PRIPYAT = new LatLng(51.405556, 30.056944); final LatLng HOME = PRIPYAT; final LatLng WORK = new LatLng(51.261926,30.236045); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); setPointer(); }
private void setPointer() { //get location service (system service) getGPSPermission(); // ask for permission by code for API 6 and above locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); //set location updates if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } locationManager.requestLocationUpdates(getCriteria(), 10, 50, this); //locationManager.getLastKnownLocation(getCriteria()); //get the last known location findViewById(R.id.btnHome).setOnClickListener(this); // btn listeners findViewById(R.id.btnWork).setOnClickListener(this); }
private void getGPSPermission() { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this) .setTitle("gps Permission needed to use gps jutsu") .setMessage("This permission is needed because the app needs to be able to use maps") .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION); } }) .setNegativeButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create().show();
} else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION);
}
}
public String getCriteria() { Criteria criteria = new Criteria(); //indicates criteria for selction on location provider criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setAltitudeRequired(true); criteria.setBearingRequired(true);
//get our best provider String bestProvicer = locationManager.getBestProvider(criteria,true);// if false best GPS service will be wokend and used // if true only the gps wifi or gprs that are lit return bestProvicer; }
@Override public void onMapReady(GoogleMap googleMap) { // this is a call back methode it fires up with the service mMap = googleMap;
// Add a marker in Sydney and move the camera //LatLng hackerU = new LatLng(32.0831646, 34.8032984); LatLng home=HOME;
@Override public void onLocationChanged(Location location) { // fires up when device phisically moves this.myLocation=location; LatLng myCurrentLocation = new LatLng(myLocation.getLatitude(),myLocation.getLongitude()); //mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myCurrentLocation,17.4f));
}
@Override public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override public void onProviderEnabled(String provider) {
}
@Override public void onProviderDisabled(String provider) {
}
@Override public void onClick(View v) { switch (v.getId()) { case R.id.btnHome: //it's coming home, it's coming home mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(HOME,17.4f)); //Toast.makeText(this, HOME.latitude+","+HOME.longitude, Toast.LENGTH_SHORT).show(); motiToast(HOME); break; case R.id.btnWork: //let's got to work (not) mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(WORK,17.4f)); //Toast.makeText(this, WORK.latitude+","+WORK.longitude, Toast.LENGTH_SHORT).show(); motiToast(WORK); break; } }
public String motiToast(LatLng myLocation) { // convert gps coordinates into place name String returnString = ""; Geocoder gcdLocale = new Geocoder(this); //new Geocoder(this, Locale.ENGLISH) List<Address> localeAdd = null; try { localeAdd = gcdLocale.getFromLocation(myLocation.latitude,myLocation.longitude,1); } catch (IOException e) { e.printStackTrace(); } //if localeAdd is null (false) get out of the function (method) assert localeAdd != null; if (localeAdd.size()>0) { String myAdd = localeAdd.get(0).getAddressLine(0); Toast.makeText(this, myAdd, Toast.LENGTH_LONG).show(); returnString=myAdd; } return returnString; }
at MapsActivity.java change onLocationChanged to :
Code:
public void onLocationChanged(Location location) { // fires up when device phisically moves this.myLocation=location; LatLng myCurrentLocation = new LatLng(myLocation.getLatitude(),myLocation.getLongitude()); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myCurrentLocation,17.4f)); findViewById(R.id.lastLocation).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { motiToast(new LatLng(myLocation.getLatitude(),myLocation.getLongitude())); } });
}
clicking the btn last location will toast where you at.
_________________ MB over and out
Moti Barski super
Posts : 498 Join date : 2011-08-02
Subject: android studio classic animation walkthrough Sat Aug 25, 2018 8:02 am
go to : https://ezgif.com/split and split a gif image into frames and past them as .png into drawable dir (not v-24) in this case it was : frame1.png to frame70.png
right click drawable folder, new drawable resource file : walking_moti.xml
public class MainActivity extends AppCompatActivity implements Animation.AnimationListener{ //create the folder anim under res folder ImageView motiImage; Context context; Animation animation;
Subject: maximize triplet boost magic grimoire Sat Aug 25, 2018 12:51 pm
body of effulgent beryl sorry, but I"ll have you wait a bit before we engage. fly, bless of magic caster, infinity wall, magic ward holy. life essence, greater full potential, freedom, false data life. see through, paranormal intuition, greater resistance, mantle of chaos. Indomitability, sensor boost, greater luck, magic boost, draconic power. Greater hardening. heavenly aura, absorption, penetrate up, greater magic shield. mana essence, triplet maximize magic, explode mine, triplet magic, greater magic seal. triplet maximize boosted magic, magic arrow
_________________ MB over and out
Moti Barski super
Posts : 498 Join date : 2011-08-02
Subject: android studio category screen using expandablerelativelayout Mon Aug 27, 2018 1:21 pm
add : implementation 'com.github.aakira:expandable-layout:1.4.1@aar' to build.gradle(module:app) so it looks like :
basicly you put linear layout in com.github.aakira.expandablelayout.ExpandableRelativeLayout in ScrollView(which replaces the default layout when opening an empty activity project)
private TextureView textureView; private CameraDevice cameraDevice; private CaptureRequest.Builder previewBuilder; private CameraCaptureSession previewSession; Button getpicture; final int CAM =1; private void getCameraPermission() { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
new AlertDialog.Builder(this) .setTitle("Permission needed") .setMessage("This permission is needed because the app needs to be able to send SMSes") .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, CAM); } }) .setNegativeButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create().show();
} else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAM);
}}
private static final SparseIntArray ORIENTATIONS=new SparseIntArray();
cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() { @Override public void onConfigured(CameraCaptureSession session) {
//@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_main, menu); // 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. // int id = item.getItemId(); // // //noinspection SimplifiableIfStatement // if (id == R.id.action_settings) { // return true; // } // // return super.onOptionsItemSelected(item); // }
private static File getOutputMediaFile() { File mediaStorageDir = new File( Environment .getExternalStorageDirectory(), "MyCameraApp"); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("MyCameraApp", "failed to create directory"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") .format(new Date()); File mediaFile; mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile; } }
study study study ! :sharingan:
_________________ MB over and out
Last edited by Moti Barski on Tue Feb 19, 2019 8:25 pm; edited 1 time in total
Moti Barski super
Posts : 498 Join date : 2011-08-02
Subject: android studio get picture from camera intent or image gallery manually from the user Sun Sep 02, 2018 7:16 pm
public class MainActivity extends AppCompatActivity {
//finals //take picture request code final private int CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE=1; // permission img from camera final private int CAMERA_SIMPLE_REQUEST = 2; // img from gallerys
//pointer to image view ImageView imgPicture; //pointer to context Context context; //pointer to fileName String fileName;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //calling the set pointer setPointer(); }
private void setPointer() { //get the context this.context=this; //check for camera permission, since camera is privacy violate //we need to ask permission by code from android 6 and above checkForPermissions(); //pointer to camera on screen imgPicture=findViewById(R.id.imgPicture); //set a click listener to our button findViewById(R.id.btnCamera).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //check if user turned off the permission checkForPermissions(); //fire the intent for camera if we have a permission to work if (checkForPermissions()) { //dispatch the image taking intent dispatchTakeImageIntent(); } } }); findViewById(R.id.btnCameraSimple).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dispatchCameraSimple(); } }); } private void dispatchCameraSimple() { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); if (intent.resolveActivity(getPackageManager()) != null) { startActivityForResult(intent, CAMERA_SIMPLE_REQUEST); } } private boolean checkForPermissions() { Log.e("CHK permission", "checkForPermissions: checking permission" ); //we create a list of permission to ask, so we can add more later on. List<String> listPermissionsNeeded = new ArrayList<>(); //check if we have a permission for camera int camPerm = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA); int writePerm = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE); int readPerm = ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE);
//we don't have the permission if (camPerm == PackageManager.PERMISSION_GRANTED && writePerm == PackageManager.PERMISSION_GRANTED && readPerm == PackageManager.PERMISSION_GRANTED) { //we have a permission we can move next return true; } listPermissionsNeeded.add(Manifest.permission.CAMERA); listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE); if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE); } return false; }
//we have a feedback from the user for permission @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //checking if we got a permission result Log.e("camera", "onRequestPermissionsResult: request"); if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.e("Permission", "onRequestPermissionsResult: camera true "); dispatchTakeImageIntent(); } else { //tell the user why we can not take pictures. Toast.makeText(context, "We can not take picture without permission", Toast.LENGTH_SHORT).show(); } }
//we calling system intent of the camera private void dispatchTakeImageIntent() { //to avoid api26+ policy restrictions. StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); //we call the android image capture Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//we creating a filename so we can use it later on and put the picture inside the imageView fileName = Environment.getExternalStorageDirectory() + File.separator + UUID.randomUUID().toString() + ".jpg"; File file = new File(fileName); //we setting a global pointer to the file location Log.e("fileName", "dispatchTakeImageIntent: "+fileName ); //telling the image capture intent what will be the file name of our image intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); //since it can create exception, we surround it with try/catch block to avoid exception and application crash try { //call the intent and wait for result after intent is closed. startActivityForResult(intent, CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE); } catch (Exception e) { Log.e("Intent", "dispatchTakeImageIntent: \n" + e.getLocalizedMessage()); } }
@Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (requestCode == CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE) // finished manual cam capture { try { Log.e("camera", "onActivityResult: "+fileName ); //Get our saved file into a bitmap object: final File file = new File(fileName);
//read the image from the file and convert it to bitmap; Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//get exif data (extra information) from the image so we will know orientation of the image ExifInterface exif = null; try { exif = new ExifInterface(fileName); } catch (IOException e) { e.printStackTrace(); } assert exif != null; int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); //we will rotate the image so we can see it depending on screen rotation. Bitmap bmRotated =rotateImage(myBitmap, orientation); //now we can set the image into the image view that we have imgPicture.setImageBitmap(bmRotated); } catch (Exception e) { //printing the error that we have without crashing the application.... e.printStackTrace(); } }
private Bitmap rotateImage(Bitmap myBitmap, int orientation) { //we create a matrix, so we can put the image on it and just rotate //it will be much faster then copy pixel by pixel Matrix matrix = new Matrix(); //depending on the orientation that we got from the exif, we will rotate //in this sample we will deal with all kind of rotating from api 15 to api 27 switch (orientation) { case ExifInterface.ORIENTATION_NORMAL: //all is o.k no need to rotate, just return the image return myBitmap; case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: //flip the matrix horizontal matrix.setScale(-1, 1); break; case ExifInterface.ORIENTATION_ROTATE_180: //roate the matrix 180 degrees matrix.setRotate(180); break; case ExifInterface.ORIENTATION_FLIP_VERTICAL: //flip the picture vertical matrix.setRotate(180); matrix.postScale(-1, 1); break; case ExifInterface.ORIENTATION_TRANSPOSE: //rotate 90 degrees and flip matrix.setRotate(90); matrix.postScale(-1, 1); break; case ExifInterface.ORIENTATION_ROTATE_90: //rotate 90 degress matrix.setRotate(90); break; case ExifInterface.ORIENTATION_TRANSVERSE: //rotate 90 degrees to other side and flip matrix.setRotate(-90); matrix.postScale(-1, 1); break; case ExifInterface.ORIENTATION_ROTATE_270: //roate 90 degrees to other side matrix.setRotate(-90); break; default: //if we have a case that we don't thought of , just return the picture. return myBitmap; } try { //create an image from our rotated solution Bitmap bmRotated = Bitmap.createBitmap(myBitmap, 0, 0, myBitmap.getWidth(), myBitmap.getHeight(), matrix, true); //recycle the data by calling the garbage collector //in this case, we free memory for big images. myBitmap.recycle(); //return the rotated image return bmRotated; } catch (OutOfMemoryError e) { //if we have memory leak , we need to know about it. e.printStackTrace(); return null; } } }
public class MainActivity extends AppCompatActivity {
//finals //take picture request code final private int CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE=1; // permission img from camera final private int CAMERA_SIMPLE_REQUEST = 2; // img from gallerys private static final int VIDEO_CAPTURE = 101; Uri cameraVideoURI;
//pointer to image view ImageView imgPicture; //pointer to context Context context; //pointer to fileName String fileName;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //calling the set pointer setPointer(); }
private void setPointer() { //get the context this.context=this; //check for camera permission, since camera is privacy violate //we need to ask permission by code from android 6 and above checkForPermissions(); //pointer to camera on screen imgPicture=findViewById(R.id.imgPicture); //set a click listener to our button findViewById(R.id.btnCamera).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //check if user turned off the permission checkForPermissions(); //fire the intent for camera if we have a permission to work if (checkForPermissions()) { //dispatch the image taking intent dispatchTakeImageIntent(); } } }); findViewById(R.id.btnCameraSimple).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dispatchCameraSimple(); } }); findViewById(R.id.btnVideo).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
startRecordingVideo(); } }); } public void startRecordingVideo() { String fileName = "captureTemp.mp4"; //create new values object ContentValues values = new ContentValues(); //insert file name as the title values.put(MediaStore.Video.Media.TITLE, fileName); //create uri with values cameraVideoURI = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); //put camera file name uri intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraVideoURI); //set camera video quality intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); //set the maximum video size intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT,5000); //start activity for result , the result will be on method onActivityResult startActivityForResult(intent, VIDEO_CAPTURE); // if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) { // Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); // File mediaFile = new File( // Environment.getExternalStorageDirectory().getAbsolutePath() + "/myvideo.mp4"); // videoUri = Uri.fromFile(mediaFile); // intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri); // startActivityForResult(intent, VIDEO_CAPTURE); // } else { // Toast.makeText(this, "No camera on device", Toast.LENGTH_LONG).show(); // } } private void dispatchCameraSimple() { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); if (intent.resolveActivity(getPackageManager()) != null) { startActivityForResult(intent, CAMERA_SIMPLE_REQUEST); } } private boolean checkForPermissions() { Log.e("CHK permission", "checkForPermissions: checking permission" ); //we create a list of permission to ask, so we can add more later on. List<String> listPermissionsNeeded = new ArrayList<>(); //check if we have a permission for camera int camPerm = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA); int writePerm = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE); int readPerm = ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE);
//we don't have the permission if (camPerm == PackageManager.PERMISSION_GRANTED && writePerm == PackageManager.PERMISSION_GRANTED && readPerm == PackageManager.PERMISSION_GRANTED) { //we have a permission we can move next return true; } listPermissionsNeeded.add(Manifest.permission.CAMERA); listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE); if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE); } return false; }
//we have a feedback from the user for permission @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //checking if we got a permission result Log.e("camera", "onRequestPermissionsResult: request"); if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.e("Permission", "onRequestPermissionsResult: camera true "); dispatchTakeImageIntent(); } else { //tell the user why we can not take pictures. Toast.makeText(context, "We can not take picture without permission", Toast.LENGTH_SHORT).show(); } }
//we calling system intent of the camera private void dispatchTakeImageIntent() { //to avoid api26+ policy restrictions. StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); //we call the android image capture Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//we creating a filename so we can use it later on and put the picture inside the imageView fileName = Environment.getExternalStorageDirectory() + File.separator + UUID.randomUUID().toString() + ".jpg"; File file = new File(fileName); //we setting a global pointer to the file location Log.e("fileName", "dispatchTakeImageIntent: "+fileName ); //telling the image capture intent what will be the file name of our image intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); //since it can create exception, we surround it with try/catch block to avoid exception and application crash try { //call the intent and wait for result after intent is closed. startActivityForResult(intent, CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE); } catch (Exception e) { Log.e("Intent", "dispatchTakeImageIntent: \n" + e.getLocalizedMessage()); } }
@Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (requestCode == CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE) // finished manual cam capture { try { Log.e("camera", "onActivityResult: "+fileName ); //Get our saved file into a bitmap object: final File file = new File(fileName);
//read the image from the file and convert it to bitmap; Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//get exif data (extra information) from the image so we will know orientation of the image ExifInterface exif = null; try { exif = new ExifInterface(fileName); } catch (IOException e) { e.printStackTrace(); } assert exif != null; int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); //we will rotate the image so we can see it depending on screen rotation. Bitmap bmRotated =rotateImage(myBitmap, orientation); //now we can set the image into the image view that we have imgPicture.setImageBitmap(bmRotated); } catch (Exception e) { //printing the error that we have without crashing the application.... e.printStackTrace(); } }
private Bitmap rotateImage(Bitmap myBitmap, int orientation) { //we create a matrix, so we can put the image on it and just rotate //it will be much faster then copy pixel by pixel Matrix matrix = new Matrix(); //depending on the orientation that we got from the exif, we will rotate //in this sample we will deal with all kind of rotating from api 15 to api 27 switch (orientation) { case ExifInterface.ORIENTATION_NORMAL: //all is o.k no need to rotate, just return the image return myBitmap; case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: //flip the matrix horizontal matrix.setScale(-1, 1); break; case ExifInterface.ORIENTATION_ROTATE_180: //roate the matrix 180 degrees matrix.setRotate(180); break; case ExifInterface.ORIENTATION_FLIP_VERTICAL: //flip the picture vertical matrix.setRotate(180); matrix.postScale(-1, 1); break; case ExifInterface.ORIENTATION_TRANSPOSE: //rotate 90 degrees and flip matrix.setRotate(90); matrix.postScale(-1, 1); break; case ExifInterface.ORIENTATION_ROTATE_90: //rotate 90 degress matrix.setRotate(90); break; case ExifInterface.ORIENTATION_TRANSVERSE: //rotate 90 degrees to other side and flip matrix.setRotate(-90); matrix.postScale(-1, 1); break; case ExifInterface.ORIENTATION_ROTATE_270: //roate 90 degrees to other side matrix.setRotate(-90); break; default: //if we have a case that we don't thought of , just return the picture. return myBitmap; } try { //create an image from our rotated solution Bitmap bmRotated = Bitmap.createBitmap(myBitmap, 0, 0, myBitmap.getWidth(), myBitmap.getHeight(), matrix, true); //recycle the data by calling the garbage collector //in this case, we free memory for big images. myBitmap.recycle(); //return the rotated image return bmRotated; } catch (OutOfMemoryError e) { //if we have memory leak , we need to know about it. e.printStackTrace(); return null; } } }
global vars : private static final int VIDEO_CAPTURE = 101; Uri cameraVideoURI; were added
+ btnVideo).setOnClickListener
+ startRecordingVideo() methode + at onActivityResult, :
Code:
if (requestCode == VIDEO_CAPTURE) { if (resultCode == RESULT_OK) { Toast.makeText(this, "Video has been saved to:\n" + data.getData(), Toast.LENGTH_LONG).show(); playbackRecordedVideo(); } else if (resultCode == RESULT_CANCELED) { Toast.makeText(this, "Video recording cancelled.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "Failed to record video", Toast.LENGTH_LONG).show(); } }
was added
+ playbackRecordedVideo() methode.
now the add also records and playback videos :ddr:
shouryuken
_________________ MB over and out
Last edited by Moti Barski on Sun Sep 02, 2018 9:39 pm; edited 4 times in total
Moti Barski super
Posts : 498 Join date : 2011-08-02
Subject: android studio firebase chit chat app Sun Sep 02, 2018 8:12 pm
tool strip: tools, firebase, realtime firebase save and retrieve data, connect to firebase, add the real time database to your app.
add implementation 'com.android.support:design:27.1.1' to gradle module.
at solution explorer window : project, app, google-services.json : change package name to your package name. to make it work on different other apps put in that json file with the other app package name, them those other apps can chat with the prime app and among themselves.
private void sendMessage() { String msg = myMsg.getText().toString(); myMsg.setText(""); //fire base will give us singleton of his instance
//creating an instance to the database FirebaseDatabase database = FirebaseDatabase.getInstance(); //creating a referance to message object DatabaseReference msgRef = database.getReference(REF_ID); //set value to the database msgRef.setValue(msg); }
private void setMessageListener() { //create an instance to the database FirebaseDatabase database = FirebaseDatabase.getInstance(); //create a referance to the database DatabaseReference msgRef = database.getReference(REF_ID); //create an event listner with callback to our Reference msgRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { //this method is called once with the initial value and again //whenever data at this location is updated String value=dataSnapshot.getValue(String.class); msgList.add(0,value); ChatAdapter myAdapter = new ChatAdapter(context,msgList); myMsgList.setAdapter(myAdapter); }
@Override public void onCancelled(@NonNull DatabaseError databaseError) {
} private void createNotification(int nId, int icon, String msg, String title, Context context) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext(), "notify_001"); Intent ii = new Intent(context.getApplicationContext(), MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, ii, 0);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle(); bigText.bigText(msg); bigText.setBigContentTitle(msg); bigText.setSummaryText("Text in detail");
key notes : replace 5000 with in how many milisecs from current time you want the scheduled task to fire up (scream of the banshee)
to calculate delay you can use (from moti barski java grimoire):
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); java.util.Date date2 = dateFormatter.parse("1955-11-05 " + RAL1.getEndTime()); Calendar cal = Calendar.getInstance(); int h2 = date2.getHours() - cal.getTime().getHours(); int m2 = date2.getMinutes() - cal.getTime().getMinutes(); int s2 = date2.getSeconds() - cal.getTime().getSeconds(); int delay2 = h * 3600000 + m * 60000 + s * 1000; if (delay2 < 0) { delay2 += 24 * 24 * 3600000; }
keynote 2 : the Handler in MyTimeTask enables the toast message
_________________ MB over and out
Admin Admin
Posts : 140 Join date : 2011-08-01
Subject: android studio java thread techniques Mon Sep 10, 2018 11:52 am
threading makes codes run inparallel on different processor cores at the same time, giving the app speed, this is called asyncro. unlike syncro that runs linearly.
public class MainActivity extends AppCompatActivity { // TextView pelet; final Date now = new Date(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //pelet = findViewById(R.id.txtOutput); Thread t = new Thread(new Runnable() { @Override public void run() { for(int i = 0;i<500;i++){ Log.d("async", now + " ___ " + i); } } }); t.start(); } }
set thread priority importance : t.setPriority(5); get thread priority : t.getPriority(5); get current thread priority : Thread.currentThread().getPriority();
3 join : makes whatever is on the main program thread wait till joined threads finish :
ExThread.java
Code:
package com.yotamarker.egyptiancotton;
import android.util.Log;
public class ExThread extends Thread { @Override public void run() { for (int i = 0; i < 500; i++) { Log.d("async", " ___ " + i); } } }
public class MainActivity extends AppCompatActivity { // TextView pelet; final Date now = new Date(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ExThread t1 = new ExThread(); ExThread t2 = new ExThread(); t1.start();; t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < 500; i++) { Log.d("sync", " ___ " + i); } } }
4 pause a thread : Thread.sleep(5000); 5 stop a thread :
t.stopThread(); // assuming it started (t.start()
6 mutex syncro shoukan:
Code:
import android.util.Log;
public class ExThread extends Thread { private static Object mutex = new Object(); @Override public void run() { synchronized (mutex){ // this code block will run syncro } // outside mutex runs asyncro for (int i = 0; i < 500; i++) { Log.d("async", " ___ " + i); } } }
7 making a thread stop for racing several threads
stoppable thread class ExThread.java :
Code:
package com.yotamarker.egyptiancotton;
import android.util.Log;
public class ExThread extends Thread { public boolean stop = false; // can also set as static var @Override public void run() { for (int i = 0; i < 5000; i++) { if(!stop){ Log.d("async", "long thread ___ " + i);} else{return;}
} } }
fast thread ExThread2:
Code:
package com.yotamarker.egyptiancotton;
import android.util.Log;
public class ExThread2 extends Thread { private static Object mutex = new Object(); @Override public void run() {
for (int i = 0; i < 500; i++) { Log.d("async", " short thread___ " + i); } } }
\n\nThis software may not, in whole or in any part, be copied, reproduced, transmitted, translated (into any language, natural or computer), stored in a retrieval system, reduced to any electronic medium or machine readable format, or by any other form or means without prior consent, in writing, from APP_NAME.
\n\nYou are granted a limited license to use this software. The software may be used or copied only in accordance with the terms of that license, which is described in the following paragraphs.
\n\nTRADEMARKS: \n\n[Software logos, icons, etc that are Trademarked]
\n\nLICENSE: \n\n\"THE SOFTWARE\" shall be taken to mean the software contained in this app and any subsequent versions or upgrades received as a result of having purchased this app. \"BUYER\" shall be taken as the original purchaser of the software.
\n\nBuyer has the non-exclusive right to the use of software only on a single device. Buyer may not electronically transfer the program from one device to another over any type of network. Buyer may not distribute copies of the software or the accompanying documentation to others either for a fee or without charge. Buyer may not modify or translate the program or documentation. User may not disassemble the program or allow it to be disassembled into its constituent source code. Buyer\'s use of the software indicates his/her acceptance of these terms and conditions. If buyer does not agree to these conditions, return the distribution media, documentation, and associated materials to the vendor from whom the software was purchased, and/or uninstall the software from the device, and erase the software from any and all storage devices upon which it may have been installed.
\n\nThis license agreement shall be governed by the laws of The United States of America, Massachusetts and shall inure to the benefit of APP_NAME or its assigns.
\n\nDISCLAIMER / LIMITATION OF LIABILITY: \n\nBuyer acknowledges that the software may not be free from defects and may not satisfy all of buyer\'s needs. APP_NAME warrants all media on which the software is distributed for 60 days to be free from defects in normal use. The software and any accompanying written materials are licensed \"AS IS\". Buyer\'s exclusive remedy during the warranty period (if any) shall consist of replacement of distribution media if determined to be faulty. In no event will APP_NAME be liable for direct, indirect, incidental or consequential damage or damages resulting from loss of use, or loss of anticipated profits resulting from any defect in the software, even if it has been advised of the possibility of such damage. Some laws do not allow exclusion or limitation of implied warranties or liabilities for incidental or consequential damages, so the above limitations or exclusion may not apply.
\n\nSPECIFIC RESTRICTIONS: \n\nIn accordance with the COMPUTER SOFTWARE RENTAL ACT OF 1990, this software may not be rented, lent or leased. \n\nThe software and accompanying documentation may not be provided by a \"Backup Service\" or any other vendor which does not provide an original package as composed of APP_NAME, including but not limited to all original distribution media, documentation, registration cards, and insertions. </string> </resources>
public class MainActivity extends AppCompatActivity { final String EULA_FLAG = "1"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(!readEula()){EULA();}
}
private void EULA() { new AlertDialog.Builder(this) .setTitle("agreement to use app") .setMessage(R.string.EULA) .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { saveTrue(); } }) .setNegativeButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); System.exit(0); dialog.dismiss(); } }) .create().show();
click cancel on the agreement : app closes click ok : app saves you agreed, and doesn't display the EULA any more when the app opens note that : finish(); System.exit(0); are the code lines to close the app