常用代码随笔--非懒癌晚期勿进

懒癌的福音https://github.com/vondear/RxTools

一网络

1.AsyncTask

class ContactAsync extends AsyncTask
	{
		private ProgressDialog dialog;

		@Override
		protected void onPreExecute()
		{
			dialog = new ProgressDialog(mContext);
			this.dialog.setMessage(mContext.getResources().getString(R.string.loading_contact_msg));
			this.dialog.show();
		}

		@Override
		protected String doInBackground(Integer... params)
		{
			Map param;			
			String url = URL_HEAD + "/iw/qinqinghao";
			param = new HashMap();
			param.put("imei", imei);
			return NetUtils.post(url, param, "-------------查询联系人-------------------");

		}

		@Override
		protected void onPostExecute(String s)
		{
			if (this.dialog.isShowing())
			{
				this.dialog.dismiss();
			}
			if (s == null)
			{
				Toast.makeText(mContext, "网络异常!", Toast.LENGTH_SHORT).show();
				return;
			}

			org.json.JSONObject resultObj = null;
			try
			{
				resultObj = new org.json.JSONObject(s);//用原生解析

				

			} catch (JSONException e)
			{
				e.printStackTrace();
			}

		}

	}




2.handler

Message msg = Message.obtain();
			msg.what = HANDLER_ADD;
			msg.arg1 = i;
			msg.obj = contactInfo.get(i + 1);
			mHander.sendMessage(msg);

3.文件上传

studio用httpclient上传文件,需要添加如下代码才能识别

android {
useLibrary 'org.apache.http.legacy'
} 


二弹窗

1.ppw

public static void createPPW(Context con, int layout)
	{
		PopupWindow window;
		View popupView = LayoutInflater.from(con).inflate(layout, null);
		window = new PopupWindow(popupView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		window.setBackgroundDrawable(new BitmapDrawable());
		window.setFocusable(true);
		window.setOutsideTouchable(true);

 }

显示位置

                // 相对屏幕--中心
		window.showAtLocation(activity.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
		// 相对某个控件
		// 下方:
		window.showAsDropDown(v);
		// 其他方向:
		window.showAtLocation(v, Gravity.RIGHT | Gravity.TOP, 0, height + hight);





2.dialog

在service中显示dia

1.加权限<uses-permission android:name="Android.permission.SYSTEM_ALERT_WINDOW"/>

2.设置 alertDialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));

  但是某些手机对底层进行了修改(小米,魅族之类),系统会默认会拒绝该权限。dialog将无法显示。

解决: 

通过将type设定为TYPE_TOAST, 就可以绕过检查 

Java代码   收藏代码
  1. mProgressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);  

,and单击返回home不dismiss

alertDialog.setCancelable(false);

public void openGPSdialog(boolean isOut)
{
   Log.d(TAG, "显示dia");
   AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
   builder.setMessage(isOut ? "检测到gps未打开" : "检测到室内运动,建议关闭gps");
   builder.setTitle("提示");
   builder.setPositiveButton("" + (isOut ? "打开" : "关闭"), new DialogInterface.OnClickListener()
   {
      @Override
      public void onClick(DialogInterface dialog, int which)
      {
         mContext.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
         waitOpenGps();
         dialog.dismiss();
      }
   });
   builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
   {
      @Override
      public void onClick(DialogInterface dialog, int which)
      {
         dialog.dismiss();
      }
   });
   final Handler handler = new Handler();
   final AlertDialog alertDialog = builder.create();
   alertDialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
   alertDialog.setCancelable(false);
   alertDialog.show();
   Log.d(TAG, "6666666666666666666666显示dia");
}

常用代码随笔--非懒癌晚期勿进_第1张图片

v7实现,自带圆角

用法说明:

1.改成v7的alertdialog

android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);

2.
在values---> styles文件中你运用的主题下面加上这行代码


<item name="alertDialogTheme">@style/Theme.AppCompat.Light.Dialog.Alert.Selfitem>

3.

<style name="Theme.AppCompat.Light.Dialog.Alert.Self" parent="@style/Theme.AppCompat.Light.Dialog.Alert">
    
    <item name="colorAccent">@color/color_6600a1item>
style>

这样就可以实现右边的效果了,会了就感觉很容易,之前不会想实现这种效果就很折腾人。希望这篇博客能够帮助那些需要这种效果的人。
builder.show();
Window window = builder.getWindow();
window.setContentView(R.layout.dialog_xieyi);// 设置弹出框加载的布局

备份:

AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("温馨提示");
builder.setMessage("系统检测到您尚未开卡,是否需要立即开卡");
builder.setPositiveButton("暂不开卡", new DialogInterface.OnClickListener()
{
   @Override
   public void onClick(DialogInterface dialogInterface, int i)
   {

   }
});
builder.setNegativeButton("立即开卡", new DialogInterface.OnClickListener()
{
   @Override
   public void onClick(DialogInterface dialogInterface, int i)
   {
      Intent intent = new Intent(mContext, OpenCardActivity.class);
      intent.putExtra("homeflg", communicationCheck.getFlg());
      startActivity(intent);
   }
});
builder.create().show();

3.toast(自定义)

在service中显示toast
private void showBTBroken(final int flag)
{
   Handler handler = new Handler(Looper.getMainLooper());
   handler.post(new Runnable()
   {
      public void run()
      {
         switch (flag)
         {
         case PHONE_BLOOTH_UNENABLED:
            Toast.makeText(getApplicationContext(), "腕表蓝牙崩溃,正在重启中···", Toast.LENGTH_LONG).show();
            break;
         case WATCH_BLOOTH_UNENABLED:
            Toast.makeText(getApplicationContext(), "请重启腕表蓝牙!", Toast.LENGTH_LONG).show();
            break;
         }
      }
   });
}

4.通知栏

发通知(一直有个误区requestCode和notifid都是独一无二的,实际上注释李明明白白写了notify(id - An identifier for this notification unique within your application.)而requestCode - Private request code for the sender)

private void sendNotification(Context context, String name, String content) {
    Intent localIntent = new Intent(context, MainActivity.class);
    localIntent.putExtra("isNotification", "true");   
    Log.d("mmmm", "手机信息发送系统通知" + requestCode);
    PendingIntent localPendingIntent = PendingIntent.getActivity(context, 随机数, localIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    Notification localNotification = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.local).setContentTitle(name).setContentText(content).setContentIntent(localPendingIntent).setAutoCancel(true).build();
    ((NotificationManager) context.getSystemService(NOTIFICATION_SERVICE)).notify(Integer.parseInt(getCode()), localNotification);
}

public String getCode() {
    Random rand = new Random();// 生成随机数
    String code = "";
    for (int a = 0; a < 8; a++) {
        code += rand.nextInt(10);// 生成8位数字
    }
    return code;
}

坑:随机数位置:相同会导致获取的localIntent的extra信息一直都是最后一条,即被覆盖

Integer.parseInt(getCode())位置:相同导致通知栏信息被覆盖

取消所有通知:

