Andye献礼2013---Android开发各种小功能大全(第一版)

 

           当日历再翻过去一页的时候,2012这个数字就将变成了回忆。在2012年的最后一个夜晚里,回顾过去的一年的点点滴滴,酸酸甜甜,磕磕绊绊的走到今天,经历过很多的事情,失落过,痛苦过,沮丧过,也脆弱过,成功过,失败过,也痛过,伤过,笑过,流泪过。感谢我的亲人,感谢所有在我困难的时候陪我一起风雨同舟的朋友和兄弟们,感谢你们的帮助,感谢你们的支持,感谢你们的鼓励!是你们的支持和鼓励让我走到现在,所有的一切,我都深深的记在了心底。

         我的2012,已经过去,新的2013,即将到来。

         今天晚上看了以前在2012年年初写的一篇《2012,你的新年梦想是什么?》,写那篇日志的时候是那么的激情满怀,如今的我依然饱含热情,2013,我相信,肯定会比2012更加精彩,相信正在看这篇日志的你也一定精彩!

           加入到园子,已经有三个月的时间了,通过写博客,让我进步很大,还有园子里那么多热心的朋友,跟你们在一起奋斗,很开心。

           本篇《Andye献礼2013》,是我发了将近两天三夜的时间整理出来的。共有两部分,第一部分在2012年的最后一天发布,本篇文章就是第一部分。第二部分将在2013年的一个合适的时间发布,敬请关注。本篇文章我收集并总结了我们安卓开发中的常用小功能,这些都是在开发中经常用到的,我都给整理了下来。来到Andye的小窝,相信总能够找到你需要的!希望能够给大家提供帮助!

         

             Andye 还是一个小菜鸟,需要大家的指点才能够飞的更高。文章在整理的过程中,由于时间仓促,难免会有错误。如果您感觉这篇文章对您有帮助,那么请点击下页面右下角的“推荐”,让更多的朋友看到。如果您看到有些地方有错误,欢迎指出来,Andye一定会感激不尽,您的支持是我前进的动力!谢谢您朋友!

          Andye联系方式:yejiurui@126.com    -- 真诚愿与你做朋友! 

           

           目录如下:

第一礼:删除时候弹出一个dialog界面的操作  
第二礼:按返回键退出程序的dialog操作
第三礼:设置当天的零点时间。
第四礼:短信发送
第五礼:如何设置手机横屏
第六礼:手机的monkey测试
第七礼:防止手机休眠,保持手机背光常亮
第八礼:创建程序的快捷方式
第九礼:播放器中设置快捷键的操作
第十礼:获得当前系统sdk版本号的方法
第十一礼:获取软件当前的版本号
第十二礼:解析从服务器获得的数据 (pull解析器 , 解析xml)
第十三礼:Intent 开启一个activity (无参数)
第十四礼:判断SD卡是否可用
第十五礼:得到当前版本的SD卡的路径
第十六礼:获取SD ROM可用空间
第十七礼:获得ROM可用空间
第十八礼:获取RAM可用空间(Linux)
第十九礼:从网络上下载文件
第二十礼:下载apk后自动安装
第二十一礼:获取手机SIM卡串号
第二十二礼:Sharedpreference 偏好设置
第二十三礼:内容提供者 获取联系人姓名和电话 返回 infos对象
第二十四礼:对话框的使用
第二十五礼:异步任务
第二十六礼:移动图片的动画效果(从左到右移出)
第二十七礼:进度条
第二十八礼:递归删除文件及文件夹
第二十九礼:过滤掉其他的播放器,使用我自己的播放器来做
第三十礼:怎么检测一个应用是否安装



精彩即将呈现:

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------

第一礼:删除时候弹出一个dialog界面的操作  

 

image

代码如下:

// 弹出来一个删除确认的 dialog
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    ConversationActivity.this);
            builder.setTitle(R.string.delete);
            builder.setIcon(android.R.drawable.ic_dialog_alert);
            builder.setMessage(R.string.delete_info);
            // 确定
            builder.setPositiveButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            pd = new ProgressDialog(
                                    ConversationActivity.this);
                            pd.setTitle(R.string.delete);
                            pd.setIcon(android.R.drawable.ic_dialog_alert);
                            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                            pd.setMax(itemSelected.size());
                            pd.setButton(getString(android.R.string.cancel),
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            // 终止信息删除

                                            isDelete = false;
                                        }
                                    });

                            pd.setOnDismissListener(new DialogInterface.OnDismissListener() {

                                public void onDismiss(DialogInterface dialog) {
                                    changeMode(DISPLAYMODE.list);
                                }
                            });

                            pd.show();

 

 

 

 

第二礼:按返回键退出程序的dialog操作

 

按返回键退出程序的操作。

                 public boolean onKeyDown(int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                                builder.setTitle(R.string.exit_title);
                                builder.setMessage(R.string.exit_msg);
                                builder.setPositiveButton(R.string.confirm,
                                                new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                                  
                                                                finish(); 
                                                         

                                                        }
                                                });
                                builder.setNegativeButton(R.string.cancel, null);
                                builder.show();
                                return true;
                        }
                        
                        return super.onKeyDown(keyCode, event);



                @Override
                 public void onDestroy()
                 {
                        System.exit(0); 
                 }
                }

 

第三礼:设置当天的零点时间。

 

Time time = new Time();//得到当前时间,把当前时间都设置为0
            time.setToNow();
            time.hour = 0;
            time.minute = 0;
            time.second = 0;
            // false 时间  true 日期  把时间设置为毫秒值
            long fristSecondOfToday = time.toMillis(false);

 

 

第四礼:短信发送

 

//取得短信电话号码  内容
            String number = actv_enter_number.getText().toString();
            String body = et_enter_msg_content.getText().toString();
            
            SmsManager smsManager = SmsManager.getDefault();
            ArrayList<String> parts = smsManager.divideMessage(body);
            
            for(String part : parts){
                
                smsManager.sendTextMessage(number, null, part, null, null);
                
                Uri url = Sms.Sent.CONTENT_URI;
                ContentValues values = new ContentValues();
                values.put("address", number);
                values.put("body", part);
                getContentResolver().insert(url, values);
            }

 

第五礼:如何设置手机横屏

在清单文件中加入如下代码:

image

 

第六礼:手机的monkey测试

1.使用第一个命令链接设备

2.使用第二个命令 后面的数字代表2000

image

 

第七礼:防止手机休眠,保持手机背光常亮

 

// 保持背光常亮的设置
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

 

第八礼:创建程序的快捷方式

第一种方法:

使用首选项来存储快捷方式的boolean值如果存在就设置为true,不存在就设置为false

直接上代码

if(preference!=null){
                boolean isExit = preference.getBoolean("shortcut", false);
                if(preference!=null&&!isExit){
                    createShortCut();
                    SharedPreferences.Editor editor = preference.edit();
                    if(editor != null){
                         editor.putBoolean("shortcut", true);
                         editor.commit();
                    }
            }
public void createShortCut(){
        try{
            //创建快捷方式的Intent
            Intent shortcutintent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
            //不允许重复创建
            shortcutintent.putExtra("duplicate", false);
            //需要现实的名称
            shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
            //快捷图片
            Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.icon);
            shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
            //点击快捷图片,运行的程序主入口
            shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(getApplicationContext() , LoginActivity.class));
            //发送广播。OK
            sendBroadcast(shortcutintent);
        }catch (Exception e) { 
            closeWindow();
        }
    
    }

第二种方法:

自己看吧,相信你能够看懂

       去系统的lacunch数据库中查找,查找有没有跟我当前应用名字一样的快捷方式,如果有的话,就说明已经存在。

