Androidプロジェクトまとめ
16519 ワード
プロジェクトのまとめ
最近、会社で非常に軽量なアプリを作っていますが、中にはいくつかの知識点があります.資料を調べてからです.今、アプリは基本的に終わりました.全体をまとめてみましょう.
1.現在のappの基礎情報を取得します.
2.高徳地図(具体的な使い方は官ネットカフェ、ドキュメントが詳しい)
3.個のプッシュ(1つのプッシュサービス、使いやすく、同時にその別名メカニズムも人間的で、バックグラウンドを節約してもう1セットのマッピングを維持しました)
4.Bugly(テンセントの崩壊統計、異常報告のSDK、非常に配置がよく、非常に使いやすい)
5.コールバッククラスを配置する場合、汎用的に作ることができ、非常に便利で柔軟である
6.FragmentでActivityと通信したい場合はEventBusで通信できますが、これに過度に依存しないでください.過度に依存すると、コード全体の論理が異常に複雑になり、同時に異常が発生した後も、非常にチェックしにくいからです.
7.appでは、1つのネットワークインタフェースが何回現れたかにかかわらず、統一的にカプセル化したほうが便利です.
8.Model専用Json文字列をGsonで使用できます.
9.カメラのViewと制御フラッシュを得る:
10.Notification
11.没入式ステータスバー
これはサードパーティ製のライブラリで、使いやすいので、暇があればソースコードをかき回すべきです.
12.反射によるtablayoutの長さの動的調整
13.検証コードカウントダウン
14.downloadManagerツールクラス
15.簡単なツールクラスもあります.
16.cardViewのクリック効果
最近、会社で非常に軽量なアプリを作っていますが、中にはいくつかの知識点があります.資料を調べてからです.今、アプリは基本的に終わりました.全体をまとめてみましょう.
1.現在のappの基礎情報を取得します.
public static final boolean DEBUG = BuildConfig.DEBUG;
//
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.fuyizhulao.daily_service";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0.0";
2.高徳地図(具体的な使い方は官ネットカフェ、ドキュメントが詳しい)
3.個のプッシュ(1つのプッシュサービス、使いやすく、同時にその別名メカニズムも人間的で、バックグラウンドを節約してもう1セットのマッピングを維持しました)
4.Bugly(テンセントの崩壊統計、異常報告のSDK、非常に配置がよく、非常に使いやすい)
5.コールバッククラスを配置する場合、汎用的に作ることができ、非常に便利で柔軟である
public interface NetWorkListener {
void onSuccess(T netWorkModel);
void onFail(T netWorkModel);
}
6.FragmentでActivityと通信したい場合はEventBusで通信できますが、これに過度に依存しないでください.過度に依存すると、コード全体の論理が異常に複雑になり、同時に異常が発生した後も、非常にチェックしにくいからです.
7.appでは、1つのネットワークインタフェースが何回現れたかにかかわらず、統一的にカプセル化したほうが便利です.
8.Model専用Json文字列をGsonで使用できます.
new Gson().toJson(new GetOrderList(
Integer.valueOf(MyApplication.id)
, state
, pageNum
, pageSize))
9.カメラのViewと制御フラッシュを得る:
public class CameraView extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback {
private Camera mCamera;
private int mPreviewRotation = 90;
private int mCamId = Camera.CameraInfo.CAMERA_FACING_BACK;
private PreviewCallback mPrevCb;
private byte[] mYuvPreviewFrame;
private int previewWidth;
private int previewHeight;
private Camera.Parameters params;
public interface PreviewCallback {
void onGetYuvFrame(byte[] data);
}
public CameraView(Context context) {
this(context, null);
}
public CameraView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setPreviewRotation(int rotation) {
mPreviewRotation = rotation;
}
public void setCameraId(int id) {
mCamId = id;
}
public int getCameraId() {
return mCamId;
}
public void setPreviewCallback(PreviewCallback cb) {
mPrevCb = cb;
getHolder().addCallback(this);
}
public void setPreviewResolution(int width, int height) {
previewWidth = width;
previewHeight = height;
}
public boolean startCamera() {
if (mCamera != null) {
return false;
}
if (mCamId > (Camera.getNumberOfCameras() - 1) || mCamId < 0) {
return false;
}
mCamera = Camera.open(mCamId);
params = mCamera.getParameters();
Camera.Size size = mCamera.new Size(previewWidth, previewHeight);
mYuvPreviewFrame = new byte[previewWidth * previewHeight * 3 / 2];
params.setPreviewSize(previewWidth, previewHeight);
params.setPreviewFormat(ImageFormat.NV21);
List supportedFocusModes = params.getSupportedFocusModes();
if (!supportedFocusModes.isEmpty()) {
if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
}
mCamera.setParameters(params);
mCamera.setDisplayOrientation(mPreviewRotation);
mCamera.addCallbackBuffer(mYuvPreviewFrame);
mCamera.setPreviewCallbackWithBuffer(this);
try {
mCamera.setPreviewDisplay(getHolder());
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
return true;
}
public void stopCamera() {
if (mCamera != null) {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
mPrevCb.onGetYuvFrame(data);
camera.addCallbackBuffer(mYuvPreviewFrame);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder arg0) {
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
public void isOpenLight(boolean isOpen) {
if (isOpen) {
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(params);
} else {
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
mCamera.setParameters(params);
}
}
}
10.Notification
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle(title)//
.setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL)) //
.setNumber(number) //
.setTicker(title) // ,
.setWhen(System.currentTimeMillis())// , ,
.setPriority(Notification.PRIORITY_DEFAULT) //
.setAutoCancel(true)//
.setOngoing(false)//ture, 。 , ( ) , ( , , )
.setDefaults(Notification.DEFAULT_VIBRATE)// 、 、 , defaults ,
//Notification.DEFAULT_ALL Notification.DEFAULT_SOUND // requires VIBRATE permission
.setSmallIcon(R.mipmap.ic_launcher);// ICON
mNotificationManager.notify(1, mBuilder.build());
11.没入式ステータスバー
これはサードパーティ製のライブラリで、使いやすいので、暇があればソースコードをかき回すべきです.
compile 'com.readystatesoftware.systembartint:systembartint:1.0.3'
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
//
tintManager.setStatusBarTintEnabled(true);
// enable navigation bar tint
//tintManager.setNavigationBarTintEnabled(true);
//
//tintManager.setTintColor(R.color.red);
//
tintManager.setStatusBarTintResource(R.color.normal_blue);
//Apply the specified drawable or color resource to the system navigation bar.
//
//tintManager.setNavigationBarTintResource(R.color.normal_blue);
}
android:fitsSystemWindows="true"
android:clipToPadding="true"
12.反射によるtablayoutの長さの動的調整
public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
Class> tabLayout = tabs.getClass();
Field tabStrip = null;
try {
tabStrip = tabLayout.getDeclaredField("mTabStrip");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
tabStrip.setAccessible(true);
LinearLayout llTab = null;
try {
llTab = (LinearLayout) tabStrip.get(tabs);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());
for (int i = 0; i < llTab.getChildCount(); i++) {
View child = llTab.getChildAt(i);
child.setPadding(0, 0, 0, 0);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
params.leftMargin = left;
params.rightMargin = right;
child.setLayoutParams(params);
child.invalidate();
}
}
13.検証コードカウントダウン
mTimeCount = new TimeCount(60000, 1000);
mTimeCount.start();
class TimeCount extends CountDownTimer {
public TimeCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {//
mGetCode.setText(" ");
mGetCode.setClickable(true);
}
@Override
public void onTick(long millisUntilFinished) {//
mGetCode.setClickable(false);//
mGetCode.setText(String.valueOf(millisUntilFinished / 1000) + " ");
}
}
14.downloadManagerツールクラス
public class DownloadUtils {
private DownloadManager mDownloadManager;
private Context mContext;
private long downloadId;
private String apkName;
public DownloadUtils(Context context) {
mContext = context;
}
public void download(String url, String name) {
final String packageName = "com.android.providers.downloads";
int state = mContext.getPackageManager().getApplicationEnabledSetting(packageName);
//
if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
|| state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
|| state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext).setTitle(" ").setMessage
(" , ").setPositiveButton(" ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + packageName));
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
Intent intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
mContext.startActivity(intent);
}
}
}).setNegativeButton(" ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
} else {
//
apkName = name;
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setAllowedOverRoaming(false);
//
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setTitle("test");
request.setDescription(" ...");
request.setVisibleInDownloadsUi(true);
//
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName);
// DownloadManager
mDownloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
downloadId = mDownloadManager.enqueue(request);
mContext.registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
checkStatus();
}
};
/**
*
*/
private void checkStatus() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = mDownloadManager.query(query);
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
//
case DownloadManager.STATUS_PAUSED:
break;
//
case DownloadManager.STATUS_PENDING:
break;
//
case DownloadManager.STATUS_RUNNING:
break;
//
case DownloadManager.STATUS_SUCCESSFUL:
installAPK();
break;
//
case DownloadManager.STATUS_FAILED:
Toast.makeText(mContext, " ", Toast.LENGTH_SHORT).show();
break;
}
}
cursor.close();
}
/**
* 7.0
*/
private void installAPK() {
File apkFile =
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), apkName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".provider", apkFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
}
mContext.startActivity(intent);
}
}
15.簡単なツールクラスもあります.
public class Util {
/**
*
*/
public static String stampToDate(String s) {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
long lt = new Long(s);
Date date = new Date(lt);
res = simpleDateFormat.format(date);
return res;
}
/**
*
* :12 21 09:00 - 10:00
*/
public static String stampAndDurationToDate(long serviceTime, long duration) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM dd HH:mm");
Date date = new Date(serviceTime);
String myData = simpleDateFormat.format(date);
Date date2 = new Date(serviceTime + duration * 60 * 1000);
String myData2 = simpleDateFormat.format(date2);
return myData + "-" + myData2.split(" ")[1];
}
/**
*
* :2016-12-21 09:00-10:00
*/
public static String stampAndDurationToDateForOrder(long serviceTime, long duration) {
String date1 = stampToDate(String.valueOf(serviceTime));
String date2 = stampToDate(String.valueOf(serviceTime + duration * 60 * 1000));
return date1 + "-" + date2.split(" ")[1];
}
/**
* bitmap file
*/
public static File saveBitmapFile(Bitmap bitmap) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/img.png");//
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
}
16.cardViewのクリック効果
android:foreground="@drawable/card_view_select"
-
-