以前在Google notes里摘录的android-dev笔记,在google关闭notes后导出成本地文件了,现在上传到blog上吧。
SPAN_EXCLUSIVE_EXCLUSIVE
.setMovementMethod,此方法在需要响应用户事件时使用,如点击一个电话号码就跳转到拨号页面。如果不执行这个方法是不会响应事件的,即便文本看着已经是下划线蓝色字了。
.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,这是在 setSpan 时需要指定的 flag,它的意义我试了很久也没试出来,睡个觉,今天早上才突然有点想法,试之,果然。它是用来标识在 Span 范围内的文本前后输入新的字符时是否把它们也应用这个效果。分别有 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(前后都不包括)、Spanned.SPAN_INCLUSIVE_EXCLUSIVE(前面包括,后面不包括)、Spanned.SPAN_EXCLUSIVE_INCLUSIVE(前面不包括,后面包括)、Spanned.SPAN_INCLUSIVE_INCLUSIVE(前后都包括)。看个截图就更明白了:
标签: android-dev
ClickableSpan
SpannableStringBuilder ssb = new SpannableStringBuilder(s);
ClickableSpan clickSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
}
};
ssb.setSpan(clickSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
标签: android-dev
AlarmManager and Timer
1. The Alarm Manager holds a CPU wake lock as long as the alarm receiver’s onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast.
2. If your alarm receiver called
Context.startService()
, it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.3. If an alarm is delayed (by system sleep, for example, for non _WAKEUP alarm types), a skipped repeat will be delivered as soon as possible. For example, if you have set a recurring alarm for the top of every hour but the phone was asleep from 7:45 until 8:45, an alarm will be sent as soon as the phone awakens, then the next alarm will be sent at 9:00.
Sample:
Intent intent = new Intent(AlarmActivity.this, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(AlarmActivity.this, 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), (10 1000), pi);
4. Each timer has one thread on which tasks are executed sequentially.
5(1)schedule方法:下一次执行时间相对于 上一次 实际执行完成的时间点 ,因此执行时间会不断延后
(2)scheduleAtFixedRate方法:下一次执行时间相对于上一次开始的 时间点 ,因此执行时间不会延后,存在并发性
(2)scheduleAtFixedRate方法:下一次执行时间相对于上一次开始的 时间点 ,因此执行时间不会延后,存在并发性
6. 手机SleepTimer依然执行
Sample:
TimerTask task = new SyncContactsTimerTask();
delay = genDelay();
mTimer.schedule(new BackupContactsTimerTask(), delay, TIMER_TASK_PERIOD);
private final class BackupContactsTimerTask extends TimerTask {
public void run() {
if (DBG) {
LogUtil.i(ContactBackupRestore.TAG, “BackupContactsTimerTask run() begin”);
}
if (ContactBackupRestore.getAutoSyncPref(ContactsService.this) != 0) {
ContactBackupRestore.setIsAutoBackingUp(ContactsService.this, 1);
backupContacts();
}
}
}
标签: android-dev
Android 解屏幕锁与点亮屏幕(来电时效果)
PowerManager pm=(PowerManager) getSystemService(Context.POWER_SERVICE);
//获取电源管理器对象
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, “bright”);
//获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
wl.acquire();
//点亮屏幕
KeyguardManager km= (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
//得到键盘锁管理器对象
KeyguardLock kl = km.newKeyguardLock(“unLock”);
//参数是LogCat里用的Tag
kl.disableKeyguard();
//解锁
/
这里写程序的其他代码
*/
kl.reenableKeyguard();
//重新启用自动加锁
wl.release();
//释放
标签: android-dev
TextView实现多行滚动
<TextView
android:id=”@+id/tvCWJ”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:scrollbars=”vertical” <!–垂直滚动条 –>
android:singleLine=”false” <!–实现多行 –>
android:maxLines=”15” <!–最多不超过15行 –>
android:textColor=”#FF0000”
/>
android:id=”@+id/tvCWJ”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:scrollbars=”vertical” <!–垂直滚动条 –>
android:singleLine=”false” <!–实现多行 –>
android:maxLines=”15” <!–最多不超过15行 –>
android:textColor=”#FF0000”
/>
当然我们为了让TextView动起来,还需要用到TextView的setMovementMethod方法设置一个滚动实例,代码如下
TextView tvAndroid123 = (TextView)findViewById(R.id.tvCWJ);
tvAndroid123.setMovementMethod(ScrollingMovementMethod.getInstance());
// Android开发网提示相关的可以查看SDK中android.text.method分支了解更多
标签: android-dev
Android Canvas绘图抗锯齿解决方法
对于Android来说Canvas一般大量用于自定义View和游戏开发中,对于图形的基础绘制类,提供的drawText、drawBitmap以及drawCircle都需要抗锯齿处理才能让人满意,下面Android123将他们分为两大种情况。
一、包含Paint参数情况时,对于drawText、drawBitmap这样的方法,一般最后一个参数为Paint对象,Paint对象一般用于设置笔刷颜色和大小,同时包含了抗锯齿的方法,比如说objPaint.setAntiAlias(true); 这个方法执行后即可有比较明显的改善。
二、部分方法没有Paint参数,比如说setDrawFilter这个方法,它的参数只有PaintFlagsDrawFilter对象,我们自己构造一个新的对象,比如说new PaintFlagsDrawFilter(0,Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG)这样就过滤器可以让文本和位图经过圆滑处理。
标签: android-dev
android.resource://这个Uri你知道吗
如何访问平时APK文件Res目录下的内容呢? 如果直接访问Apk下的assets目录可以使用AssetManager类处理,而需要访问 res/raw这样的文件夹怎么办呢? 这里Android123可以告诉大家APK在安装时已经解压缩,部分资源存放在/data/data /package_name/这里, 比如我们想访问res/raw/android123.cwj文件,可以使用android.resource: //package_name/“ + R.raw.android123 这个Uri,其中package_name是你工程的包名。 完整的处理代码为 Uri uri = Uri.parse(“android.resource://com.android123.Sample/raw/android123.cwj”); 即可使用工程res/raw目录下的文件了。
标签: android-dev
void android.view.ViewGroup.setChildrenDrawnWithCacheEnabled(boolean enabled)
Tells the ViewGroup to draw its children using their drawing cache. This property is ignored when isAlwaysDrawnWithCacheEnabled() is true. A child’s drawing cache will be used only if it has been enabled. Subclasses should call this method to start and stop using the drawing cache when they perform performance sensitive operations, like scrolling or animating.
Parameters:
enabled true if children should be drawn with their cache, false otherwise
See Also:
setAlwaysDrawnWithCacheEnabled(boolean)
isChildrenDrawnWithCacheEnabled()
标签: android-dev
StrictMode
public void onCreate() {
if (DEVELOPER_MODE) {
StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder
()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder
()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
super.onCreate();
}
标签: android-dev
Toast makeText() 时的layout view:frameworks/base/core/res/res/layout/transient_notification.xml
android:shadowColor指定文本阴影的颜色,需要与shadowRadius一起使用。
android:shadowDx设置阴影横向坐标开始位置。
android:shadowDy设置阴影纵向坐标开始位置。
android:shadowRadius设置阴影的半径。设置为0.1就变成字体的颜色了,一般设置为3.0的效果比较好。
android:shadowColor指定文本阴影的颜色,需要与shadowRadius一起使用。
android:shadowDx设置阴影横向坐标开始位置。
android:shadowDy设置阴影纵向坐标开始位置。
android:shadowRadius设置阴影的半径。设置为0.1就变成字体的颜色了,一般设置为3.0的效果比较好。
标签: android-dev
触发媒体库进行扫描
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(“file://“+ Environment.getExternalStorageDirectory())));
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(“file://“+ Environment.getExternalStorageDirectory())));
标签: android-dev
<activity-alias>
The alias presents the target activity as a independent entity. It can have its own set of intent filters, and they, rather than the intent filters on the target activity itself, determine which intents can activate the target through the alias and how the system treats the alias. For example, the intent filters on the alias may specify the “
The alias presents the target activity as a independent entity. It can have its own set of intent filters, and they, rather than the intent filters on the target activity itself, determine which intents can activate the target through the alias and how the system treats the alias. For example, the intent filters on the alias may specify the “
android.intent.action.MAIN
“ and “android.intent.category.LAUNCHER
“ flags, causing it to be represented in the application launcher, even though none of the filters on the target activity itself set these flags.With the exception of targetActivity
, <activity-alias>
attributes are a subset of <activity>
attributes. For attributes in the subset, none of the values set for the target carry over to the alias. However, for attributes not in the subset, the values set for the target activity also apply to the alias.see http://androidappdocs.appspot.com/guide/topics/manifest/activity-alias-element.html标签: android-dev
BOLD fonts
We trying to use a regular font and use the font engine to extrapolate
that to BOLD format. I just tried with free font DejaVuSans.Typeface regFace = Typeface.createFromAsset(getContext().getAssets(), “fonts/DejaVuSans.ttf”);
Typeface boldFace = Typeface.create(regFace, Typeface.BOLD);Now when we set the type face to this boldFace in the paint object
using setTypeface(boldFace);
When we draw the text, we are expecting bold fonts. What we see is
regular fonts. Is this not the right usage ?
If I use a bold font file it works. But If I use regular font file,
the font is not extrapolated to bold. Our platform has requirement
not use different font files for bold and regular fonts (space
limitations).
Solution:
set FAKE_BOLD_TEXT_FLAG to the paint object.
We trying to use a regular font and use the font engine to extrapolate
that to BOLD format. I just tried with free font DejaVuSans.Typeface regFace = Typeface.createFromAsset(getContext().getAssets(), “fonts/DejaVuSans.ttf”);
Typeface boldFace = Typeface.create(regFace, Typeface.BOLD);Now when we set the type face to this boldFace in the paint object
using setTypeface(boldFace);
When we draw the text, we are expecting bold fonts. What we see is
regular fonts. Is this not the right usage ?
If I use a bold font file it works. But If I use regular font file,
the font is not extrapolated to bold. Our platform has requirement
not use different font files for bold and regular fonts (space
limitations).
Solution:
set FAKE_BOLD_TEXT_FLAG to the paint object.
标签: android-dev
如何在onCreate时获取View的width和height
有时我们会遇到这样的情况,在onCreate时就需要获取View的宽度和高度。但是在View显示之前,
不论是getWidth(),getHeight(),还是getMeasuredWidth(),getMeasuredHeight(),都会返回0。
实际上我们可以主动调用一次measure函数,但是要注意传入的参数:
view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
之后调用view.getMeasuredWidth()即可获得宽度,注意此时调用view.getWidth()还是返回0。
标签: android-dev
First, JavaScript running inside the WebView can call out to code in your Activity. You can use this to have your JavaScript trigger actions like starting a new activity, or it can be used to fetch data from a database or
ContentProvider
. The API for this is very simple: just call the addJavascriptInterface()
method on your WebView. You pass an object whose methods you want to expose to JavaScript and the name to use when making calls. You can see the exact syntax in WebViewDemo. java. Here we are making our DemoJavascriptInterface object available to JavaScript where it will be called “window.demo”.Second, your Activity can invoke JavaScript methods. All you have to do is call the
loadUrl
method with the appropriate JavaScript call:mWebView.loadUrl(“javascript:wave()”);
标签: android-dev
context.getResources().getConfiguration().locale.getCountry();
返回如”CN”或”TW”
标签: android-dev
DateFormat
DateFormat df = DateFormat.getDateInstance();
String formatDate = df.format(new Date());
DateFormat df = DateFormat.getDateInstance();
String formatDate = df.format(new Date());
标签: android-dev
Android屏幕截图之View方法
了解Linux的网友可能知道直接读取/dev/graphics/fb0即可来实现framebuffer,当然了对于自己的View实现一些绘图或子类化的技术时可以不用系统级这样的方法,我们可以通过
view.setDrawingCacheEnabled(true); //其中View是你需要截图的的View
Bitmap bm = view.getDrawingCache();
标签: android-dev
根据packageName构造Context
通常情况下获取当前应用的context的方法是getApplicationContext,但是通过根据其他的packageName如何构造Context呢? Android平台的应用实例其实还可以通过其他方式构造。比如代码
try {
Context ctx= createPackageContext(“com.android123.Cwj”, 0);
//ctx已经是com.android123.cwj的实例
} catch (NameNotFoundException e) {
//可能由于pacakgeName不存在所以必须处理该异常
}
需要注意的是,createPackageContext方法的第二个参数可选为CONTEXT_INCLUDE_CODE 和 CONTEXT_IGNORE_SECURITY ,定义分别为4和2,上面为0。一般忽略安全错误问题可以通过CONTEXT_IGNORE_SECURITY 标记,同时可能还需要处理 SecurityException 异常。
标签: android-dev
android.os.SystemProperties.get( TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC, “”)
PROPERTY_ICC_OPERATORNUMERIC:
The MCC+MNC (mobile country code+mobile network code) of the provider of the SIM. 5 or 6 decimal digits. Availablity: SIM state must be “READY”
标签: android-dev
<a name=”NDQIQDAoQ1Y-hbkl”>
setLocationProvider
public static final void setLocationProviderEnabled (ContentResolver cr, String provider, boolean enabled)
eg:
android.provider.Settings.Secure.setLocationProviderEnabled(getContentResolver(), LocationManager.GPS_PROVIDER, true);
android.provider.Settings.Secure.isLocationProviderEnabled(res,
LocationManager.GPS_PROVIDER);
获取Settings.System的
Settings.System.getString(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_RADIOS);
Settings.System.putInt(mContext.getContentResolver(), Settings.System.AIRPLANE_MODE_ON,
enabling ? 1 : 0);
标签: android-dev
inent调用代码总结,不断完善中
显示Web网页:
1. Uri uri = Uri.parse(“http://www.android123.com.cn“);
2. Intent it = new Intent(Intent.ACTION_VIEW,uri);
3. startActivity(it);
显示Google地图:
1. Uri uri = Uri.parse(“geo:38.899533,-77.036476”);
2. Intent it = new Intent(Intent.Action_VIEW,uri);
3. startActivity(it);
Maps路径规划:
1. Uri uri = Uri.parse(“http://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en“);
2. Intent it = new Intent(Intent.ACTION_VIEW,URI);
3. startActivity(it);
拨打电话:
1. Uri uri = Uri.parse(“tel:xxxxxx”);
2. Intent it = new Intent(Intent.ACTION_DIAL, uri);
3. startActivity(it);
1. Uri uri = Uri.parse(“tel.xxxxxx”);
2. Intent it =new Intent(Intent.ACTION_CALL,uri);
注意需要权限 <uses-permission id=”android.permission.CALL_PHONE” />
发送SMS/MMS
1. Intent it = new Intent(Intent.ACTION_VIEW);
2. it.putExtra(“sms_body”, “android开发网欢迎您”);
3. it.setType(“vnd.android-dir/mms-sms”);
4. startActivity(it);
发送短信
1. Uri uri = Uri.parse(“smsto:10086”);
2. Intent it = new Intent(Intent.ACTION_SENDTO, uri);
3. it.putExtra(“sms_body”, “10086”); //正文为10086
4. startActivity(it);
发送彩信
1. Uri uri = Uri.parse(“content://media/external/images/media/10”); //该Uri根据实际情况修改,external代表外部存储即sdcard
2. Intent it = new Intent(Intent.ACTION_SEND);
3. it.putExtra(“sms_body”, “android123.com.cn“);
4. it.putExtra(Intent.EXTRA_STREAM, uri);
5. it.setType(“image/png”);
6. startActivity(it);
发送Email
2. Uri uri = Uri.parse(“http://www.android123.com.cn/androidkaifa/mailto:android123@163.com“);
3. Intent it = new Intent(Intent.ACTION_SENDTO, uri);
4. startActivity(it);
1. Intent it = new Intent(Intent.ACTION_SEND);
2. it.putExtra(Intent.EXTRA_EMAIL, “android123@163.com“);
3. it.putExtra(Intent.EXTRA_TEXT, “android开发网测试”);
4. it.setType(“text/plain”);
5. startActivity(Intent.createChooser(it, “选择一个Email客户端”));
1. Intent it=new Intent(Intent.ACTION_SEND);
2. String[] tos={“android123@163.com“}; //发送到
3. String[] ccs={“ophone123@163.com“}; //抄送
4. it.putExtra(Intent.EXTRA_EMAIL, tos);
5. it.putExtra(Intent.EXTRA_CC, ccs);
6. it.putExtra(Intent.EXTRA_TEXT, “正文”);
7. it.putExtra(Intent.EXTRA_SUBJECT, “标题”);
8. it.setType(“message/rfc822”); //编码类型
9. startActivity(Intent.createChooser(it, “选择一个Email客户端”));
Email添加附件
1. Intent it = new Intent(Intent.ACTION_SEND);
2. it.putExtra(Intent.EXTRA_SUBJECT, “正文”);
3. it.putExtra(Intent.EXTRA_STREAM, “http://www.android123.com.cn/androidkaifa/file:///sdcard/nobody.mp3“); //附件为sd卡上的nobody MP3文件
4. sendIntent.setType(“audio/mp3”);
5. startActivity(Intent.createChooser(it, “选择一个Email客户端”));
播放多媒体
1.
2. Intent it = new Intent(Intent.ACTION_VIEW);
3. Uri uri = Uri.parse(“http://www.android123.com.cn/androidkaifa/file:///sdcard/nobody.mp3“);
4. it.setDataAndType(uri, “audio/mp3”);
5. startActivity(it);
1. Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, “1”); //从系统内部的MediaProvider索引中调用播放
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. startActivity(it);
Uninstall卸载程序
1. Uri uri = Uri.fromParts(“package”, packageName, null); //packageName为包名,比如com.android123.apkInstaller
2. Intent it = new Intent(Intent.ACTION_DELETE, uri);
3. startActivity(it);
Installer安装APK
这里安装APK文件的方法参考 http://www.android123.com.cn/kaifafaq/487.html 一文里面包含两种方法
标签: android-dev
播放一个声音文件
// Play sound here
final AudioManager audioManager = (AudioManager) mContext
.getSystemService(Context.AUDIO_SERVICE);
AsyncPlayer player = new AsyncPlayer(TAG);
player.setUsesWakeLock(mContext);
if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {
player.play(mContext, Uri.parse(BATTERYLOW_SOUND), false,
AudioManager.STREAM_NOTIFICATION);
}
// End play sound
// Play sound here
final AudioManager audioManager = (AudioManager) mContext
.getSystemService(Context.AUDIO_SERVICE);
AsyncPlayer player = new AsyncPlayer(TAG);
player.setUsesWakeLock(mContext);
if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {
player.play(mContext, Uri.parse(BATTERYLOW_SOUND), false,
AudioManager.STREAM_NOTIFICATION);
}
// End play sound
标签: android-dev
显示系统电量使用情况
final Intent intent = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_MULTIPLE_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
| Intent.FLAG_ACTIVITY_NO_HISTORY);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
final Intent intent = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_MULTIPLE_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
| Intent.FLAG_ACTIVITY_NO_HISTORY);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
标签: android-dev
Activity inside a view
> Does anyone has a simple example of to use LocalActivityManager or
> something else to meet my requirements.void createInnerActivity(ViewGroup container, Class<?> activityClass)
{
if (container.getChildCount() != 0) {
container.removeViewAt(0);
}final Intent intent = new Intent(this, activityClass);
final Window window = getLocalActivityManager().startActivity(activityClass.toString(), intent);
container.addView(window.getDecorView(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT));
}
Above should be a method of activity that extends ActivityGroup,
passed container will host newly created activity.
> Does anyone has a simple example of to use LocalActivityManager or
> something else to meet my requirements.void createInnerActivity(ViewGroup container, Class<?> activityClass)
{
if (container.getChildCount() != 0) {
container.removeViewAt(0);
}final Intent intent = new Intent(this, activityClass);
final Window window = getLocalActivityManager().startActivity(activityClass.toString(), intent);
container.addView(window.getDecorView(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT));
}
Above should be a method of activity that extends ActivityGroup,
passed container will host newly created activity.
标签: android-dev
stopService()
Note that if a stopped service still has ServiceConnection objects bound to it with the BIND_AUTO_CREATE set, it will not be destroyed until all of these bindings are removed.
Note that if a stopped service still has ServiceConnection objects bound to it with the BIND_AUTO_CREATE set, it will not be destroyed until all of these bindings are removed.
标签: android-dev
Broadcast receiver lifecycle
A broadcast receiver has single callback method:
void onReceive(Context curContext, Intent broadcastMsg)
When a broadcast message arrives for the receiver, Android calls its
onReceive()
method and passes it the Intent object containing the message. The broadcast receiver is considered to be active only while it is executing this method. When onReceive()
returns, it is inactive.A process with an active broadcast receiver is protected from being killed. But a process with only inactive components can be killed by the system at any time, when the memory it consumes is needed by other processes.
This presents a problem when the response to a broadcast message is time consuming and, therefore, something that should be done in a separate thread, away from the main thread where other components of the user interface run. If
onReceive()
spawns the thread and then returns, the entire process, including the new thread, is judged to be inactive (unless other application components are active in the process), putting it in jeopardy of being killed. The solution to this problem is for onReceive()
to start a service and let the service do the job, so the system knows that there is still active work being done in the process.The next section has more on the vulnerability of processes to being killed.
标签: android-dev
I wanted a developed a shared library(.so) with C++ code. The C++ code uses Run time polymorphism using the polymorphism using the virtual keyword. When I’m trying to compile my code, I get lot of undefined references ike “ to undefined reference to `vtable for Test::TestClass.”
RTTI is turned off for the platform code because it is not used and noticeably increases the code size
标签: android-dev
public void startBluetoothSco ()
Since: API Level 8
Start bluetooth SCO audio connection.
Requires Permission:
MODIFY_AUDIO_SETTINGS
.This method can be used by applications wanting to send and received audio to/from a bluetooth SCO headset while the phone is not in call.
As the SCO connection establishment can take several seconds, applications should not rely on the connection to be available when the method returns but instead register to receive the intent
ACTION_SCO_AUDIO_STATE_CHANGED
and wait for the state to be SCO_AUDIO_STATE_CONNECTED
.As the connection is not guaranteed to succeed, applications must wait for this intent with a timeout.
When finished with the SCO connection or if the establishment times out, the application must call
stopBluetoothSco()
to clear the request and turn down the bluetooth connection.Even if a SCO connection is established, the following restrictions apply on audio output streams so that they can be routed to SCO headset: - the stream type must be
STREAM_VOICE_CALL
- the format must be mono - the sampling must be 16kHz or 8kHzThe following restrictions apply on input streams: - the format must be mono - the sampling must be 8kHz
Note that the phone application always has the priority on the usage of the SCO connection for telephony. If this method is called while the phone is in call it will be ignored. Similarly, if a call is received or sent while an application is using the SCO connection, the connection will be lost for the application and NOT returned automatically when the call ends.
标签: android-dev
- requestFocus
<requestFocus>
- Any element representing a
View
object can include this empty element, which gives it’s parent initial focus on the screen. You can have only one of these elements per file.
<?xml version=”1.0” encoding=”utf-8”?>
<ViewGroup xmlns:android=”http://schemas.android.com/apk/res/android“
android:id=”@[+][package:]id/resource_name“
android:layout_height=[“dimension“ | “fill_parent” | “wrap_content”]
android:layout_width=[“dimension“ | “fill_parent” | “wrap_content”]
[ViewGroup-specific attributes] >
<View
android:id=”@[+][package:]id/resource_name“
android:layout_height=[“dimension“ | “fill_parent” | “wrap_content”]
android:layout_width=[“dimension“ | “fill_parent” | “wrap_content”]
[View-specific attributes] >
<requestFocus/>
</View>
<ViewGroup >
<View />
</ViewGroup>
<include layout=”@layout/layout_resource“/>
</ViewGroup>
标签: android-dev
FLAG_DIM_BEHIND:everything behind this window will be dimmed.
dimAmount:amount of dimming to apply. Range is from 1.0 for completely opaque to 0.0 for no dim.params.
eg:
Dialog d = new …;
WindowManager.LayoutParams params = d.getWindow().getAttributes();
TypedArray a = d.getWindow().getWindowStyle();
params.dimAmount = a.getFloat(android.R.styleable.Window_backgroundDimAmount, 0.5f);FLAG_BLUR_BEHIND
dimAmount:amount of dimming to apply. Range is from 1.0 for completely opaque to 0.0 for no dim.params.
eg:
Dialog d = new …;
WindowManager.LayoutParams params = d.getWindow().getAttributes();
TypedArray a = d.getWindow().getWindowStyle();
params.dimAmount = a.getFloat(android.R.styleable.Window_backgroundDimAmount, 0.5f);FLAG_BLUR_BEHIND
标签: android-dev
frameworks下的activity的Manifest文件:
位置:frameworks/base/core/res/AndroidManifest.xml
被定义的activity有:frameworks/base/core/java/com/android/internal/app/{ResolverActivity.java, ChooserActivity.java}等等
AndroidManifest.xml中还定义了其他一些东西:
protected-broadcast:Special broadcasts that only the system can send
标签: android-dev
一些有关Intent异常的处理方法(no activity matches)
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
标签: android-dev
android 用HttpURLConnection读网络
String getURL = “http://g.cn/“;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(getURL);
InputStream is = null;
try {
HttpResponse response;
response = httpclient.execute(httpget);
is = response.getEntity().getContent();
StringBuffer versionString = new StringBuffer();
InputStreamReader reader = new InputStreamReader(is);
char buffer[] = new char[256];
int count;
while ((count = reader.read(buffer, 0, buffer.length)) > 0) {
versionString.append(buffer, 0, count);
}
return versionString.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
if (e instanceof SocketException
|| e instanceof SocketTimeoutException) {
throw new SocketException(e.getMessage());
}
} finally {
}
————————————————————————————————
网络上很多关于HttpURLConnection的例子,
void getInput(){
try
{
URL url = new URL(“http://www.google.cn/“);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(10000);
conn.setRequestMethod(“GET”);
conn.setRequestProperty(“accept”, “/“);
String location = conn.getRequestProperty(“location”);
int resCode = conn.getResponseCode();
conn.connect();
InputStream stream = conn.getInputStream();
byte[] data=new byte[102400];
int length=stream.read(data);
String str=new String(data,0,length);
conn.disconnect();
System.out.println(str);
stream.close();
}
catch(Exception ee)
{
System.out.print(“ee:”+ee.getMessage());
}
}
只是要注意的是配置一个权限,AndroidManifest.xml 中应该加入如下节点。
</activity>
</application>
<uses-permission android:name=”android.permission.INTERNET”></uses-permission>
</manifest>
可 以把AndroidManifest.xml open with manifest editor 来编辑 在permissions中add uses-permission,然后再在name中选择android.permission.INTERNET,然后save就ok了。
标签: android-dev
设置屏幕不被锁屏:
getWindow();addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow();addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
标签: android-dev
获取density DPI:
context.getResources().getDisplayMetrics().densityDpi;
context.getResources().getDisplayMetrics().densityDpi;
标签: android-dev
调用android中的cmds:
try {
String command = “chmod 777 “ + destFile.getAbsolutePath();
Log.i(“cmd”, “command = “ + command);
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
proc.waitFor(); // Causes the calling thread to wait for the native process associated with this object to finish executing.
proc.destroy(); // Terminates this process and closes any associated streams.
} catch (IOException e) {
Log.i(“cmd”, “chmod fail!!!!”);
e.printStackTrace();
}
try {
String command = “chmod 777 “ + destFile.getAbsolutePath();
Log.i(“cmd”, “command = “ + command);
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
proc.waitFor(); // Causes the calling thread to wait for the native process associated with this object to finish executing.
proc.destroy(); // Terminates this process and closes any associated streams.
} catch (IOException e) {
Log.i(“cmd”, “chmod fail!!!!”);
e.printStackTrace();
}
标签: android-dev
让屏幕不自动锁:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
标签: android-dev
改变屏幕亮度:
Window w = getWindow();
WindowManager.LayoutParams lp = w.getAttributes();
lp.screenBrightness = [brightness value];
w.setAttributes(lp);
Window w = getWindow();
WindowManager.LayoutParams lp = w.getAttributes();
lp.screenBrightness = [brightness value];
w.setAttributes(lp);
标签: android-dev
<?xml version=”1.0” encoding=”utf-8”?>
<searchable xmlns:android=”http://schemas.android.com/apk/res/android“
android:label=”@string/search_label”
android:hint=”@string/search_hint”
android:voiceSearchMode=”showVoiceSearchButton|launchRecognizer” >
</searchable>
<activity android:name=”.MySearchableActivity”
android:launchMode=”singleTop“ >
<intent-filter>
<action android:name=”android.intent.action.SEARCH” />
</intent-filter>
<meta-data android:name=”android.app.searchable”
android:resource=”@xml/searchable”/>
</activity>
标签: android-dev
Extending BackupAgent
Caution: If your application data is saved to a file, make sure
that you use synchronized statements while accessing the file so that your backup agent does not
read the file while an Activity in your application is also writing the file.
Extending BackupAgentHelper
public class MyPrefsBackupAgent extends BackupAgentHelper {
// The name of the SharedPreferences file
static final String PREFS = “user_preferences”;
// A key to uniquely identify the set of backup data
static final String PREFS_BACKUP_KEY = “prefs”;
// Allocate a helper and add it to the backup agent
void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
Note:
SharedPreferences
are threadsafe, so you can safely read and write the shared preferences file from your backup agent and other activities.public class MyFileBackupAgent extends BackupAgentHelper {
// The name of the SharedPreferences file
static final String TOP_SCORES = “scores”;
static final String PLAYER_STATS = “stats”;
// A key to uniquely identify the set of backup data
static final String FILES_BACKUP_KEY = “myfiles”;
// Allocate a helper and add it to the backup agent
void onCreate() {
FileBackupHelper helper = new FileBackupHelper(this, TOP_SCORES, PLAYER_STATS);
addHelper(FILES_BACKUP_KEY, helper);
}
}
Note: reading and writing to files on internal storage is not threadsafe.
标签: android-dev
Using Shared Preferences
public class Calc extends Activity {
public static final String PREFS_NAME = “MyPrefsFile”;
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean(“silentMode”, false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(“silentMode”, mSilentMode);
// Commit the edits!
editor.commit();
}
}
标签: android-dev
Using the Internal Storage
You can save files directly on the device’s internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.
String FILENAME = “hello_file”;
String string = “hello world!”;
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
Tip: If you want to save a static file in your application at compile time, save the file in your project res/raw/
directory. You can open it withopenRawResource()
, passing the R.raw.<filename>
resource ID. This method returns an InputStream
that you can use to read the file (but you cannot write to the original file).Funtion references
————————————-
public abstract File getFilesDir ()
Returns the absolute path to the directory on the filesystem where files created with
openFileOutput(String, int)
are stored.public abstract String[] fileList ()
Returns an array of strings naming the private files associated with this Context’s application package.
标签: android-dev
Checking External Storage availability
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
标签: android-dev
public static File getExternalStoragePublicDirectory (String type)
Since: API Level 8
Get a top-level public external storage directory for placing files of a particular type. This is where the user will typically place and manage their own files, so you should be careful about what you put here to ensure you don’t erase their files or get in the way of their own organization.
Here is an example of typical code to manipulate a picture on the public external storage:
void createExternalStoragePublicPicture() {
// Create a path where we will place our picture in the user’s
// public pictures directory. Note that you should be careful about
// what you place here, since the user often manages these files. For
// pictures and other media owned by the application, consider
// Context.getExternalMediaDir().
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, “DemoPicture.jpg”);
try {
// Make sure the Pictures directory exists.
path.mkdirs();
// Very simple code to copy a picture from the application’s
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i(“ExternalStorage”, “Scanned “ + path + “:”);
Log.i(“ExternalStorage”, “-> uri=” + uri);
}
});
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w(“ExternalStorage”, “Error writing “ + file, e);
}
}
void deleteExternalStoragePublicPicture() {
// Create a path where we will place our picture in the user’s
// public pictures directory and delete the file. If external
// storage is not currently mounted this will fail.
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, “DemoPicture.jpg”);
file.delete();
}
boolean hasExternalStoragePublicPicture() {
// Create a path where we will place our picture in the user’s
// public pictures directory and check if the file exists. If
// external storage is not currently mounted this will think the
// picture doesn’t exist.
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, “DemoPicture.jpg”);
return file.exists();
}
Parameters
type | The type of storage directory to return. Should be one of DIRECTORY_MUSIC , DIRECTORY_PODCASTS , DIRECTORY_RINGTONES , DIRECTORY_ALARMS , DIRECTORY_NOTIFICATIONS ,DIRECTORY_PICTURES , DIRECTORY_MOVIES , DIRECTORY_DOWNLOADS , or DIRECTORY_DCIM . May not be null. |
---|
Returns
- Returns the File path for the directory. Note that this directory may not yet exist, so you must make sure it exists before using it such as with
File.mkdirs()
.
标签: android-dev
public static File getExternalStorageDirectory ()
Since: API Level 1
Gets the Android external storage directory.
标签: android-dev
public abstract File getExternalFilesDir (String type)
Since: API Level 8
Returns the absolute path to the directory on the external filesystem (that is somewhere on
Environment.getExternalStorageDirectory()
) where the application can place persistent files it owns. These files are private to the applications, and not typically visible to the user as media.This is like
getFilesDir()
in that these files will be deleted when the application is uninstalled, however there are some important differences:- External files are not always available: they will disappear if the user mounts the external storage on a computer or removes it. See the APIs on
Environment
for information in the storage state. - There is no security enforced with these files. All applications can read and write files placed here.
Here is an example of typical code to manipulate a file in an application’s private storage:
void createExternalStoragePrivateFile() {
// Create a path where we will place our private file on external
// storage.
File file = new File(getExternalFilesDir(null), “DemoFile.jpg”);
try {
// Very simple code to copy a picture from the application’s
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w(“ExternalStorage”, “Error writing “ + file, e);
}
}
void deleteExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), “DemoFile.jpg”);
if (file != null) {
file.delete();
}
}
boolean hasExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), “DemoFile.jpg”);
if (file != null) {
return file.exists();
}
return false;
}
If you supply a non-null type to this function, the returned file will be a path to a sub-directory of the given type. Though these files are not automatically scanned by the media scanner, you can explicitly add them to the media database with
MediaScannerConnection.scanFile
. Note that this is not the same as Environment.getExternalStoragePublicDirectory()
, which provides directories of media shared by all applications. The directories returned here are owned by the application, and their contents will be removed when the application is uninstalled. Unlike Environment.getExternalStoragePublicDirectory()
, the directory returned here will be automatically created for you.Here is an example of typical code to manipulate a picture in an application’s private storage and add it to the media database:
void createExternalStoragePrivatePicture() {
// Create a path where we will place our picture in our own private
// pictures directory. Note that we don’t really need to place a
// picture in DIRECTORY_PICTURES, since the media scanner will see
// all media in these directories; this may be useful with other
// media types such as DIRECTORY_MUSIC however to help it classify
// your media for display to the user.
File path = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File file = new File(path, “DemoPicture.jpg”);
try {
// Very simple code to copy a picture from the application’s
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i(“ExternalStorage”, “Scanned “ + path + “:”);
Log.i(“ExternalStorage”, “-> uri=” + uri);
}
});
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w(“ExternalStorage”, “Error writing “ + file, e);
}
}
void deleteExternalStoragePrivatePicture() {
// Create a path where we will place our picture in the user’s
// public pictures directory and delete the file. If external
// storage is not currently mounted this will fail.
File path = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (path != null) {
File file = new File(path, “DemoPicture.jpg”);
file.delete();
}
}
boolean hasExternalStoragePrivatePicture() {
// Create a path where we will place our picture in the user’s
// public pictures directory and check if the file exists. If
// external storage is not currently mounted this will think the
// picture doesn’t exist.
File path = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (path != null) {
File file = new File(path, “DemoPicture.jpg”);
return file.exists();
}
return false;
}
Parameters
type | The type of files directory to return. May be null for the root of the files directory or one of the following Environment constants for a subdirectory: DIRECTORY_MUSIC , DIRECTORY_PODCASTS , DIRECTORY_RINGTONES , DIRECTORY_ALARMS , DIRECTORY_NOTIFICATIONS , DIRECTORY_PICTURES , or DIRECTORY_MOVIES . |
---|
Returns
- Returns the path of the directory holding application files on external storage. Returns null if external storage is not currently mounted so it could not ensure the path exists; you will need to call this method again when it is available.
getExternalCacheDir () … Since: API Level 8
标签: android-dev
Hiding your files from the Media Scanner
Include an empty file named
.nomedia
in your external files directory (note the dot prefix in the filename). This will prevent Android’s media scanner from reading your media files and including them in apps like Gallery or Music.标签: android-dev
Saving cache files
If you’d like to cache some data, rather than store it persistently, you should use
getCacheDir()
to open a File
that represents the internal directory where your application should save temporary cache files.When the device is low on internal storage space, Android may delete these cache files to recover space. However, you should not rely on the system to clean up these files for you. You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user uninstalls your application, these files are removed.
public abstract File getCacheDir ()
Returns the absolute path to the application specific cache directory on the filesystem.
标签: android-dev
Behind the JAVA process
system_server is a special case. It calls ActivityThread.java’s systemMain static function, which creates an instance of ActivityThread. ActivityThread then creates an instance of ApplicationThread, Application and ApplicationContext.
Every other JAVA process works in a different way. It’s controlled by system_server while forked by zygote. When any JAVA process other than system_server is forked from zygote, it automatically calls ActivityThread.java’s main static function(See Process.java and the following code snippet).
try {
ZygoteInit.invokeStaticMain(cloader, className, mainArgs);
} catch (RuntimeException ex) {
logAndPrintError (newStderr, “Error starting. “, ex);
}
The ActivityThread.java’s main function creates an instance of ActivityThread. ActivityThread then creates an instance of ApplicationThread. The ApplicationThread will work as an IBinder object to interact with ActivityManagerService in system_server. The new process does nothting at this time other than waiting IPC call from system_server. The Application and ApplicationContext object won’t be created at this time. Actually it’s deferred to when the process really works, eg. start an activity, receive intent or start a service.
For example, when start an activity, ActivityManagerService know which process the to-be-launched activity should run in, so it will RPC call ApplicationThread’s scheduleLaunchActivity to launch a new activity in that process. ApplicationThread then post a message to let ActivityThread know it needs to start an activity. ActivityThread then creates Application and ApplicationContext object. After that, it calls Instrumentation, then Instrumentation finally calls JAVA dalvik VM to really create an activity JAVA object.
标签: android-dev
save to bytearray
Bitmap bitmap = Bitmap.createBitmap((int) cell.getWidth(), (int) cell.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
cell.dispatchDraw(c);
// bubbleTextview line 123
int size = bitmap.getWidth() bitmap.getHeight() 4;
ByteArrayOutputStream ostream = new ByteArrayOutputStream(size);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
bitmap.recycle();
byte[] savedBitmap = ostream.toByteArray();
decode from bytearray
mCacheBitmap = BitmapFactory.decodeByteArray(bitmapByte, 0, bitmapByte.length);
if (mCacheBitmap != null) {
mCacheBitmap.recycle();
mCacheBitmap = null;
}
标签: android-dev
Full Screen Dialog:
dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
标签: android-dev
query
resolver.query(uri, projection, selection, selectionArgs, sortOrder);
selection的where语句可以是:
MediaStore.Audio.Media._ID + “ IN ( 1, 2, 3, 4 ) “
resolver.query(uri, projection, selection, selectionArgs, sortOrder);
selection的where语句可以是:
MediaStore.Audio.Media._ID + “ IN ( 1, 2, 3, 4 ) “
标签: android-dev
大家一定和我一样,有Bitmap exceeds VM budget的痛苦。借由明礼提供的工具,
在ImageView类中,
因此,改用先通过BitmapFactory.
标签: android-dev
AsyncTask
- onPreExecute() 当任务执行之前开始调用此方法,可以在这里显示进度对话框。
- doInBackground(Params…) 此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。在执行过程中可以调用publicProgress(Progress…)来更新任务的进度。
- onProgressUpdate(Progress…) 此方法在主线程执行,用于显示任务执行的进度。
- onPostExecute(Result) 此方法在主线程执行,任务执行的结果作为此方法的参数返回。
举个简单的例子如下:
// 设置三种类型参数分别为String,Integer,String
class PageTask extends AsyncTask {
// 可变长的输入参数,与AsyncTask.exucute()对应
@Override
protected String doInBackground(String… params) {
try {
HttpClient client = new DefaultHttpClient();
// params[0]代表连接的url
HttpGet get = new HttpGet(params[0]);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
InputStream is = entity.getContent();
String s = null;
if (is != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[128];
int ch = -1;
int count = 0;
while ((ch = is.read(buf)) != -1) {
baos.write(buf, 0, ch);
count += ch;
if (length > 0) {
// 如果知道响应的长度,调用publishProgress()更新进度
publishProgress((int) ((count / (float) length) 100));
}
// 为了在模拟器中清楚地看到进度,让线程休眠100ms
Thread.sleep(100);
}
s = new String(baos.toByteArray()); }
// 返回结果
return s;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onPostExecute(String result) {
// 返回HTML页面的内容
message.setText(result);
}
@Override
protected void onPreExecute() {
// 任务启动,可以在这里显示一个对话框,这里简单处理
message.setText(R.string.task_started);
}
@Override
protected void onProgressUpdate(Integer… values) {
// 更新进度
message.setText(values[0]);
}
}
执行PageTask非常简单,只需要调用如下代码。
PageTask task = new PageTask();
task.execute(url.getText().toString());
标签: android-dev
Use the Custom Component
<view
class=”com.android.notepad.NoteEditor$MyEditText”
id=”@+id/note”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:background=”@android:drawable/empty”
android:padding=”10dip”
android:scrollbars=”vertical”
android:fadingEdge=”vertical” />
——————————– or (if not inner class) ———————————
<com.android.notepad.MyEditText
id=”@+id/note”
… />
标签: android-dev
UI Events
- This allows yourActivity.dispatchTouchEvent(MotionEvent)
Activity
to intercept all touch events before they are dispatched to the window.
- This allows aViewGroup.onInterceptTouchEvent(MotionEvent)
ViewGroup
to watch events as they are dispatched to child Views.
- Call this upon a parent View to indicate that it should not intercept touch events withViewParent.requestDisallowInterceptTouchEvent(boolean)
.onInterceptTouchEvent(MotionEvent)
标签: android-dev
Displaying a Progress Bar
An activity can display a progress bar to notify the user that something is happening. To display a progress bar in a screen, call
Activity.requestWindowFeature(Window.FEATURE_PROGRESS)
. To set the value of the progress bar, call Activity.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, level)
. Progress bar values are from 0 to 9,999, or set the value to 10,000 to make the progress bar invisible.You can also use the
ProgressDialog
class, which enables a dialog box with an embedded progress bar to send a “I’m working on it” notification to the user.标签: android-dev
我自己总结一下吧:
方法一:直接给activity要adapter
ListAdapter listAdapter = activity.getListAdapter();
获得的数据不是用户从界面更改后的,而是你最开始设置的初始数据
方法二:获取ListView listView = activity.getListView();
然后
for(int i=0;i<listView.getChildCount();i++){
View view = listView.getChildAt(i);
。。。。
获取的数据仅仅是当前界面上的,不是全部
方法三:先获取ListView listView = activity.getListView();
然后获取:
ListAdapter listAdapter = listView.getAdapter();
for(int l=0;l<listAdapter.getCount();l++){
View view = listAdapter.getView(l, null, null);
。。。。
这样就可以获取全部数据,并且是最新数据
方法一:直接给activity要adapter
ListAdapter listAdapter = activity.getListAdapter();
获得的数据不是用户从界面更改后的,而是你最开始设置的初始数据
方法二:获取ListView listView = activity.getListView();
然后
for(int i=0;i<listView.getChildCount();i++){
View view = listView.getChildAt(i);
。。。。
获取的数据仅仅是当前界面上的,不是全部
方法三:先获取ListView listView = activity.getListView();
然后获取:
ListAdapter listAdapter = listView.getAdapter();
for(int l=0;l<listAdapter.getCount();l++){
View view = listAdapter.getView(l, null, null);
。。。。
这样就可以获取全部数据,并且是最新数据
标签: android-dev
read the file:
If the table entry is a
If the table entry is a
content:
URI, do not open and read the file directly (for one thing, permissions problems can make this fail), callContentResolver.openInputStream()
to get an InputStream
object that you can use to read the data.标签: android-dev
managedQuery()
causes the activity to manage the life cycle of the Cursor. A managed Cursor handles all of the niceties, such as unloading itself when the activity pauses, and requerying itself when the activity restarts. You can ask an Activity to begin managing an unmanaged Cursor object for you by callingActivity.startManagingCursor()
.标签: android-dev
The Activity class also provides an API for managing internal persistent state associated with an activity. This can be used, for example, to remember the user’s preferred initial display in a calendar (day view or week view) or the user’s default home page in a web browser.
Activity persistent state is managed with the method
getPreferences(int)
, allowing you to retrieve and modify a set of name/value pairs associated with the activity. To use preferences that are shared across multiple application components (activities, receivers, services, providers), you can use the underlying Context.getSharedPreferences()
method to retrieve a preferences object stored under a specific name. (Note that it is not possible to share settings data across application packages – for that you will need a content provider.) 【Content providers store and retrieve data and make it accessible to all applications. They’re the only way to share data across applications; 】Here is an excerpt from a calendar activity that stores the user’s preferred view mode in its persistent settings:
public class CalendarActivity extends Activity {
…
static final int DAY_VIEW_MODE = 0;
static final int WEEK_VIEW_MODE = 1;
private SharedPreferences mPrefs;
private int mCurViewMode;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences mPrefs = getSharedPreferences();
mCurViewMode = mPrefs.getInt(“view_mode” DAY_VIEW_MODE);
}
protected void onPause() {
super.onPause();
SharedPreferences.Editor ed = mPrefs.edit();
ed.putInt(“view_mode”, mCurViewMode);
ed.commit();
}
}
标签: android-dev
Configuration Changes
Unless you specify otherwise, a configuration change (such as a change in screen orientation, language, input devices, etc) will cause your current activity to be destroyed, going through the normal activity lifecycle process of
onPause()
, onStop()
, and onDestroy()
as appropriate. If the activity had been in the foreground or visible to the user, once onDestroy()
is called in that instance then a new instance of the activity will be created, with whatever savedInstanceState the previous instance had generated from onSaveInstanceState(Bundle)
.This is done because any application resource, including layout files, can change based on any configuration value. Thus the only safe way to handle a configuration change is to re-retrieve all resources, including layouts, drawables, and strings. Because activities must already know how to save their state and re-create themselves from that state, this is a convenient way to have an activity restart itself with a new configuration.
In some special cases, you may want to bypass restarting of your activity based on one or more types of configuration changes. This is done with the
android:configChanges
attribute in its manifest. For any types of configuration changes you say that you handle there, you will receive a call to your current activity’s onConfigurationChanged(Configuration)
method instead of being restarted. If a configuration change involves any that you do not handle, however, the activity will still be restarted and onConfigurationChanged(Configuration)
will not be called.标签: android-dev
Set the theme from the application(注意事项)
If using the
setTheme()
method to load a theme for an Activity programmatically, you must be sure to set the theme before instantiating any Views in the context, for example, before calling setContentView(View)
or inflate(int, ViewGroup)
. This ensures that the system applies the same theme for all of your UI screens.If you are considering loading a theme programmatically for the main
screen of your application, note that the theme would not be applied
in any animations the system would use to start the activity, which
would take place before your application opens. In most cases, if
you want to apply a theme to your main screen, doing so in XML
is a better approach.
标签: android-dev
(@) and (?)
(@): The at-symbol indicates that we’re referencing a resource previously defined elsewhere;
(?):The question-mark indicates that we’re referencing a resource value in the currently loaded theme.
(@): The at-symbol indicates that we’re referencing a resource previously defined elsewhere;
(?):The question-mark indicates that we’re referencing a resource value in the currently loaded theme.
标签: android-dev
If a user later returns to an application that’s been killed, Android needs a way to re-launch it in the same state as it was last seen, to preserve the “all applications are running all of the time” experience. This is done by keeping track of the parts of the application the user is aware of (the Activities), and re-starting them with information about the last state they were seen in. This last state is generated each time the user leaves that part of the application, not when it is killed, so that the kernel can later freely kill it without depending on the application to respond correctly at that point.
标签: android-dev
Activities and Tasks
To the user, it will seem as if the map viewer is part of the same application as your activity, even though it’s defined in another application and runs in that application’s process. Android maintains this user experience by keeping both activities in the same task. Simply put, a task is what the user experiences as an “application.” It’s a group of related activities, arranged in a stack.
Note that when a new instance of an Activity is created to handle a new intent, the user can always press the BACK key to return to the previous state (to the previous activity). But when an existing instance of an Activity handles a new intent, the user cannot press the BACK key to return to what that instance was doing before the new intent arrived.
标签: android-dev
a “
singleTask
“ activity may or may not have other activities above it in the stack. If it does, it is not in position to handle the intent, and the intent is dropped. (Even though the intent is dropped, its arrival would have caused the task to come to the foreground, where it would remain.)标签: android-dev
Activities and Tasks
Atask is what the user experiences as an “application.” It’s a group of related activities, arranged in a stack. The root activity in the stack is the one that began the task — typically, it’s an activity the user selected in the application launcher. The activity at the top of the stack is one that’s currently running — the one that is the focus for user actions. When one activity starts another, the new activity is pushed on the stack; it becomes the running activity. The previous activity remains in the stack. When the user presses the BACK key, the current activity is popped from the stack, and the previous one resumes as the running activity.
The association of activities with tasks, and the behavior of an activity within a task, is controlled by the interaction between flags set in the Intent object that started the activity and attributes set in the activity’s
<activity>
element in the manifest. Both requester and respondent have a say in what happens.标签: android-dev
android.intent.action.MAIN
/ android.intent.category.LAUNCHER
the action “
android.intent.action.MAIN
“ and the category “android.intent.category.LAUNCHER
“ — is a common one. It marks the activity as one that should be represented in the application launcher, the screen listing applications users can launch on the device. In other words, the activity is the entry point for the application, the initial one users would see when they choose the application in the launcher.标签: android-dev
RegisterReceiver()
broadcast receivers can either be declared in the manifest, or they can be created dynamically in code (as
broadcast receivers can either be declared in the manifest, or they can be created dynamically in code (as
BroadcastReceiver
objects) and registered with the system by calling Context.registerReceiver()
.For a broadcast receiver that’s created and registered in code, the intent filter is instantiated directly as an IntentFilter
object. All other filters are set up in the manifest.标签: android-dev
public void startActivityForResult (Intent intent, int requestCode)
Using a negative requestCode is the same as calling
startActivity(Intent)
(the activity is not launched as a sub-activity).Note that this method should only be used with Intent protocols that are defined to return a result. In other protocols (such as
ACTION_MAIN
or ACTION_VIEW
), you may not get the result when you expect. For example, if the activity you are launching uses the singleTask launch mode, it will not run in your task and thus you will immediately receive a cancel result.As a special case, if you call startActivityForResult() with a requestCode >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your activity, then your window will not be displayed until a result is returned back from the started activity. This is to avoid visible flickering when redirecting to another activity.
标签: android-dev
A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. The Activity class inherits from Context.
标签: android-dev