private void createShortCut() {
        // TODO Auto-generated method stub
        //先判断该快捷是否存在
        if(!isExist()){
            Intent intent = new Intent();
            //指定动作名称
            intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
            //指定快捷方式的图标
            Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.congsmall);
            intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
            //指定快捷方式的名称
            intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "短信管理器");
            
            //指定快捷图标激活哪个activity
            Intent i = new Intent();
            i.setAction(Intent.ACTION_MAIN);
            i.addCategory(Intent.CATEGORY_LAUNCHER);
            ComponentName component = new ComponentName(this, MainActivity.class);
            i.setComponent(component);
            intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, i);
            sendBroadcast(intent);
        }
    }
private boolean isExist(){
        boolean isExist = false;
        int version = getSdkVersion();
        Uri uri = null;
        if(version < 2.0){
            uri = Uri.parse("content://com.android.launcher.settings/favorites");
        }else{
            uri = Uri.parse("content://com.android.launcher2.settings/favorites");
        }
        String selection = " title = ?";
        String[] selectionArgs = new String[]{"短信管理器"};
        Cursor c = getContentResolver().query(uri, null, selection, selectionArgs, null);
        if(c.getCount() > 0){
            isExist = true;
        }
        c.close();
        return isExist;
    }

 

 

第九礼:播放器中设置快捷键的操作

   这个可是核心操作,大家可要好好看看哦

/**
     * 设置键盘快捷键
     */
    public void setKeyBoardShortcut() {
        //B表示下一首歌曲
        KeyStroke nextStroke = KeyStroke.getKeyStroke(KeyEvent.VK_B, 0, true);
        //空格表示播放和暂停
        KeyStroke pauseStroke = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true);
        //C表示播放
        KeyStroke playStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, 0, true);
        //V表示停止
        KeyStroke stopStroke = KeyStroke.getKeyStroke(KeyEvent.VK_V, 0, true);
        //三个快捷键,显示三个窗体
        KeyStroke eqStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0, true);
        KeyStroke plStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0, true);
        KeyStroke lrcStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0, true);
        String nextID = "NEXT";
        String pauseID = "PAUSE";
        String playID = "PLAY";
        String stopID = "STOP";
        String eqID = "EQ";
        String plID = "PL";
        String lrcID = "LRC";
        Action nextAction = new AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                if (mp != null) {
                    mp.processNext(e.getModifiers());
                }
            }
        };
        Action pauseAction = new AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                if (mp != null) {
                    mp.processPause(e.getModifiers());
                }
            }
        };
        Action playAction = new AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                if (mp != null) {
                    mp.processPlay(e.getModifiers());
                }
            }
        };
        Action stopAction = new AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                if (mp != null) {
                    mp.processStop(e.getModifiers());
                }
            }
        };
        Action lrcAction = new AbstractAction() {

            public void actionPerformed(ActionEvent ae) {
//                toggleLyricWindow(!lrcWin.isShowing());
                mp.lrc.doClick();
            }
        };
        Action eqAction = new AbstractAction() {

            public void actionPerformed(ActionEvent ae) {
//                toggleEqualizer(!eqWin.isShowing());
                mp.eq.doClick();
            }
        };
        Action plAction = new AbstractAction() {

            public void actionPerformed(ActionEvent ae) {
//                togglePlaylist(!plWin.isShowing());
                mp.pl.doClick();
            }
        };
        setKeyboardAction(nextID, nextStroke, nextAction);
        setKeyboardAction(pauseID, pauseStroke, pauseAction);
        setKeyboardAction(playID, playStroke, playAction);
        setKeyboardAction(stopID, stopStroke, stopAction);
        setKeyboardAction(lrcID, lrcStroke, lrcAction);
        setKeyboardAction(eqID, eqStroke, eqAction);
        setKeyboardAction(plID, plStroke, plAction);

    }

    public void setKeyboardAction(String id, KeyStroke key, Action action) {
        mp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(key, id);
        mp.getActionMap().put(id, action);
        mp.getPlaylistUI().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(key, id);
        mp.getPlaylistUI().getActionMap().put(id, action);
        mp.getEqualizerUI().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(key, id);
        mp.getEqualizerUI().getActionMap().put(id, action);
        mp.getLyricUI().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(key, id);
        mp.getLyricUI().getActionMap().put(id, action);
    }

 