((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll();

三UI

0.代码设置样式

1.字体

path:fonts/msyh.ttf

常用代码随笔--非懒癌晚期勿进_第2张图片

public static void setTypeface(Context context, TextView tv, String path)
{
   Typeface typeFace = Typeface.createFromAsset(context.getAssets(), path);
   tv.setTypeface(typeFace);
}

2.动态改变布局

if ((currIndex == 0  && str.length() > 5) || ((currIndex == 1 || currIndex == 2) && str.length() >= 4))
{
   Log.e("resulttt", "---------------------靠右------------------------------");
   params.addRule(RelativeLayout.CENTER_IN_PARENT, 0);//0:false;
   params.addRule(RelativeLayout.LEFT_OF, R.id.tv_data_unit);
} else
{
   Log.e("resulttt", "---------------------居中------------------------------");
   params.addRule(RelativeLayout.CENTER_IN_PARENT);
   params.addRule(RelativeLayout.LEFT_OF, 0);
}

1.selector


文本,背景等



    
    

2.shape(主要圆角等)







    

    

    

3.bitmap背景图







四.日期


1.系统当前日期

1.字符串

public String getSystemDateStr()
	{
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		return simpleDateFormat.format(new java.util.Date());
	}


2.字段

a.Calendar

    Calendar c = Calendar.getInstance();
    year = c.get(Calendar.YEAR)
    month = c.grt(Calendar.MONTH)
    day = c.get(Calendar.DAY_OF_MONTH)
    hour = c.get(Calendar.HOUR_OF_DAY);
    minute = c.get(Calendar.MINUTE
b.Time

    Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料。
  t.setToNow(); // 取得系统时间。
  int year = t.year;
  int month = t.month;
  int date = t.monthDay;
  int hour = t.hour; // 0-23
  int minute = t.minute;
  int second = t.second;

毫秒转日期

public String getDateByLongStr(String longStr)
	{
		long unixstamp = Long.parseLong(longStr);
		Date dt = new Date(unixstamp);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		return sdf.format(dt);
	}

日期转毫秒

public static long getDateMills2(String dateStr)
	{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try
		{
			return sdf.parse(dateStr).getTime();
		} catch (ParseException e)
		{
			e.printStackTrace();
		}
		return 0;
	}


显示日期规则:今天:时间;昨天:昨天;其他:日期

package com.mstarc.app.record.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class SystemUtil
{

    public static String getDateTitle(long dateMills)
    {
        String currentDate = getDateStr(System.currentTimeMillis());
        String targetDate = getDateStr(dateMills);
        String yesterdayDate = getDateStr(getDateMills(currentDate) - 24 * 60 * 3600);//0点减去随便一个值都是前天
        if (targetDate.equals(currentDate))
        {
            return new SimpleDateFormat("HH:mm").format(dateMills);
        } else if (targetDate.equals(yesterdayDate))
        {
            return "昨天";
        } else
        {
            return targetDate;
        }
    }

    public static String getDateStr(long dateMills)
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(new Date(dateMills));
    }

    public static long getDateMills(String dateStr)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try
        {
            return sdf.parse(dateStr).getTime();
        } catch (ParseException e)
        {
            e.printStackTrace();
        }
        return 0;
    }
}

获取系统时制:

DateFormat.is24HourFormat(context)

获取时间上下午:

String getPrefix(long time)
	{
		final Calendar mCalendar = Calendar.getInstance();
		mCalendar.setTimeInMillis(time);
		int apm = mCalendar.get(Calendar.AM_PM);
		return apm==0?"上午":"下午";
	}


五.存储

1.shared

写:

public void editSharedWeatherInfo(Context context, String key, String value)
	{
		SharedPreferences sharedPreferences = context.getSharedPreferences("share", 0);
		Editor editor = sharedPreferences.edit();
		editor.putString(key, value);
		editor.commit();
	}

读:

	public String getSharedWeatherInfo(Context context, String key)
	{
		SharedPreferences sharedPreferences = context.getSharedPreferences("share", 0);
		String value = sharedPreferences.getString(key, "");
		return value;
	}

清空

	public void clearSharedInfo(String location, Context context)
	{
		SharedPreferences sharedPreferences = context.getSharedPreferences(location, 0);
		Editor editor = sharedPreferences.edit();// 用于写入
		editor.clear();
		editor.commit();
	}


4.sharedpreference

不同应用如何共享:

在manifest.xml里面将两个应用程序的android:sharedUserId属性设为相同

SharedPreferences sharedPreferences = context.getSharedPreferences(location, 0);
中的location

六.数据库

生成数据库中的唯一标识

引用类

import java.util.UUID;

生成随机数

String id=UUID.randomUUID().toString().replace("-","");

7.四大组件

1.广播

a.系统广播

常用的系统广播接收器


b.内部广播

public static class LocationListener extends BroadcastReceiver
{
   @Override
   public void onReceive(Context context, Intent intent)
   {
      setExtraGPSData((BTLocation) intent.getParcelableExtra(Constants.BT_LOCATION_KEY));
      Toast.makeText(context, ((BTLocation) intent.getParcelableExtra(Constants.BT_LOCATION_KEY)).toString(), Toast.LENGTH_SHORT).show();
   }
}
注册:
<receiver android:name="com.mstarc.plus.route_navigation.SingleRouteCalculateActivity$LocationListener">
    <intent-filter>
        <action android:name="com.ginwave.message_changed"/>
    intent-filter>
receiver>


2.显式隐式启动。

在同一个应用内部,知根知底的启动无所为。

不同应用间的交互,无需知道也不方便具体组件的名称啥的,此时就要通过action来启动了。

2.service

aa.         IntentService和service之间的关系区别。

bb.         service和、thread之间的关系

cc.         顺便了解一下线程池

Intentservice:

public class HelloIntentService extends IntentService {

  /** 
   * 构造方法是必需的,必须用工作线程名称作为参数
   * 调用父类的[http://developer.android.com/reference/android/app/IntentService.html#IntentService(java.lang.String) IntentService(String)]构造方法。
   */
  public HelloIntentService() {
      super("HelloIntentService");
  }

  /**
   * IntentService从缺省的工作线程中调用本方法,并用启动服务的intent作为参数。 
   * 本方法返回后,IntentService将适时终止这个服务。
   */
  @Override
  protected void onHandleIntent(Intent intent) {
      // 通常我们会在这里执行一些工作,比如下载文件。
      // 作为例子,我们只是睡5秒钟。
      long endTime = System.currentTimeMillis() + 5*1000;
      while (System.currentTimeMillis() < endTime) {
          synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
          }
      }
  }
}
service:

