Toast.makeText(getApplicationContext(), getResources().getString(R.string.your_text), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), getString(R.string.your_text), Toast.LENGTH_LONG).show();
class Test {
public static void main(String[] args) {
int k = 10000;
long st, en;
int[] A;
int length = 100000;
A = new int[length];
st = System.nanoTime();
for (int i = 0; i < length; i++)
{
A[i] = k;
}
en = System.nanoTime();
System.out.println("\nOne time=" + (en - st) / 1000000.d + " msc");
int cache = 10000;
A = new int[length];
int[] temp = new int[cache];
st = System.nanoTime();
for (int N = 0; N < length; N+=cache) {
for (int i = 0; i < cache; i++) {
temp[i] = k;
}
System.arraycopy(temp, 0, A, N, temp.length);
}
en = System.nanoTime();
System.out.println("\nTwo time=" + (en - st) / 1000000.d + " msc");
}
}
Более удивительной по сравнению с производительностью при чтении является производительность при записи и копировании. Производительность при записи даже для рабочих наборов с небольшими размерами, никогда не поднимается выше 4 байтов за цикл. Это указывает на то, что в таких процессорах Netburst, Intel решила использовать в кэш-памяти L1d режим с прямой записью (Write-Through), при котором скорость, очевидно, ограничена скорость работы кэш-памяти L2. Это также означает, что производительность теста копирования, в котором данные копируются из одной области памяти в другую непересекающуюся области памяти, не намного хуже. Следовательно, требуемые операций чтения выполняются намного быстрее и могут частично перекрываться с операциями записи. Самым интересными деталями измерения записи и копирования является низкая производительность в случае, как только становится мало кэш-памяти L2. Производительность падает до 0,5 байта за цикл! Это значит, что операции записи в десять раз медленнее, чем операции чтения. Это означает, что оптимизация этих операций еще более важна для выполнения программы.
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle("Cообщение")
.setMessage("Приложение свернули")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alert.show();
public class BaseActivity extends AppCompatActivity {
protected boolean isShowAlert = true;
private int oldOrientation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
oldOrientation = getResources().getConfiguration().orientation;
}
@Override
protected void onPause() {
super.onPause();
int currentOrientation = getResources().getConfiguration().orientation;
if(currentOrientation != oldOrientation)
isShowAlert = false;
}
@Override
protected void onStart() {
super.onStart();
isShowAlert = true;
}
@Override
protected void onStop() {
super.onStop();
if (isShowAlert)
AppHideHandler();
}
@Override
public void onBackPressed() {
isShowAlert = false;
super.onBackPressed();
}
public void AppHideHandler() {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle("Сообщение")
.setMessage("Приложение свернули")
.setCancelable(true);
AlertDialog alert = builder.create();
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alert.show();
}
}
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isShowAlert = false;
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
});
}
}
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:popupTheme="@android:style/ThemeOverlay.Material.Light"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#ffffff">
</LinearLayout>
</android.support.v7.widget.Toolbar>
public class MyClass {
MyClassCallback callback;
public MyClass() {
if(callback != null)
callback.done();
}
public void setCallback(MyClassCallback callback) {
this.callback = callback;
}
public void perform() {
if(callback != null)
callback.done();
}
interface MyClassCallback {
void done();
}
}
public class MainActivity extends AppCompatActivity {
private MyClass myClass;
private MyClass.MyClassCallback myClassCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myClass = new MyClass();
myClassCallback = new MyClass.MyClassCallback() {
@Override
public void done() {
Toast.makeText(MainActivity.this, "Мое сообщение", Toast.LENGTH_LONG).show();
}
};
myClass.setCallback(myClassCallback);
myClass.perform();
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:listSelector="@color/item_color_test"
android:id="@+id/listView"/>
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
private final static String KEY = "selectedRow";
private MyAdapter adapter;
private int selectedItem = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
final String[] data = {
"a","v","c"
};
if(savedInstanceState != null && savedInstanceState.containsKey(KEY))
{
selectedItem = savedInstanceState.getInt(KEY);
}
adapter = new MyAdapter(this, R.layout.item, data, selectedItem);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selected = data[position];
selectedItem = position;
adapter.setSelectedRow(selectedItem);
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY, selectedItem);
}
private class MyAdapter extends ArrayAdapter<String> {
final int resId;
int selectedRow;
public MyAdapter(Context context, int resId, String[] data, int selectedRow) {
super(context, resId, data);
this.resId = resId;
this.selectedRow = selectedRow;
selectedColor = getResources().getColor(R.color.item_color_test);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String string = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(resId, null);
}
TextView textView = (TextView) convertView;
textView.setText(string);
textView.setBackgroundColor(position == selectedRow ? selectedColor : 0x00000000);
return convertView;
}
public void setSelectedRow(int row)
{
selectedRow = row;
notifyDataSetInvalidated();
}
}
}
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingTop="20dp"
android:paddingBottom="20dp"
android:paddingLeft="10dp"/>
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ValueAnimator;
public class RippleCircle extends View {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = RippleCircle.class.getSimpleName();
private static final int RIPPLE_COLOR = 0x66000000;
private static final int RIPPLE_FADE_COLOR = 0x22000000;
private static final int FAB_COLOR = 0xffcccccc;
private static final long ANIM_DURATION = 250;
protected static int FLAGS = Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG;
// ===========================================================
// Fields
// ===========================================================
private Paint mButtonBg;
private Paint mRippleButtonBg;
private Path main;
private ValueAnimator animatorRipple;
private float selRadius;
private float radius;
private float centerY;
private float centerX;
private float rippleX;
private float rippleY;
private boolean isButtonTouchDown;
private boolean isProgress;
// ===========================================================
// Constructors
// ===========================================================
public RippleCircle(Context context) {
super(context);
init();
}
public RippleCircle(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected void onDraw(Canvas canvas) {
canvas.drawCircle(centerX, centerY, radius, mButtonBg);
canvas.clipPath(main);
canvas.drawCircle(rippleX, rippleY, selRadius, mRippleButtonBg);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
float size = Math.min(w, h);
centerY = size / 2;
centerX = size / 2;
radius = size / 2;
main.addCircle(centerX, centerY, radius, Path.Direction.CCW);
animatorRipple.setFloatValues(0, radius);
}
// ===========================================================
// Inner Methods
// ===========================================================
private void init() {
main = new Path();
animatorRipple = ValueAnimator.ofFloat(0, 0);
animatorRipple.setDuration(ANIM_DURATION);
animatorRipple.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
selRadius = (Float) animation.getAnimatedValue();
if (selRadius / radius <= 1 && selRadius / radius >= 0)
mRippleButtonBg.setColor(blendColors(RIPPLE_COLOR, RIPPLE_FADE_COLOR, 1 - selRadius / radius));
invalidate();
}
});
animatorRipple.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
if (!isButtonTouchDown) {
selRadius = 0;
invalidate();
isProgress = false;
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
setLayerType(LAYER_TYPE_SOFTWARE, null);
}
mButtonBg = new Paint(FLAGS);
mButtonBg.setColor(FAB_COLOR);
mRippleButtonBg = new Paint(FLAGS);
mRippleButtonBg.setColor(RIPPLE_COLOR);
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
rippleX = event.getX();
rippleY = event.getY();
if (isPointInCircle(centerX, centerY, event.getX(), event.getY(), radius)) {
isButtonTouchDown = true;
if (!isProgress) {
rippleX = event.getX();
rippleY = event.getY();
isProgress = true;
float max = distance(centerX, centerY, rippleX, rippleY) + radius;
animatorRipple.setFloatValues(0, max);
animatorRipple.start();
}
}
break;
case MotionEvent.ACTION_UP:
isButtonTouchDown = false;
if (!animatorRipple.isRunning()) {
selRadius = 0;
invalidate();
isProgress = false;
}
break;
}
return true;
}
});
}
private boolean isPointInCircle(float centerX, float centerY, float x, float y, float radius) {
return distance(centerX, centerY, x, y) <= radius;
}
private float distance(final float pX1, final float pY1, final float pX2, final float pY2) {
final float dX = pX2 - pX1;
final float dY = pY2 - pY1;
return (float) Math.sqrt((dX * dX) + (dY * dY));
}
private int blendColors(int color1, int color2, float ratio) {
final float inverseRation = 1f - ratio;
float a = (Color.alpha(color1) * ratio) + (Color.alpha(color2) * inverseRation);
float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
return Color.argb((int) a, (int) r, (int) g, (int) b);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
<yourPackage.RippleCircle
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_centerInParent="true"/>
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
new MyTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
new MyTask().execute();
}