第十礼:获得当前系统sdk版本号的方法

 

/**
     * 得到当前系统sdk版本
     * @return
     */
    private int getSdkVersion(){
        return android.os.Build.VERSION.SDK_INT;
    }

 

第十一礼:获取软件当前的版本号

 

// 获取手机系统的包管理器
PackageManager pm = getPackageManager();
PackageInfo pkinfo=pm.getPackageInfo(getPackageName(),0);
return pkinfo.versionName;

 

第十二礼:解析从服务器获得的数据 (pull解析器 , 解析xml)

 

public class UpdateInfoParser {
    /**
     * 获取服务器上的更新信息
     * @param is 服务器更新信息的返回的流
     * @return UpdateInfo 封装的更新信息
     */
    public static UpdateInfo getUpdateInfo(InputStream is) {
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(is, "UTF-8");
            int type = parser.getEventType();
            UpdateInfo info = null;
            while(type!=XmlPullParser.END_DOCUMENT){
                switch (type) {
                case XmlPullParser.START_TAG:
                    String tagname = parser.getName();
                    if("info".equals(tagname)){
                        info = new UpdateInfo();
                    }else if("version".equals(tagname)){
                        String version = parser.nextText();
                        info.setVersion(version);
                    }
                    break;}
                type = parser.next();}
            return info;

 

第十三礼:Intent 开启一个activity (无参数)

 

Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();    // 关闭当前的界面

 

第十四礼:判断SD卡是否可用

 

if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED))

 

第十五礼:得到当前版本的SD卡的路径

 

Environment.getExternalStorageDirectory()

 

第十六礼:获取SD ROM可用空间

 

private String getSize() {
        //得到ROM剩余空间
        File path = Environment.getDataDirectory();
//得到SD卡剩余空间
       // Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        long availsize = availableBlocks * blockSize;
        String size = Formatter.formatFileSize(this, availsize);
        return size;
    }

 

第十七礼:获得ROM可用空间

 

/**
     * 获取手机的剩余可用ROM
     */
    public static long getAvailableMem(Context context){
        ActivityManager  am  = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        MemoryInfo outInfo = new MemoryInfo();
        am.getMemoryInfo(outInfo);
        long availMem = outInfo.availMem;
        return availMem;
    }

 

第十八礼:获取RAM可用空间(Linux)

 

public static long getTotalRamSize(){
            File file = new File("/proc/meminfo");
            FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String result = br.readLine();
            StringBuffer sb = new StringBuffer();
            for(char c: result.toCharArray()){
                if(c>='0'&&c<='9'){
                    sb.append(c);
                }    }
            return Integer.parseInt(sb.toString())*1024;
    } // 有异常 catch

 

第十九礼:从网络上下载文件

 

URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET"); //
            conn.setConnectTimeout(5000); // 超时时间
            int code = conn.getResponseCode(); // 状态码
            if (code == 200) {
                InputStream is = conn.getInputStream();
            }

 

第二十礼:下载apk后自动安装

 

/**
     * 安装下载完成的APK
     * @param savedFile
     */
    private void installAPK(File savedFile) {
        //调用系统的安装方法
        Intent intent=new Intent();
        intent.setAction(intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(savedFile), "application/vnd.android.package-archive");
        startActivity(intent);
        finish();
    }

 

第二十一礼:获取手机SIM卡串号

 

TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    String sim = tm.getSimSerialNumber();

 

第二十二礼:Sharedpreference 偏好设置

 

private SharedPreferences sp;
        sp = getSharedPreferences("config", MODE_PRIVATE);
// 向偏好设置内添加数据
Editor editor = sp.edit();
editor.putBoolean("update", false);
editor.commit();
// 从偏好设置内提取数据
sp.getBoolean ("update", false);

 

第二十三礼:内容提供者 获取联系人姓名和电话 返回 infos对象

 