public class HelloService extends Service {
  private Looper mServiceLooper;
  private ServiceHandler mServiceHandler;

  // 处理从线程接收的消息
  private final class ServiceHandler extends Handler {
      public ServiceHandler(Looper looper) {
          super(looper);
      }
      @Override
      public void handleMessage(Message msg) {
          // 通常我们在这里执行一些工作,比如下载文件。
          // 作为例子,我们只是睡个5秒钟。
          long endTime = System.currentTimeMillis() + 5*1000;
          while (System.currentTimeMillis() < endTime) {
              synchronized (this) {
                  try {
                      wait(endTime - System.currentTimeMillis());
                  } catch (Exception e) {
                  }
              }
          }
          // 根据startId终止服务,这样我们就不会在处理其它工作的过程中再来终止服务
          stopSelf(msg.arg1);
      }
  }

  @Override
  public void onCreate() {
    // 启动运行服务的线程。
    // 请记住我们要创建一个单独的线程,因为服务通常运行于进程的主线程中,可我们不想阻塞主线程。
    // 我们还要赋予它后台运行的优先级,以便计算密集的工作不会干扰我们的UI。
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    
    // 获得HandlerThread的Looper队列并用于Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

      // 对于每一个启动请求,都发送一个消息来启动一个处理
      // 同时传入启动ID,以便任务完成后我们知道该终止哪一个请求。
      Message msg = mServiceHandler.obtainMessage();
      msg.arg1 = startId;
      mServiceHandler.sendMessage(msg);
      
      // 如果我们被杀死了,那从这里返回之后被重启
      return START_STICKY;
  }

  @Override
  public IBinder onBind(Intent intent) {
      // 我们不支持绑定,所以返回null
      return null;
  }
  
  @Override
  public void onDestroy() {
    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); 
  }
}

onStartCommand()的返回值必须是以下常量之一:

START_NOT_STICKY 
如果系统在 onStartCommand()返回后杀死了服务,则不会重建服务了,除非还存在未发送的intent。 当服务不再是必需的,并且应用程序能够简单地重启那些未完成的工作时,这是避免服务运行的最安全的选项。
START_STICKY 
如果系统在 onStartCommand()返回后杀死了服务,则将重建服务并调用 onStartCommand(),但不会再次送入上一个intent, 而是用null intent来调用 onStartCommand() 。除非还有启动服务的intent未发送完,那么这些剩下的intent会继续发送。 这适用于媒体播放器(或类似服务),它们不执行命令,但需要一直运行并随时待命。
START_REDELIVER_INTENT 

