Android -- 经验分享_移动开发_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > 移动开发 > Android -- 经验分享

Android -- 经验分享

 2014/8/5 19:51:28  我爱物联网  程序员俱乐部  我要评论(0)
  • 摘要:目录代码中安装apk判断某个apk是否已经安装取得屏幕大小获得LayoutInflater实例的三种方式ContentResolver.query(),以及Activity.managedQuery异同解锁功能点亮屏幕activity全屏显示屏常亮代码SQL中innerjoin、leftjoin、rightjoin、outerjoin之间的区别包含button的item也能弹出菜单,回调click以及longclick的监听器背光亮度/sys/class/leds/lcd
  • 标签:android 经验 经验分享

目录                                                                                            

  • 代码中安装apk
  • 判断某个apk是否已经安装
  • 取得屏幕大小
  • 获得 LayoutInflater 实例的三种方式
  • ContentResolver.query(),以及 Activity.managedQuery异同
  • 解锁功能
  • 点亮屏幕
  • activity全屏显示
  • 屏常亮代码
  • SQL中 inner join、 left join 、right join、 outer join之间的区别
  • 包含button的item也能弹出菜单,回调click以及long click的监听
  • 背光亮度   /sys/class/leds/lcd-backlight/brightness
  • 判断是否在锁屏界面的函数
  • OnTouchListener实现双击事件
  • 回到待机界面
  • 定时器相关
  • sd卡和sim卡状态判断
  • 开机启动,检查sim卡是否发生变更

代码中安装apk                                                                             

Runtime.getRuntime().exec("pm install xxx.apk");

需要在manifest.xml文件中,加上INSTALL_PACKAGES的权限,可以用 Package install的receiver来处理安装成功后的操作

或者:

/** 
     * 安装apk 
     * @param url 
     */  
    private void installApk(String saveFileName){  
        File apkfile = new File(saveFileName);  
        if (!apkfile.exists()) {  
            return;  
        }      
        Intent i = new Intent(Intent.ACTION_VIEW);  
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");   
        mContext.startActivity(i);  
}

判断某个APK是否已经安装                                                             

private boolean isAppInstalled(String uri){  
      
    PackageManager pm = getPackageManager();  
    boolean installed =false;  
    try{  
        pm.getPackageInfo(uri,PackageManager.GET_ACTIVITIES);  
        installed =true;  
    }catch(PackageManager.NameNotFoundException e){  
        installed =false;  
    }  
      
    return installed;  
 }
//Just call the method by passing the package name of the application you need to check.
    if(isAppInstalled("com.yourpackage.package")){
     //app installed
    }else{
      //app not installed
    }

取得屏幕大小                                                                                

1、在非activity类中

WindowManager windowManager = (WindowManager)(mContext.getSystemService(Context.WINDOW_SERVICE));
 int screenWidth = windowManager.getDefaultDisplay().getWidth(); 
 int screenHeight = windowManager.getDefaultDisplay().getHeight();

2、在activity类中

int screenWidth  = getWindowManager().getDefaultDisplay().getWidth();       // 屏幕宽(像素,如:480px)  
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();      // 屏幕高(像素,如:800px)

获得 LayoutInflater 实例的三种方式                                             

LayoutInflater inflater = getLayoutInflater();  //调用Activity的getLayoutInflater()
LayoutInflater localinflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(context);

示意代码:

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
View view = inflater.inflate(R.layout.custom, (ViewGroup)findViewById(R.id.test));

对于上面代码,指定了第二个参数 ViewGroup root,当然你也可以设置为 null 值。

ContentResolver.query(),以及 Activity.managedQuery异同

参数、返回值相同:都返回 Cursor 对象

参数:

URI:  Content Provider 需要返回的资源索引
Projection: 用于标识有哪些columns需要包含在返回数据中。
Selection: 作为查询符合条件的过滤参数,类似于SQL语句中Where之后的条件判断。
SelectionArgs: 同上。
SortOrder: 用于对返回信息进行排序。

不同:

mContext.getContentResolver().query

ContentResolver.query(),以及 Activity.managedQuery()所以,我们看到一个是ContentResolver提供的查询方法,位于android.content.ContextWrapper.getContentResolver(),另一个则为Activity。  

Activity.managedQuery()  方法导致活动管理 Cursor 的生命周期

解锁功能                                                                                      