public static List<ContactInfo> getContactInfo(Context context) {
        List<ContactInfo> infos = new ArrayList<ContactInfo>();
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        Uri datauri = Uri.parse("content://com.android.contacts/data");
        Cursor cursor = context.getContentResolver() 
.query(uri, null, null,null, null);
        while (cursor.moveToNext()) {
            String id = cursor.getString((cursor.getColumnIndex("contact_id")));
            // 根据上面的ID查询联系人的 信息
        ContactInfo info = new ContactInfo();
            Cursor datacursor = context.getContentResolver().query(datauri,null, "raw_contact_id=?", new String[] { id }, null);
            while (datacursor.moveToNext()) {
                String data1 = datacursor.getString(cursor.getColumnIndex("data1"));
                String mimetype = datacursor.getString(cursor.getColumnIndex("mimetype"));
if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) {
                    info.setNumber(data1);        }
if ("vnd.android.cursor.item/name".equals(mimetype)) {
                    info.setName(data1);        }    }
            datacursor.close();
            infos.add(info);    }
        cursor.close();
        return infos; }

 

第二十四礼:对话框的使用

private void showNormalEntryDialog() {
    AlertDialog.Builder builder = new Builder(this);
    // 按键盘上的取消 回到主界面
    builder.setOnCancelListener(new OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            Intent intent = new Intent(getApplicationContext(), MainActivity.class); 
            startActivity(intent);
            finish();
        }});
        View view = View.inflate(this, R.layout. dialog, null);
        bt_ok = (Button) view.findViewById(R.id.bt_ok);
        bt_ok.setOnClickListener(this);
        dialog = builder.create();
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();
}

 

第二十五礼:异步任务

new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
             // 异步任务运行时执行
                return null;
            }
            @Override
            protected void onPreExecute() {
           //异步任务运行前执行 可以放置进度条 progressbar等
                super.onPreExecute();
            }
            @Override
            protected void onPostExecute(Void result) {
            //异步任务运行结束后执行
                super.onPostExecute(result);
            }
        }.execute();

 

第二十六礼:移动图片的动画效果(从左到右移出)

TranslateAnimation ta = new TranslateAnimation(
                        Animation.RELATIVE_TO_SELF, 0,
                        Animation.RELATIVE_TO_SELF, 1.0f,
                        Animation.RELATIVE_TO_SELF, 0,
                        Animation.RELATIVE_TO_SELF, 0);
                ta.setDuration(200);
                view.startAnimation(ta);

 

第二十七礼:进度条

ProgressDialog pd;
    pd = new ProgressDialog(this);
    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    pd.setTitle("标题");
    pd.setMessage("进度条正文");
    pd.show();

 

第三十八礼:递归删除文件及文件夹

public static void delete(File file) {
    if (file.isFile()) {
        file.delete();
        return;
    }
    if(file.isDirectory()){
        File[] childFiles = file.listFiles();
        if (childFiles == null || childFiles.length == 0) {
            file.delete();
            return;
        }
        for (int i = 0; i < childFiles.length; i++) {
            delete(childFiles[i]);
        }
        file.delete();
    }}

 

第二十九礼:过滤掉其他的播放器,使用我自己的播放器来做

//过滤调用第三方浏览器。并且解析视频网站播放地址,传给播放器
        wv.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(final WebView view,
                    final String url) {
                
                if (url.contains("3gp") || url.contains("mp4")) {//http://113.31.34.14:80/work/500/152/283/484/500.20120913082849.3gp
                    loadurl(view, url, true);//载入视频
                } else {
                    loadurl(view, url, false);// 载入网页
                }
//                http://113.31.34.15:80/work/500/094/076/171/500.20120716165645.3gp

                return true;
            }// 重写点击动作,用webview载入

        });

 

第三十礼:怎么检测一个应用是否安装

 
//检查某个应用是否安装
    public static boolean checkAPP(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager()
                    .getApplicationInfo(packageName,
                            PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (NameNotFoundException e) {
            return false;
        }
    }
 
posted @ 2012-12-31 20:57  Andye  阅读(3282)  评论(4编辑  收藏  举报