如果系统在onStartCommand()返回后杀死了服务,则将重建服务并用上一个已送过的intent调用onStartCommand()。任何未发送完的intent也都会依次送入。这适用于那些需要立即恢复工作的活跃服务,比如下载文件。

没有实践过---提升service优先级或者存活率, 并不能解决被安全软件强行杀死的问题.:
1. service中重写onStartCommand方法,这个方法有三个返回值,START_STICKY是service被kill掉后自动

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

return START_STICKY;   

}
2.配置android:persistent="true"
3. startForeground()stopForeground()//在onStartCommand和destroy中添加
4. android:process=”com.xxx.xxxservice”配置到单独的进程中

3.activity


1.退至后台:

moveTaskToBack(true);

Intent intent = new Intent();
			intent.setAction("android.intent.action.MAIN");
			intent.addCategory("android.intent.category.HOME");
			startActivity(intent);


2.四种启动模式:

常用代码随笔--非懒癌晚期勿进_第3张图片



常用判断:

1.前台运行?

public static boolean isRunningForeground(Context context)
	{
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
		String currentPackageName = cn.getPackageName();
		if (currentPackageName != null && currentPackageName.equals(context.getPackageName()))
		{
			return true;
		}
		return false;
	}

2.网络可用?

 public static boolean isNetworkAvailable(Context context)
    {
        // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null)
        {
            return false;
        }
        else
        {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
            if (networkInfo != null && networkInfo.length > 0)
            {
                for (int i = 0; i < networkInfo.length; i++)
                {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }

9常用事件

1.返回

@Override
public void onBackPressed()
{
   // 按返回键返回桌面
   Log.e("resulttt", "----------------------onBackPressed------------------------");
   moveTaskToBack(true);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
   if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME)
   {
      String startText = startBtn.getText().toString();
      if (startText.equals(getResources().getString(R.string.sport_btn_switch_start)))
      {
         new HeartTool(context).sendmessage(1);// 关闭心率
         SharedTool.getInstance().clearSportStateSharedInfo(context);
         finish();
         return true;
      }
      recordResetMark();
      return true;
   }
   return super.onKeyDown(keyCode, event);
}

10.java

Logger.t("resultttt").d("测试----" + "aaaaaa,aaaa,".split(",").length);

结果:测试----2

11.组件(零碎)

ListView中每个Item项之间都有分割线,设置Android:footerDividersEnabled表示是否显示分割线,此属性默认为true。

1.不显示分割线只要在ListView控件中添加android:footerDividersEnabled="false"即可。

[html] view plain copy
  1. <ListView  
  2.     android:id="@+id/local_groups_list"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:footerDividersEnabled="false" />  

2.改变ListView的分割线颜色和宽度,需要在布局中定义android:dividerandroid:dividerHeight属性。

[html] view plain copy
  1. <ListView  
  2.     android:id="@+id/local_groups_list"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:divider="@color/divider_color"  
  6.     android:dividerHeight="1px" />
2.
    android:checkedButton="@id/rb_default"//设置默认选项    
android:orientation="horizontal">

bug

1 异常日志:

            java.lang.IllegalStateException: Timer was canceled 

2 所做操作:

            调用cancel()取消后不能再执行 schedule语句,否则提示出现以上异常。

3解决方案

            正确的中止Timer方法:

               timer.cancel();

                    timer.purge();

                    timer = null;(可选)

4.获取当前运行的activity(com.mstarc.app.mstarchelper2.functions.home.ui.HomeActivity

 

private String getRunningActivityName(){         
        ActivityManager activityManager=(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); 
        String runningActivity=activityManager.getRunningTasks(1).get(0).topActivity.getClassName(); 
        return runningActivity;                
}

1.1.其他属性:

ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

        RunningTaskInfo info = manager.getRunningTasks(1).get(0);
        String shortClassName = info.topActivity.getShortClassName();    //类名
        String className = info.topActivity.getClassName();              //完整类名

        String packageName = info.topActivity.getPackageName();          //包名




你可能感兴趣的:(util,懒癌笔记,Android,基础)