KeyguardManager keyguardManager = (KeyguardManager)getSystemService(KEYGUARD_SERVICE);    
KeyguardLock keyguardLock = keyguardManager.newKeyguardLock(""); 
keyguardLock.disableKeyguard();
PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);

点亮屏幕                                                                                      

PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE); 
WakeLock mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP|PowerManager.SCREEN_DIM_WAKE_LOCK,"SimpleTimer"); 
mWakeLock.acquire();//点亮 
mWakeLock.release();//关闭

activity全屏显示                                                                          

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);

注意;要在setContentView(R.layout.layout)语句之前调用才行。

屏常亮代码                                                                                   

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//屏常亮

SQL中 inner join、 left join 、right join、 outer join之间的区别

举例说明

A表(a1,b1,c1)      B表(a2,b2)
a1   b1   c1        a2    b2
01   数学 95         01    张三
02   语文 90         02    李四
03   英语 80         04    王五
select A.*,B.* from A  inner join B on(A.a1=B.a2)
结果是:
a1   b1   c1       a2    b2
01   数学 95       01    张三
02   语文 90       02    李四
select A.*,B.* from A  left outer join B on(A.a1=B.a2)
结果是:
a1   b1   c1       a2    b2
01   数学 95       01    张三
02   语文 90       02    李四
03   英语 80       NULL  NULL
select A.*,B.* from A  right outer join B on(A.a1=B.a2)
结果是:
a1   b1   c1       a2    b2
01   数学 95       01    张三
02   语文 90       02    李四
NULL NULL NULL     04    王五
select A.*,B.* from A  full outer join B on(A.a1=B.a2)
结果是:
a1   b1   c1       a2    b2
01   数学 95       01    张三
02   语文 90       02    李四
03   英语 80       NULL  NULL
NULL NULL NULL     04    王五

包含button的item也能弹出菜单,回调click以及long click的监听器  

设置button属性:

android:focusable="false"

外还要设置 listview属性:

android:longClickable="true"

PS: 如果包含的Button是ImageButton,那么在xml中设置了android:focusable="false"属性在当前版本是无效的,必须在代码中,再次呼叫函数ImageButton.setFocusable(false)设置一次。 

或者在父Item里面加上

android:descendantFocusability="blocksDescendants"

背光亮度   /sys/class/leds/lcd-backlight/brightness            

例如

echo 255 > /sys/class/leds/lcd-backlight/brightness

代码修改亮度:

Settings.System.putInt(getContentResolver(), SCREEN_BRIGHTNESS, brightness);    //brightness 背光亮度 0~255
Settings.System.putInt(getContentResolver(),SCREEN_OFF_TIMEOUT, timeoutValues);//timeoutValues 灭屏时间 ms

判断是否在锁屏界面的函数                                                              

KeyguardManager: inKeyguardRestrictedInputMode();

例:

KeyguardManager km = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
boolean keyguardexist = km.inKeyguardRestrictedInputMode();

OnTouchListener实现双击事件                                                    

class MyOnTouchListener implements View.OnTouchListener{
    private long mLastTime = 0;
    private long mCurTime = 0;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(MotionEvent.ACTION_DOWN == event.getAction()){  
            mLastTime = mCurTime; 
            mCurTime = System.currentTimeMillis();
            if (mCurTime - mLastTime < 1000) {
                // 双击事件  关闭activity
                FullBlackActivity.this.finish();
                return true;
            }
        }
        return false;
    }
}

回到待机界面                                                                                

Intent home = new Intent(Intent.ACTION_MAIN);  
home.addCategory(Intent.CATEGORY_HOME);  
this.startActivity(home);

定时器相关                                                                                   

  • 采用Handler与线程的sleep(long)方法

Handler主要用来处理接受到的消息。

1. 定义一个Handler类,用于处理接受到的Message。

Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        // 要做的事情
        super.handleMessage(msg);
    }
};

新建一个实现Runnable接口的线程类,如下:

public class MyThread implements Runnable {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            try {
                Thread.sleep(10000);// 线程暂停10秒,单位毫秒
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);// 发送消息
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

3. 在需要启动线程的地方加入下面语句:

new Thread(new MyThread()).start();

4. 启动线程后,线程每10s发送一次消息。

