当前位置: 编程技术>移动开发
本页文章导读:
▪WindowManager兑现悬浮窗口 WindowManager实现悬浮窗口
Android中悬浮窗口的实现原理和示例代码 http://www.xsmile.net/?p=404 调用WindowManager,并设置WindowManager.LayoutParams的相关属性,通过WindowManager的addView方法创建View,这样产.........
▪ 5个步骤配置coreplot 五个步骤配置coreplot
Five Steps to CorePlot1. Copy the CorePlotSDK directory to ~/Library/SDKs/2. Add to your project's .PCH file:#import <CorePlot/CorePlot.h>3. Open Project -> Edit Project Settings and for All Configurations: 3a. .........
▪ 惯用代码合集二 常用代码合集二
=====================================================1.使用剪切板可以直接实现数据的传输 ClipboardManagerview plaincopy to clipboardprint?public void setClipboard(String text) { ClipboardManager clipboar.........
[1]WindowManager兑现悬浮窗口
来源: 互联网 发布时间: 2014-02-18
WindowManager实现悬浮窗口
Android中悬浮窗口的实现原理和示例代码
http://www.xsmile.net/?p=404
调用WindowManager,并设置WindowManager.LayoutParams的相关属性,通过WindowManager的addView方法创建View,这样产生出来的View根据WindowManager.LayoutParams属性不同,效果也就不同了。比如创建系统顶级窗口,实现悬浮窗口效果!
WindowManager的方法很简单,基本用到的就三个addView,removeView,updateViewLayout。
而WindowManager.LayoutParams的属性就多了,非常丰富,具体请查看SDK文档。这里给出Android中的WindowManager.java源码,可以具体看一下。
WindowManager 的源码地址:
http://www.netmite.com/android/mydroid/frameworks/base/core/java/android/view/WindowManager.java
以下代码请仅供演示:
Java代码
public class myFloatView extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bb=new Button(getApplicationContext());
WindowManager wm=(WindowManager)getApplicationContext().getSystemService("window");
WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
wmParams.type=2002; //type是关键,这里的2002表示系统级窗口,你也可以试试2003。
wmParams.format=1;
/**
*这里的flags也很关键
*代码实际是wmParams.flags |= FLAG_NOT_FOCUSABLE;
*40的由来是wmParams的默认属性(32)+ FLAG_NOT_FOCUSABLE(8)
*/
wmParams.flags=40;
wmParams.width=40;
wmParams.height=40;
wm.addView(bb, wmParams);//创建View
}
}
public class myFloatView extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bb=new Button(getApplicationContext());
WindowManager wm=(WindowManager)getApplicationContext().getSystemService("window");
WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
wmParams.type=2002; //type是关键,这里的2002表示系统级窗口,你也可以试试2003。
wmParams.format=1;
/**
*这里的flags也很关键
*代码实际是wmParams.flags |= FLAG_NOT_FOCUSABLE;
*40的由来是wmParams的默认属性(32)+ FLAG_NOT_FOCUSABLE(8)
*/
wmParams.flags=40;
wmParams.width=40;
wmParams.height=40;
wm.addView(bb, wmParams);//创建View
}
}
PS:本代码在Android2.3下测试无错(从API Level来看,实际上android1.5都可行)!另外别忘了在AndroidManifest.xml文件中加入如下权限:
Xml代码
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
关于代码中wmParams.type的值的问题,下面给出一些数值参考:
/**
* Window type: the status bar. There can be only one status bar
* window; it is placed at the top of the screen, and all other
* windows are shifted down so they are below it.
*/
public static final int TYPE_STATUS_BAR = FIRST_SYSTEM_WINDOW;
/**
* Window type: the search bar. There can be only one search bar
* window; it is placed at the top of the screen.
*/
public static final int TYPE_SEARCH_BAR = FIRST_SYSTEM_WINDOW+1;
/**
* Window type: phone. These are non-application windows providing
* user interaction with the phone (in particular incoming calls).
* These windows are normally placed above all applications, but behind
* the status bar.
*/
public static final int TYPE_PHONE = FIRST_SYSTEM_WINDOW+2;
/**
* Window type: system window, such as low power alert. These windows
* are always on top of application windows.
*/
public static final int TYPE_SYSTEM_ALERT = FIRST_SYSTEM_WINDOW+3;
/**
* Window type: keyguard window.
*/
public static final int TYPE_KEYGUARD = FIRST_SYSTEM_WINDOW+4;
/**
* Window type: transient notifications.
*/
public static final int TYPE_TOAST = FIRST_SYSTEM_WINDOW+5;
/**
* Window type: system overlay windows, which need to be displayed
* on top of everything else. These windows must not take input
* focus, or they will interfere with the keyguard.
*/
public static final int TYPE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW+6;
/**
* Window type: priority phone UI, which needs to be displayed even if
* the keyguard is active. These windows must not take input
* focus, or they will interfere with the keyguard.
*/
public static final int TYPE_PRIORITY_PHONE = FIRST_SYSTEM_WINDOW+7;
/**
* Window type: panel that slides out from the status bar
*/
public static final int TYPE_STATUS_BAR_PANEL = FIRST_SYSTEM_WINDOW+8;
/**
* Window type: panel that slides out from the status bar
*/
public static final int TYPE_SYSTEM_DIALOG = FIRST_SYSTEM_WINDOW+8;
/**
* Window type: dialogs that the keyguard shows
*/
public static final int TYPE_KEYGUARD_DIALOG = FIRST_SYSTEM_WINDOW+9;
/**
* Window type: internal system error windows, appear on top of
* everything they can.
*/
public static final int TYPE_SYSTEM_ERROR = FIRST_SYSTEM_WINDOW+10;
/**
* End of types of system windows.
*/
public static final int LAST_SYSTEM_WINDOW = 2999;
---------------------------------
这个FIRST_SYSTEM_WINDOW的值就是2000。2003和2002的区别就在于2003类型的View比2002类型的还要top,能显示在系统下拉状态栏之上!
可以看出来,2002的值的含义其实就是2000+2。数值2000的含义就是系统级窗口,2002和2003的区别就是 2003 比 2002还要更上一层!比如,type为2003的view,能显示在手机下拉状态栏之上!
而关于flags等其他的属性请参考SDK文档
Android中悬浮窗口的实现原理和示例代码
http://www.xsmile.net/?p=404
调用WindowManager,并设置WindowManager.LayoutParams的相关属性,通过WindowManager的addView方法创建View,这样产生出来的View根据WindowManager.LayoutParams属性不同,效果也就不同了。比如创建系统顶级窗口,实现悬浮窗口效果!
WindowManager的方法很简单,基本用到的就三个addView,removeView,updateViewLayout。
而WindowManager.LayoutParams的属性就多了,非常丰富,具体请查看SDK文档。这里给出Android中的WindowManager.java源码,可以具体看一下。
WindowManager 的源码地址:
http://www.netmite.com/android/mydroid/frameworks/base/core/java/android/view/WindowManager.java
以下代码请仅供演示:
Java代码
public class myFloatView extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bb=new Button(getApplicationContext());
WindowManager wm=(WindowManager)getApplicationContext().getSystemService("window");
WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
wmParams.type=2002; //type是关键,这里的2002表示系统级窗口,你也可以试试2003。
wmParams.format=1;
/**
*这里的flags也很关键
*代码实际是wmParams.flags |= FLAG_NOT_FOCUSABLE;
*40的由来是wmParams的默认属性(32)+ FLAG_NOT_FOCUSABLE(8)
*/
wmParams.flags=40;
wmParams.width=40;
wmParams.height=40;
wm.addView(bb, wmParams);//创建View
}
}
public class myFloatView extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bb=new Button(getApplicationContext());
WindowManager wm=(WindowManager)getApplicationContext().getSystemService("window");
WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
wmParams.type=2002; //type是关键,这里的2002表示系统级窗口,你也可以试试2003。
wmParams.format=1;
/**
*这里的flags也很关键
*代码实际是wmParams.flags |= FLAG_NOT_FOCUSABLE;
*40的由来是wmParams的默认属性(32)+ FLAG_NOT_FOCUSABLE(8)
*/
wmParams.flags=40;
wmParams.width=40;
wmParams.height=40;
wm.addView(bb, wmParams);//创建View
}
}
PS:本代码在Android2.3下测试无错(从API Level来看,实际上android1.5都可行)!另外别忘了在AndroidManifest.xml文件中加入如下权限:
Xml代码
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
关于代码中wmParams.type的值的问题,下面给出一些数值参考:
/**
* Window type: the status bar. There can be only one status bar
* window; it is placed at the top of the screen, and all other
* windows are shifted down so they are below it.
*/
public static final int TYPE_STATUS_BAR = FIRST_SYSTEM_WINDOW;
/**
* Window type: the search bar. There can be only one search bar
* window; it is placed at the top of the screen.
*/
public static final int TYPE_SEARCH_BAR = FIRST_SYSTEM_WINDOW+1;
/**
* Window type: phone. These are non-application windows providing
* user interaction with the phone (in particular incoming calls).
* These windows are normally placed above all applications, but behind
* the status bar.
*/
public static final int TYPE_PHONE = FIRST_SYSTEM_WINDOW+2;
/**
* Window type: system window, such as low power alert. These windows
* are always on top of application windows.
*/
public static final int TYPE_SYSTEM_ALERT = FIRST_SYSTEM_WINDOW+3;
/**
* Window type: keyguard window.
*/
public static final int TYPE_KEYGUARD = FIRST_SYSTEM_WINDOW+4;
/**
* Window type: transient notifications.
*/
public static final int TYPE_TOAST = FIRST_SYSTEM_WINDOW+5;
/**
* Window type: system overlay windows, which need to be displayed
* on top of everything else. These windows must not take input
* focus, or they will interfere with the keyguard.
*/
public static final int TYPE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW+6;
/**
* Window type: priority phone UI, which needs to be displayed even if
* the keyguard is active. These windows must not take input
* focus, or they will interfere with the keyguard.
*/
public static final int TYPE_PRIORITY_PHONE = FIRST_SYSTEM_WINDOW+7;
/**
* Window type: panel that slides out from the status bar
*/
public static final int TYPE_STATUS_BAR_PANEL = FIRST_SYSTEM_WINDOW+8;
/**
* Window type: panel that slides out from the status bar
*/
public static final int TYPE_SYSTEM_DIALOG = FIRST_SYSTEM_WINDOW+8;
/**
* Window type: dialogs that the keyguard shows
*/
public static final int TYPE_KEYGUARD_DIALOG = FIRST_SYSTEM_WINDOW+9;
/**
* Window type: internal system error windows, appear on top of
* everything they can.
*/
public static final int TYPE_SYSTEM_ERROR = FIRST_SYSTEM_WINDOW+10;
/**
* End of types of system windows.
*/
public static final int LAST_SYSTEM_WINDOW = 2999;
---------------------------------
这个FIRST_SYSTEM_WINDOW的值就是2000。2003和2002的区别就在于2003类型的View比2002类型的还要top,能显示在系统下拉状态栏之上!
可以看出来,2002的值的含义其实就是2000+2。数值2000的含义就是系统级窗口,2002和2003的区别就是 2003 比 2002还要更上一层!比如,type为2003的view,能显示在手机下拉状态栏之上!
而关于flags等其他的属性请参考SDK文档
[2] 5个步骤配置coreplot
来源: 互联网 发布时间: 2014-02-18
五个步骤配置coreplot
Five Steps to CorePlot
1. Copy the CorePlotSDK directory to ~/Library/SDKs/
2. Add to your project's .PCH file:
#import <CorePlot/CorePlot.h>
3. Open Project -> Edit Project Settings and for All Configurations:
3a. Add to Additional SDKS:
$HOME/Library/SDKs/CorePlotSDK/${PLATFORM_NAME}.sdk
3b. Add to Other Linker Flags:
-ObjC -all_load -lCorePlot
4. Add the QuartzCore framework to the project.
5. Add a CPGraph to your application.
最后不要忘记“项目Build Info中,C/C++ Compiler Version必须使用LLVM GCC 4.2,而不能使用GCC 4.2”!
Five Steps to CorePlot
1. Copy the CorePlotSDK directory to ~/Library/SDKs/
2. Add to your project's .PCH file:
#import <CorePlot/CorePlot.h>
3. Open Project -> Edit Project Settings and for All Configurations:
3a. Add to Additional SDKS:
$HOME/Library/SDKs/CorePlotSDK/${PLATFORM_NAME}.sdk
3b. Add to Other Linker Flags:
-ObjC -all_load -lCorePlot
4. Add the QuartzCore framework to the project.
5. Add a CPGraph to your application.
最后不要忘记“项目Build Info中,C/C++ Compiler Version必须使用LLVM GCC 4.2,而不能使用GCC 4.2”!
[3] 惯用代码合集二
来源: 互联网 发布时间: 2014-02-18
常用代码合集二
=====================================================
1.使用剪切板可以直接实现数据的传输 ClipboardManager
view plaincopy to clipboardprint?
public void setClipboard(String text) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
public String getClipboard() {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
return clipboard.getText().toString();
}
public void setClipboard(String text) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
public String getClipboard() {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
return clipboard.getText().toString();
}
有关剪切板的数据类型可以通过 该类的boolean hasText() 方法判断。
2.SharedPreferences
SharedPreferences是以键值对来存储应用程序的配置信息的一种方式,它只能存储基本数据类型。一个程序的配置文件仅可以在本应用程序中使用,或者说只能在同一个包内使用,不能在不同的包之间使用。 实际上SharedPreferences是采用了XML格式将数据存储到设备中,在DDMS中的File Explorer中的/data/data/<package name>/shares_prefs下。
返回值 SharedPreferences
函数 Context.getSharedPreferences(String name,int mode)
备注
name为本组件的配置文件名(如果想要与本应用程序的其他组件共享此配置文件,可以用这个名字来检索到这个配置文件)。
mode为操作模式,默认的模式为0或MODE_PRIVATE,还可以使用MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE。
返回值 SharedPreferences
函数 Activity.getPreferences(int mode)
备注
配置文件仅可以被调用的Activity使用。
mode为操作模式,默认的模式为0或MODE_PRIVATE,还可以使用MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE。
如果要读取配置文件信息,只需要直接使用SharedPreferences对象的getXXX()方法即可,而如果要写入配置信息,则必须先调用SharedPreferences对象的edit()方法,使其处于可编辑状态,然后再调用putXXX()方法写入配置信息,最后调用commit()方法提交更改后的配置文件。
以下是示例代码:
view plaincopy to clipboardprint?
import android.app.Activity;
import android.content.SharedPreferences;
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
. . .
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
//载入配置文件
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//或者使用 SharedPreferences settings = getPreferences(0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
//写入配置文件。可以使用SharedPreferences.Editor来辅助解决。
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
editor.commit(); //一定要记得提交
//或者再简单化一可以这样写
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
setting.edit().putBoolean(“silentMode”,mSilentMode).commit();
}
}
import android.app.Activity;
import android.content.SharedPreferences;
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
. . .
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
//载入配置文件
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//或者使用 SharedPreferences settings = getPreferences(0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
//写入配置文件。可以使用SharedPreferences.Editor来辅助解决。
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
editor.commit(); //一定要记得提交
//或者再简单化一可以这样写
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
setting.edit().putBoolean(“silentMode”,mSilentMode).commit();
}
}
=====================================================================================
添加快捷图标
2.drawable-hdpi,drawable-ldpi,drawable-mdpi有什么区别?
答:主要是为了支持多分辨率的.
hdpi里面主要放高分辨率的图片,如WVGA (480x800),FWVGA (480x854)
mdpi 里面主要放中等分辨率的图片,如HVGA (320x480)
ldpi里面主要放低分辨率的图片,如QVGA (240x320)
系统会根据机器的分辨率来分别到这几个文件夹里面去找对应的图片
所以在开发程序时为了兼容不同平台不同屏幕,建议各自文件夹根据需求均存放不同版本图片
3.Android 判断SdCard是否存在?
答:if (android .os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
4.Android 删除文件为什么总是报错,删除不了?
答:Android自1.6版本以后,引入了一个权限,让用户可以修改外部存储设备文件,这个问题只要我们在Manifest.xml加一个permission节点就可以解决了:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
5.Android 如何判断系统语言?
view plaincopy to clipboardprint?
01.private String getLocaleLanguage() {
02. Locale l = Locale.getDefault();
03. return String.format("%s-%s", l.getLanguage(), l.getCountry());
04. }
private String getLocaleLanguage() {
Locale l = Locale.getDefault();
return String.format("%s-%s", l.getLanguage(), l.getCountry());
}
返回en-US(也可能是en-XX)表示英语,zh-CN表示简体中文,zh-TW表示繁体中文,以此类推。
6.Android 如何判断系统时间是12小时制还是24小时制?
view plaincopy to clipboardprint?
01.ContentResolver cv = this.getContentResolver();
02. String strTimeFormat = android.provider.Settings.System.getString(cv,
03. android.provider.Settings.System.TIME_12_24);
ContentResolver cv = this.getContentResolver();
String strTimeFormat = android.provider.Settings.System.getString(cv,
android.provider.Settings.System.TIME_12_24);
返回值strTimeFormat有三种可能一种是NULL,一种是24,另外一种是12.
以上来自CSDN博客,转载请标明出处:http://blog.csdn.net/Android_Tutor/archive/2010/05/27/5629262.aspx
错误集:
1. UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.IllegalArgumentException: already added:Lorg/xmlpull/v1/XmlPullParser;
....
Conversion to Dalvik format failed with error 1
i solved the problem.
i seems that is have two jars on my buildpath that include the same package and classes.
i used smack.jar and android_maps_lib-1.0.2
delete this package from one jar solved the problem.
4. m访问网络(httppost httpget) 遇到本地pc设置有代理的问题时,依照一般的连接方式有错误
需在模拟器上添加:
System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", proxyIp);
System.getProperties().put("proxyPort", proxyPort);
第一行通知 Java 您要通过代理进行连接,第二行指定代理所在的机器,第三行指定代理监听的端口
5.android 正确获取屏幕像素大小
DisplayMetrics dm =new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int widthPixels= dm.widthPixels;
int heightPixels= dm.heightPixels;
float density = dm.density;
int screenWidth = widthPixels * density ;
int screenHeight = heightPixels * density ;
6. 本地assets目录下的html文件:web2.loadUrl("file:///android_asset/index.html") ;
InputStreamReader inputReader = new InputStreamReader( getResources().getAssets().open(fileName) );
InputStreamReader inputReader = new InputStreamReader(getResources().openRawResource(R.raw.test1));
7. 检查网络是否可用:
public static boolean chkConnection() {
ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
cwjManager.getActiveNetworkInfo();
if (cwjManager.getActiveNetworkInfo() !=null) {
return cwjManager.getActiveNetworkInfo().isAvailable();
}
return false;
}
8.获取正在运行的任务,
首先需要声明一个活动对象管理器(ActivityManager) 所有的活动任务都属于此,然后通过获取服务可以得到所有的活动对象,然后通过活动对象可以得到所有运行的任务和服务,当然要获取服务和任务是使用不同的方法,但是方式是一样的。下面是获取代码:
代码 void getTask() {
ActivityManager activityManager;
try {
activityManager = (ActivityManager) this
.getSystemService(ACTIVITY_SERVICE);
arylistTask =new ArrayList<String>();
List<ActivityManager.RunningTaskInfo> mRunningTasks =
activityManager.getRunningTasks(30); //30表示获取的最大数
/* 以循环及baseActivity方式取得任务名称与ID */
for (RunningTaskInfo amTask : mRunningTasks)
{
Log.d("TaskInfo", amTask.baseActivity.getClassName()+"("+amTask.id+")");
}
//获取服务
List<RunningServiceInfo> mserviceTasks =
activityManager.getRunningServices(30);
/* 以循环方式取得任务名称与ID */
for (RunningServiceInfo serinfo : mserviceTasks)
{
Log.d("TaskServerInfo", serinfo.process+"("+serinfo.pid+")");
}
}
catch (Exception e)
{
}
9.Android 获取MIEI ISMI Sim卡串号等信息
TelephonyManager telephonemanage = (TelephonyManager) getWindow().getContext().getSystemService(Context.TELEPHONY_SERVICE);
try {
edit1.setText("MIEI: " + telephonemanage.getDeviceId()+ "\n SimSSN " + telephonemanage.getSimSerialNumber()+ "\n IMSI " + telephonemanage.getSubscriberId());
} catch (Exception e) {
edit1.setText(e.getMessage());
}
10.添加快捷图标
代码 privatevoid addShortcut(){
Intent shortcut =new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//快捷方式的名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
// shortcut.putExtra("duplicate", false); //不允许重复创建
//指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer
//注意: ComponentName的第二个参数必须加上点号(.),否则快捷方式无法启动相应程序
// ComponentName comp = new ComponentName(this.getPackageName(), "."+this.getLocalClassName());
// shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this,ShortcutTest.class));
//快捷方式的图标
ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
sendBroadcast(shortcut);
}
shortcut.putExtra("duplicate", false); //表示的为不允许重复设置
此种代码,直接添加到桌面上,并且也在上图所示的地方显示,但是此需要添加下面的权限:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
11. 防止锁屏:
PowerManager mPowerManager = (PowerManager) getSystemService(POWER_SERVICE); //电源控制,比如防锁屏
WakeLock mWakeLock= mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass()
.getName()); //处理屏幕防止锁屏
mWakeLock.acquire(); //恢复时解除锁屏
mWakeLock.release();
12. Drawable,Bitmap相互转换:
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
//canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
Resources res=getResources();
Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);
private byte[] Bitmap2Bytes(Bitmap bm){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
private Bitmap Bytes2Bimap(byte[] b){
if(b.length!=0){
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
else {
return null;
}
}
=====================================================
1.使用剪切板可以直接实现数据的传输 ClipboardManager
view plaincopy to clipboardprint?
public void setClipboard(String text) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
public String getClipboard() {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
return clipboard.getText().toString();
}
public void setClipboard(String text) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
public String getClipboard() {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
return clipboard.getText().toString();
}
有关剪切板的数据类型可以通过 该类的boolean hasText() 方法判断。
2.SharedPreferences
SharedPreferences是以键值对来存储应用程序的配置信息的一种方式,它只能存储基本数据类型。一个程序的配置文件仅可以在本应用程序中使用,或者说只能在同一个包内使用,不能在不同的包之间使用。 实际上SharedPreferences是采用了XML格式将数据存储到设备中,在DDMS中的File Explorer中的/data/data/<package name>/shares_prefs下。
返回值 SharedPreferences
函数 Context.getSharedPreferences(String name,int mode)
备注
name为本组件的配置文件名(如果想要与本应用程序的其他组件共享此配置文件,可以用这个名字来检索到这个配置文件)。
mode为操作模式,默认的模式为0或MODE_PRIVATE,还可以使用MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE。
返回值 SharedPreferences
函数 Activity.getPreferences(int mode)
备注
配置文件仅可以被调用的Activity使用。
mode为操作模式,默认的模式为0或MODE_PRIVATE,还可以使用MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE。
如果要读取配置文件信息,只需要直接使用SharedPreferences对象的getXXX()方法即可,而如果要写入配置信息,则必须先调用SharedPreferences对象的edit()方法,使其处于可编辑状态,然后再调用putXXX()方法写入配置信息,最后调用commit()方法提交更改后的配置文件。
以下是示例代码:
view plaincopy to clipboardprint?
import android.app.Activity;
import android.content.SharedPreferences;
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
. . .
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
//载入配置文件
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//或者使用 SharedPreferences settings = getPreferences(0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
//写入配置文件。可以使用SharedPreferences.Editor来辅助解决。
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
editor.commit(); //一定要记得提交
//或者再简单化一可以这样写
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
setting.edit().putBoolean(“silentMode”,mSilentMode).commit();
}
}
import android.app.Activity;
import android.content.SharedPreferences;
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
. . .
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
//载入配置文件
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//或者使用 SharedPreferences settings = getPreferences(0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
//写入配置文件。可以使用SharedPreferences.Editor来辅助解决。
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
editor.commit(); //一定要记得提交
//或者再简单化一可以这样写
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
setting.edit().putBoolean(“silentMode”,mSilentMode).commit();
}
}
=====================================================================================
添加快捷图标
2.drawable-hdpi,drawable-ldpi,drawable-mdpi有什么区别?
答:主要是为了支持多分辨率的.
hdpi里面主要放高分辨率的图片,如WVGA (480x800),FWVGA (480x854)
mdpi 里面主要放中等分辨率的图片,如HVGA (320x480)
ldpi里面主要放低分辨率的图片,如QVGA (240x320)
系统会根据机器的分辨率来分别到这几个文件夹里面去找对应的图片
所以在开发程序时为了兼容不同平台不同屏幕,建议各自文件夹根据需求均存放不同版本图片
3.Android 判断SdCard是否存在?
答:if (android .os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
4.Android 删除文件为什么总是报错,删除不了?
答:Android自1.6版本以后,引入了一个权限,让用户可以修改外部存储设备文件,这个问题只要我们在Manifest.xml加一个permission节点就可以解决了:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
5.Android 如何判断系统语言?
view plaincopy to clipboardprint?
01.private String getLocaleLanguage() {
02. Locale l = Locale.getDefault();
03. return String.format("%s-%s", l.getLanguage(), l.getCountry());
04. }
private String getLocaleLanguage() {
Locale l = Locale.getDefault();
return String.format("%s-%s", l.getLanguage(), l.getCountry());
}
返回en-US(也可能是en-XX)表示英语,zh-CN表示简体中文,zh-TW表示繁体中文,以此类推。
6.Android 如何判断系统时间是12小时制还是24小时制?
view plaincopy to clipboardprint?
01.ContentResolver cv = this.getContentResolver();
02. String strTimeFormat = android.provider.Settings.System.getString(cv,
03. android.provider.Settings.System.TIME_12_24);
ContentResolver cv = this.getContentResolver();
String strTimeFormat = android.provider.Settings.System.getString(cv,
android.provider.Settings.System.TIME_12_24);
返回值strTimeFormat有三种可能一种是NULL,一种是24,另外一种是12.
以上来自CSDN博客,转载请标明出处:http://blog.csdn.net/Android_Tutor/archive/2010/05/27/5629262.aspx
错误集:
1. UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.IllegalArgumentException: already added:Lorg/xmlpull/v1/XmlPullParser;
....
Conversion to Dalvik format failed with error 1
i solved the problem.
i seems that is have two jars on my buildpath that include the same package and classes.
i used smack.jar and android_maps_lib-1.0.2
delete this package from one jar solved the problem.
4. m访问网络(httppost httpget) 遇到本地pc设置有代理的问题时,依照一般的连接方式有错误
需在模拟器上添加:
System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", proxyIp);
System.getProperties().put("proxyPort", proxyPort);
第一行通知 Java 您要通过代理进行连接,第二行指定代理所在的机器,第三行指定代理监听的端口
5.android 正确获取屏幕像素大小
DisplayMetrics dm =new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int widthPixels= dm.widthPixels;
int heightPixels= dm.heightPixels;
float density = dm.density;
int screenWidth = widthPixels * density ;
int screenHeight = heightPixels * density ;
6. 本地assets目录下的html文件:web2.loadUrl("file:///android_asset/index.html") ;
InputStreamReader inputReader = new InputStreamReader( getResources().getAssets().open(fileName) );
InputStreamReader inputReader = new InputStreamReader(getResources().openRawResource(R.raw.test1));
7. 检查网络是否可用:
public static boolean chkConnection() {
ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
cwjManager.getActiveNetworkInfo();
if (cwjManager.getActiveNetworkInfo() !=null) {
return cwjManager.getActiveNetworkInfo().isAvailable();
}
return false;
}
8.获取正在运行的任务,
首先需要声明一个活动对象管理器(ActivityManager) 所有的活动任务都属于此,然后通过获取服务可以得到所有的活动对象,然后通过活动对象可以得到所有运行的任务和服务,当然要获取服务和任务是使用不同的方法,但是方式是一样的。下面是获取代码:
代码 void getTask() {
ActivityManager activityManager;
try {
activityManager = (ActivityManager) this
.getSystemService(ACTIVITY_SERVICE);
arylistTask =new ArrayList<String>();
List<ActivityManager.RunningTaskInfo> mRunningTasks =
activityManager.getRunningTasks(30); //30表示获取的最大数
/* 以循环及baseActivity方式取得任务名称与ID */
for (RunningTaskInfo amTask : mRunningTasks)
{
Log.d("TaskInfo", amTask.baseActivity.getClassName()+"("+amTask.id+")");
}
//获取服务
List<RunningServiceInfo> mserviceTasks =
activityManager.getRunningServices(30);
/* 以循环方式取得任务名称与ID */
for (RunningServiceInfo serinfo : mserviceTasks)
{
Log.d("TaskServerInfo", serinfo.process+"("+serinfo.pid+")");
}
}
catch (Exception e)
{
}
9.Android 获取MIEI ISMI Sim卡串号等信息
TelephonyManager telephonemanage = (TelephonyManager) getWindow().getContext().getSystemService(Context.TELEPHONY_SERVICE);
try {
edit1.setText("MIEI: " + telephonemanage.getDeviceId()+ "\n SimSSN " + telephonemanage.getSimSerialNumber()+ "\n IMSI " + telephonemanage.getSubscriberId());
} catch (Exception e) {
edit1.setText(e.getMessage());
}
10.添加快捷图标
代码 privatevoid addShortcut(){
Intent shortcut =new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//快捷方式的名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
// shortcut.putExtra("duplicate", false); //不允许重复创建
//指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer
//注意: ComponentName的第二个参数必须加上点号(.),否则快捷方式无法启动相应程序
// ComponentName comp = new ComponentName(this.getPackageName(), "."+this.getLocalClassName());
// shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this,ShortcutTest.class));
//快捷方式的图标
ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
sendBroadcast(shortcut);
}
shortcut.putExtra("duplicate", false); //表示的为不允许重复设置
此种代码,直接添加到桌面上,并且也在上图所示的地方显示,但是此需要添加下面的权限:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
11. 防止锁屏:
PowerManager mPowerManager = (PowerManager) getSystemService(POWER_SERVICE); //电源控制,比如防锁屏
WakeLock mWakeLock= mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass()
.getName()); //处理屏幕防止锁屏
mWakeLock.acquire(); //恢复时解除锁屏
mWakeLock.release();
12. Drawable,Bitmap相互转换:
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
//canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
Resources res=getResources();
Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);
private byte[] Bitmap2Bytes(Bitmap bm){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
private Bitmap Bytes2Bimap(byte[] b){
if(b.length!=0){
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
else {
return null;
}
}
最新技术文章: