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

来源:互联网 发布:二十四节气小雪知乎 编辑:程序博客网 时间:2024/05/10 12:46

http://www.cnblogs.com/yejiurui/archive/2012/12/31/2840994.html

           

           目录如下:

第一礼:删除时候弹出一个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载入        });
复制代码

 

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

1
  
复制代码
//检查某个应用是否安装    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;        }    }
复制代码

0 0
原创粉丝点击