Gradle peer not authenticated

Gradle编译时报错:gradle:peer not authenticated
处理方法:
Change your repository syntax to one of the following

[codesyntax lang="java"]

repositories {
jcenter {
url "http://jcenter.bintray.com/"
}
}

repositories {
maven {
url "http://repo1.maven.org/maven2"
}
}


[/codesyntax]

PS:大概意思就是修改 项目build.gradle文件,repostories修改成上边的任意一条的内容,就可以了

Android AlarmManager实现不间断轮询服务[转载]

来源:http://blog.csdn.net/ryantang03/article/details/9317499

写在这里是为了自己用来保持CPU不休眠做参考,内容有删减,在此感谢原作者

更多信息请看这里(原文地址)

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

在消息的获取上是选择轮询还是推送得根据实际的业务需要来技术选型,例如对消息实时性比较高的需求,比如微博新通知或新闻等那就最好是用推送了。但如果只是一般的消息检测比如更新检查,可能是半个小时或一个小时一次,那用轮询也是一个不错的选择,因为不需要额外搭建推送服务器,不用额外配置推送服务。另外推送现在一般以维持长连接的方式实现,在手机客户端也会耗费一定的电量。今天就介绍一个在Android上实现轮询机制的方法——使用AlarmManager

AlarmManager在Android中主要用来定时处理一个事件或是定期处理一个事件,比如闹钟应用就是使用AlarmManager来实现的,我们今天要使用AlarmManager的定期执行功能来实现轮询的功能。对于定期执行任务也可以用Timer和TimerTask来实现,也可以开一个Service在Thread里面以while循环来实现。但最好的方案还是选用AlarmManager,这里涉及一个Android系统锁的机制,即系统在检测到一段时间没有活跃以后,会关闭一些不必要的服务来减少资源和电量消耗。使用Timer和Service来实现的话很可能出现的情况就是屏幕熄灭后一段时间,服务就被停止了,当然轮询也就被停止了。

部分代码:

一、新建轮询工具类PollingUtils.java

public class PollingUtils {

    //开启轮询服务
    public static void startPollingService(Context context, int seconds, Class<?> cls,String action) {
        //获取AlarmManager系统服务
        AlarmManager manager = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
       
        //包装需要执行Service的Intent
        Intent intent = new Intent(context, cls);
        intent.setAction(action);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
       
        //触发服务的起始时间
        long triggerAtTime = SystemClock.elapsedRealtime();
       
        //使用AlarmManger的setRepeating方法设置定期执行的时间间隔(seconds秒)和需要执行的Service
        manager.setRepeating(AlarmManager.ELAPSED_REALTIME, triggerAtTime,
                seconds * 1000, pendingIntent);
    }

    //停止轮询服务
    public static void stopPollingService(Context context, Class<?> cls,String action) {
        AlarmManager manager = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, cls);
        intent.setAction(action);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        //取消正在执行的服务
        manager.cancel(pendingIntent);
    }
}

二、构建轮询任务执行PollingService.java

public class PollingService extends Service {

    public static final String ACTION = "com.ryantang.service.PollingService";
   
    private Notification mNotification;
    private NotificationManager mManager;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        initNotifiManager();
    }
   
    @Override
    public void onStart(Intent intent, int startId) {
        new PollingThread().start();
    }

    //初始化通知栏配置
    private void initNotifiManager() {
        mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        int icon = R.drawable.ic_launcher;
        mNotification = new Notification();
        mNotification.icon = icon;
        mNotification.tickerText = "New Message";
        mNotification.defaults |= Notification.DEFAULT_SOUND;
        mNotification.flags = Notification.FLAG_AUTO_CANCEL;
    }

    //弹出Notification
    private void showNotification() {
        mNotification.when = System.currentTimeMillis();
        //Navigator to the new activity when click the notification title
        Intent i = new Intent(this, MessageActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i,
                Intent.FLAG_ACTIVITY_NEW_TASK);
        mNotification.setLatestEventInfo(this,
                getResources().getString(R.string.app_name), "You have new message!", pendingIntent);
        mManager.notify(0, mNotification);
    }

    /**
     * Polling thread
     * 模拟向Server轮询的异步线程
     * @Author Ryan
     * @Create 2013-7-13 上午10:18:34
     */
    int count = 0;
    class PollingThread extends Thread {
        @Override
        public void run() {
            System.out.println("Polling...");
            count ++;
            //当计数能被5整除时弹出通知
            if (count % 5 == 0) {
                showNotification();
                System.out.println("New message!");
            }
        }
    }
   
    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("Service:onDestroy");
    }

}