  • 采用Handler的postDelayed(Runnable, long)方法

1. 定义一个Handler类

Handler handler=new Handler();
Runnable runnable=new Runnable() {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        //要做的事情
        handler.postDelayed(this, 2000);
    }
};

2. 启动计时器

handler.postDelayed(runnable, 2000);//每两秒执行一次runnable.

3. 停止计时器

handler.removeCallbacks(runnable);
  • 采用Handler与timer及TimerTask结合的方法

1. 定义定时器、定时器任务及Handler句柄

private final Timer timer = new Timer();
private TimerTask task;
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        // 要做的事情
        super.handleMessage(msg);
    }
};

2. 初始化计时器任务

task = new TimerTask() {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        Message message = new Message();
        message.what = 1;
        handler.sendMessage(message);
    }
};

3. 启动定时器

timer.schedule(task, 2000, 2000);

简要说一下上面三步提到的一些内容:

1. 定时器任务(TimerTask)顾名思义,就是说当定时器到达指定的时间时要做的工作,这里是想Handler发送一个消息,由Handler类进行处理。

2. java.util.Timer.schedule(TimerTask task, long delay, long period):这个方法是说,delay/1000秒后执行task,然后进过period/1000秒再次执行task,这个用于循环任务,执行无数次,当然,你可以用timer.cancel();取消计时器的执行。

  • 闹钟定时
AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(SEND_SMS_BEGIN), 0);
am.set(AlarmManager.RTC_WAKEUP, 60*1000, pendingIntent);

耳机状态                                                                                      

private static final String HEADSET_STATE_PATH = "/sys/class/switch/h2w/state";    //保存状态文件位置

private boolean isHeadsetExists(){       //判断耳机是否插入的函数    FM源码 FMplayService.java  
        char[] buffer = new char[1024];
        int newState = 0;
        try {
            FileReader file = new FileReader(HEADSET_STATE_PATH);
            int len = file.read(buffer, 0, 1024);
            newState = Integer.valueOf((new String(buffer, 0, len)).trim());
        } catch (FileNotFoundException e) {
            Log.e(LOGTAG, "This kernel does not have wired headset support");
        } catch (Exception e) {
            Log.e(LOGTAG, "" , e);
        }
        return newState != 0;
   }
未插入耳机:

# cat /sys/class/switch/h2w/state
cat /sys/class/switch/h2w/state
0

插入耳机:
# cat /sys/class/switch/h2w/state
cat /sys/class/switch/h2w/state
1

sd卡和sim卡状态判断                                                                   

//sdcard是否可读写 
public boolean IsCanUseSdCard() { 
    try { 
        return Environment.getExternalStorageState().equals( 
                Environment.MEDIA_MOUNTED); 
    } catch (Exception e) { 
        e.printStackTrace(); 
    } 
    return false; 
} 

//sim卡是否可读 
public boolean isCanUseSim() { 
    try { 
        TelephonyManager mgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
         return TelephonyManager.SIM_STATE_READY == mgr.getSimState(); 
    } catch (Exception e) { 
        e.printStackTrace(); 
    } 
    return false; 
}

开机启动,检查sim卡是否发生变更                                                  

(1)注册receiver,设置意图过滤器

<receiver android:name=".receiver.BootCompleteReceiver" >
    <intent-filter android:priority="1000" >
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

(2)接受开机广播,并判断sim卡时候发生更改

public class BootCompleteReceiver extends BroadcastReceiver {
    private static final String TAG = "BootCompleteReceiver";
    private SharedPreferences sp;
    private TelephonyManager tm;
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG,"手机重启了");
        sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
        boolean protecting = sp.getBoolean("protecting", false);
        //如果防盗保护开启
        if(protecting){
                //判断sim卡是否发生了变化
        tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String currentSim = tm.getSimSerialNumber();
            String savedSim= sp.getString("sim", "");
            if(savedSim.equals(currentSim)){
                    // sim卡为发生变化, do nothint
            }else{
                //sim卡发生了变化
                //发送报警短信 给安全号码
                SmsManager smsManager = SmsManager.getDefault();
                String destinationAddretss = sp.getString("safenumber", "");
                smsManager.sendTextMessage(destinationAddretss, null, "sim change !!!", null, null);
            }
        }
    }
}

我是天王盖地虎的分割线                                                                 

 

 

参考:http://blog.csdn.net/jimbo_lee/article/details/8694265

发表评论
用户名: 匿名