Android宝典入门篇-进阶

Android宝典入门篇-进阶

  学习Android前后有快有1个月了,本着不耍流氓,谈恋爱就要结婚的信念(其实AD开发也挺有趣的),做了自己的第一个Android小应用。本来准备今天和大家分享的,考虑到在不同屏幕上的效果没测试和本着节约大家流量的前提下准备后天和大家分享我的APP,抽时间把一些大一点的数据缓冲到手机,不每次都去网络上下载。今天和大家分享我在开发这个app中的一些知识点。

1、请求webservices

  上次和大家说到的是请求wcf,以前有一个现成的.net网站里面提供了webservices服务,我就没有把webservices上功能拉出来部署为wcf服务了。先实现功能再说。今天先说webservices了,以后有机会再聊wcf。其实调用webservices服务挺简单的,下面把代码贴上来 

复制代码
    /**
     * 调用webservices服务
     * 
     * @param url
     *            服务地址/方法名。 例如:http://www.wenyunge.com/webservices/XXX.asmx/
     *            QueryTopsNew
     * @param params方法参数
     *            例如:List params = new ArrayList(); params.add(new
     *            BasicNameValuePair("count", count));
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public String Request(String url, List params) {
        HttpPost request = new HttpPost(url);
        String result = "";
        try {

            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse httpResponse = new DefaultHttpClient()
                    .execute(request);
            if (httpResponse.getStatusLine().getStatusCode() != 404) {
                result = EntityUtils.toString(httpResponse.getEntity());
            }
        } catch (Exception e) {
            try {
                throw e;
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        return result;
    }
复制代码

 简单吧,我就不细说了。

 2、Service、BootBroadcastReceiver学习

   自己用文云阁来看小说,总是要进去后才知道最近有没有更新,这种体验实在是糟透了。作为屌丝的程序员,肯定总能想到办法啦。1、使用BootBroadcastReceiver设置为开机启动(这个好像只有在android4.0以上的系统中才能用上),然后在从写2、onReceive方法时候启动个Service,3、再然后再Service的onCreate里面写一个定时器。定时去检查有没有更新,4、有的话再通过NotificationManager在android通知里面告诉你。这样是不是很屌丝啊。嘿嘿

1、使用BootBroadcastReceiver设置为开机启动

复制代码
AndroidManifest.xml
权限:
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
设置开机启动
<receiver android:name="BootBroadcastReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" >
                </action>

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </receiver>
复制代码

2、onReceive方法时候启动个Service

复制代码
public void onReceive(Context context, Intent intent) {
        // 后边的XXX.class就是要启动的服务
        Intent service = new Intent(context, BookUpdateService.class);
        context.startService(service);
        Log.v("TAG", "更新提醒服务已经启动");
        // 启动应用,参数为需要自动启动的应用的包名
        // Intent intent = getPackageManager().getLaunchIntentForPackage(
        // packageName);

        // context.startActivity(intent);
    }
复制代码

3、再然后再Service的onCreate里面写一个定时器

复制代码
public void onCreate() {
        // TODO Auto-generated method stub
        // Log.i("myService", "onCreate");

        Timer timer = new Timer();

        // 3. 启动定时器,
        timer.schedule(task, 1000, 1800000);

        Log.e("myService", "onCreate");
        System.out.print("onCreate");
    }
复制代码


特意设置1800000半小时检查一次,太快了流量还要钱呢。

4、有的话再通过NotificationManager在android通知里

复制代码
@SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            // 要做的事情
            Bitmap btm = BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_launcher);
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                    BookUpdateService.this)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle("文云阁").setContentText("您的书架有新更新");
            mBuilder.setTicker("您的书架有新更新");// 第一次提示消息的时候显示在通知栏上
            mBuilder.setNumber(msg.arg2);
            mBuilder.setLargeIcon(btm);
            mBuilder.setAutoCancel(true);// 自己维护通知的消失

            // 构建一个Intent
            Intent resultIntent = new Intent(BookUpdateService.this,
                    MainActivity.class);
            // 封装一个Intent
            PendingIntent resultPendingIntent = PendingIntent.getActivity(
                    BookUpdateService.this, 0, resultIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            // 设置通知主题的意图
            mBuilder.setContentIntent(resultPendingIntent);
            // 获取通知管理器对象
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(0, mBuilder.build());
        }
    };
复制代码

 

 3、系统更新

 屌丝的人生你不懂,做出来的东西也就是马马虎虎的,总有bug,总要升级

复制代码
private void notNewVersionShow() {
        StringBuffer sb = new StringBuffer();
        sb.append("当前版本:");
        sb.append(BaseActivity.getVerName(ToolActivity.this));
        sb.append(" Code:");
        sb.append(BaseActivity.getVerCode(ToolActivity.this));
        sb.append(",/n已是最新版,无需更新!");
        Dialog dialog = new AlertDialog.Builder(ToolActivity.this)
                .setTitle("软件更新").setMessage(sb.toString())// 设置内容
                .setPositiveButton("确定",// 设置确定按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                            }
                        }).create();// 创建
        // 显示对话框
        dialog.show();
    }

    private void doNewVersionUpdate() {
        StringBuffer sb = new StringBuffer();
        sb.append("当前版本:");
        sb.append(BaseActivity.getVerName(ToolActivity.this));
        sb.append(" Code:");
        sb.append(BaseActivity.getVerCode(ToolActivity.this));
        sb.append(", 发现新版本:");
        sb.append(name);
        sb.append(" Code:");
        sb.append(code);
        sb.append(", 是否更新?");
        Dialog dialog = new AlertDialog.Builder(ToolActivity.this)
                .setTitle("软件更新").setMessage(sb.toString())
                // 设置内容
                .setPositiveButton("更新",// 设置确定按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                pBar = new ProgressDialog(ToolActivity.this);
                                pBar.setTitle("正在下载");
                                pBar.setMessage("请稍候...");
                                pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                                downFile();
                            }
                        }).create();// 创建
        // .setNegativeButton("暂不更新",
        // new DialogInterface.OnClickListener() {
        // public void onClick(DialogInterface dialog,
        // int whichButton) {
        // // 点击"取消"按钮之后退出程序
        //
        // }
        // }).create();// 创建
        // 显示对话框
        dialog.show();
    }

    ProgressDialog pBar;

    void downFile() {
        pBar.show();
        new Thread() {
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(getResources().getString(
                        R.string.site_url)
                        + "wenyunge.apk");
                HttpResponse response;
                try {
                    response = client.execute(get);
                    HttpEntity entity = response.getEntity();
                    long length = entity.getContentLength();
                    InputStream is = entity.getContent();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File file = new File(
                                Environment.getExternalStorageDirectory(),
                                "wenyunge.apk");
                        fileOutputStream = new FileOutputStream(file);
                        byte[] buf = new byte[1024];
                        int ch = -1;
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);
                            if (length > 0) {
                            }
                        }
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    down();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    void down() {
        handler.post(new Runnable() {
            public void run() {
                pBar.cancel();
                update();
            }
        });
    }

    void update() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File f = new File(Environment.getExternalStorageDirectory(),
                "wenyunge.apk");
        if (f.exists()) {
            intent.setDataAndType(Uri.fromFile(f),
                    "application/vnd.android.package-archive");
            startActivity(intent);
        }
    }
复制代码

其实这段代码是我看别人的,那兄弟的网址不记得了,不然给大家贴出来
我跟大家分享个错误,在升级app的时候提示,在下面

 4、an existing package by the same name with a conflicting signature is already installed
 

是因为新app签名和原来的不同

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值