三、在MainActivity.java中开启和停止PollingService

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Start polling service
        System.out.println("Start polling service...");
        PollingUtils.startPollingService(this, 5, PollingService.class, PollingService.ACTION);
    }
   
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //Stop polling service
        System.out.println("Stop polling service...");
        PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);
    }

}

四、运行效果

运行工程后可以在控制台输出看到,每隔5s就发出一个通知,退出Activity时,轮询服务就停止了,达到了我们事先期望的效果,并且锁屏后很长一段时间也不会停止服务,因为AlarmManager是系统及服务。(Demo效果图略)

当进入消息详情Activity时,顶部状态栏的消息通知就会取消,使用如下方式也可以取消状态栏顶部的消息通知显示:

NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancelAll();

以上就实现了使用AlarmManger实现轮询的一种方式,有不足或缺陷的地方欢迎大家留言补充,以上代码只是部分,需要工程源码的同学可以到Github上Clone:https://github.com/tangren03/RTPollingDemo

Android向桌面添加快捷方式,使其指向特定的网页


出处:http://www.cnblogs.com/wanyao/archive/2011/11/27/2265333.html




/*


          * 在桌面添加快捷方式


          * @param      icon         快捷方式图标


          * @param      name      快捷方式名称


          * @param      uri           快捷方式的intent Uri


          */


         public void addShortcut(Parcelable icon, String name, Uri uri){


                   Intent intentAddShortcut = new Intent(ACTION_ADD_SHORTCUT);


                   //添加名称


                   intentAddShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);


                   //添加图标


                   intentAddShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);


                   //设置Launcher的Uri数据


                   Intent intentLauncher = new Intent();


                   intentLauncher.setData(uri);


                   //添加快捷方式的启动方法


                   intentAddShortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intentLauncher);


                   sendBroadcast(intentAddShortcut);


         }


当然,你还需要添加一个permission


<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />


这里第一个参数Parcelable类型的icon如何获得呢,以下举个例子从Drawable文件夹中获取图片。


Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);




Android如何调用系统默认浏览器访问


一、启动android默认浏览器



Intent intent= new Intent();


  intent.setAction("android.intent.action.VIEW");


  Uri content_url = Uri.parse("http://www.cxybl.com");


  intent.setData(content_url);


  startActivity(intent);


这样子,android就可以调用起手机默认的浏览器访问。


二、指定相应的浏览器访问


1、指定android自带的浏览器访问


( “com.android.browser”:packagename   ;“com.android.browser.BrowserActivity”:启动主activity)


                Intent intent= new Intent();


                intent.setAction("android.intent.action.VIEW");


                Uri content_url = Uri.parse("http://www.cxybl.com");


                intent.setData(content_url);


                intent.setClassName("com.android.browser","com.android.browser.BrowserActivity");


                startActivity(intent);


ANDROID代码实现APK文件的安装与卸载

http://www.cnblogs.com/Greenwood/archive/2011/03/09/1979268.html



Android程序使用代码的安装和卸载!!!


安装:


String str = "/CanavaCancel.apk";


String fileName = Environment.getExternalStorageDirectory() + str;


Intent intent = new Intent(Intent.ACTION_VIEW);


 intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");


startActivity(intent);


卸载:



Uri packageURI = Uri.parse("package:com.demo.CanavaCancel");


Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);


startActivity(uninstallIntent);



Environment拥有一些可以获取环境变量的方法


package:com.demo.CanavaCancel 这个形式是 package:程序完整的路径 (包名+程序名).







//下载apk程序代码
protected File downLoadFile(String httpUrl) {
// TODO Auto-generated method stub
final String fileName = "updata.apk";
File tmpFile = new File("/sdcard/update");
if (!tmpFile.exists()) {
tmpFile.mkdir();
}
final File file = new File("/sdcard/update/" + fileName);

try {
URL url = new URL(httpUrl);
try {
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[256];
conn.connect();
double count = 0;
if (conn.getResponseCode() >= 400) {
Toast.makeText(Main.this, "连接超时", Toast.LENGTH_SHORT)
.show();
} else {
while (count <= 100) {
if (is != null) {
int numRead = is.read(buf);
if (numRead <= 0) {
break;
} else {
fos.write(buf, 0, numRead);
}

} else {
break;
}

}
}

conn.disconnect();
fos.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block

e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block

e.printStackTrace();
}

return file;
}
//打开APK程序代码

private void openFile(File file) {
// TODO Auto-generated method stub
Log.e("OpenFile", file.getName());
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(intent);
}