概述
转载:Android 编程实用代码大全
http://www.juapk.com/forum.php?mod=viewthread&tid=325&fromuid=263
1
2
3
4
5
|
String status=Environment.getExternalStorageState();
if
( status.equals ( Enviroment.MEDIA_MOUNTED ) )
{
说明有SD卡插入
}
|
2、让某个Activity透明
1
2
3
|
OnCreate中不设Layout
this
.setTheme(R.style.Theme_Transparent);
以下是Theme_Transparent的定义(注意[url=http:
//www.juapk.com/thread-325-1-1.html]transparent_bg[/url]是一副透明的图片)
|
3、在屏幕元素中设置句柄
使用Activity.findViewById来取得屏幕上的元素的句柄.使用该句柄您可以设置或获取任何该对象外露的值.
1
2
|
TextView msgTextView = (TextView)findViewById(R.id.msg);
msgTextView.setText(R.string.push_me);
|
4、发送短信
1
2
3
4
5
6
|
String body=”
this
is mms demo”;
Intent mmsintent =
new
Intent(Intent.ACTION_SENDTO, Uri.fromParts(”smsto”, number,
null
));
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE,
true
);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT,
true
);
startActivity(mmsintent);
|
5、发送彩信
01
02
03
04
05
06
07
08
09
10
11
|
StringBuilder sb =
new
StringBuilder();
sb.append(”file:
//”);
sb.append(fd.getAbsoluteFile());
Intent intent =
new
Intent(Intent.ACTION_SENDTO, Uri.fromParts(”mmsto”, number,
null
));
// Below extra datas are all optional.
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT, subject);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI, sb.toString());
intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, composeMode);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, exitOnSent);
startActivity(intent);
|
6、显示toast
1
|
Toast.makeText(
this
._getApplicationContext(), R.string._item, Toast.LENGTH_SHORT).show();
|
7、发送Mail
1
2
3
4
5
6
|
mime = “img/jpg”;
shareIntent.setDataAndType(Uri.fromFile(fd), mime);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fd));
shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
shareIntent.putExtra(Intent.EXTRA_TEXT, body);
|
8、注册一个BroadcastReceiver
01
02
03
04
05
06
07
08
09
10
11
12
|
registerReceiver(mMasterResetReciever,
new
IntentFilter(”OMS.action.MASTERRESET”));
private
BroadcastReceiver mMasterResetReciever =
new
BroadcastReceiver()
{
public
void
onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if
(”oms.action.MASTERRESET”.equals(action) )
{
RecoverDefaultConfig();
}
}
};
|
9、定义ContentObserver,监听某个数据表
01
02
03
04
05
06
07
08
09
10
|
private
ContentObserver mDownloadsObserver =
new
DownloadsChangeObserver(Downloads.CONTENT_URI);
private
class
DownloadsChangeObserver
extends
ContentObserver
{
public
DownloadsChangeObserver(Uri uri)
{
super
(
new
Handler());
}
@Override
public
void
onChange(
boolean
selfChange) {}
}
|
10、获得 手机UA
1
2
3
4
5
|
public
String getUserAgent()
{
String user_agent = ProductProperties.get(ProductProperties.USER_AGENT_KEY,
null
);
return
user_agent;
}
|
11、清空手机上cookie
1
2
|
CookieSyncManager.createInstance (getApplicationContext() );
CookieManager.getInstance().removeAllCookie();
|
12、建立GPRS连接
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
//Dial the GPRS link.
private
boolean
openDataConnection()
{
// Set up data connection.
DataConnection conn = DataConnection.getInstance();
if
( connectMode ==
0
)
{
ret = conn.openConnection ( mContext, “cmwap”,
"cmwap”, "
cmwap” );
}
else
{
ret = conn.openConnection(mContext, “cmnet”,
""
,
""
);
}
}
|
13、PreferenceActivity 用法
01
02
03
04
05
06
07
08
09
10
|
public
class
Setting
extends
PreferenceActivity
{
public
void
onCreate ( Bundle savedInstanceState )
{
super
.onCreate ( savedInstanceState );
addPreferencesFromResource ( R.xml.settings );
}
}
[b]Setting.xml: [/b]
Android:key=”seting2″ android:title=”
@string
/seting2″ android:summary=”
@string
/seting2″/> android:key=”seting1″ android:title=”
@string
/seting1″ android:summaryOff=”
@string
/seting1summaryOff android:summaryOn=”
@stringseting1summaryOff
”/>
|
14、通过HttpClient从指定server获取数据
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
DefaultHttpClient httpClient =
new
DefaultHttpClient();
HttpGet method =
new
HttpGet(“[url=http:
//www.juapk.com/thread-315-1-1.html]http://www.juapk.com/thread-315-1-1.html[/url] ”);
HttpResponse resp;
Reader reader =
null
;
try
{
// AllClientPNames.TIMEOUT
HttpParams params =
new
BasicHttpParams();
params.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT,
10000
);
httpClient.setParams(params);
resp = httpClient.execute(method);
int
status = resp.getStatusLine().getStatusCode();
if
(status != HttpStatus.SC_OK)
{
return
false
;
}
// HttpStatus.SC_OK;
return
true
;
}
catch
(ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch
(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if
(reader !=
null
)
try
{
reader.close();
}
catch
(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
15、在当前Activity中启动另外一个Activity
1
|
startActivity(
new
Intent(
this
,目标Activity.
class
));
|
16、从当前ContentView从查找控件
1
2
|
(Button)findViewById(R.id.btnAbout)
R.id.btnAbout指控件id。
|
17、 获取屏幕宽高
1
2
3
4
5
|
DisplayMetrics dm =
new
DisplayMetrics();
//获取窗口属性
getWindowManager().getDefaultDisplay().getMetrics(dm);
int
screenWidth = dm.widthPixels;
//320
int
screenHeight = dm.heightPixels;
//480
|
18、 无标题栏、全屏
1
2
3
4
5
6
|
//无标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);
//全屏模式
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
注意在setContentView()之前调用,否则无效。
|
19、 调用android自带的模块
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
a:调用Web浏览器
Uri myBlogUri = Uri.parse(
"http://xxxxx.com"
);
Intent intent =
new
Intent(Intent.ACTION_VIEW, myBlogUri);
b:地图
Uri mapUri = Uri.parse(
"geo:38.899533,-77.036476"
);
Intent intent =
new
Intent(Intent.ACTION_VIEW, mapUri);
c:调拨打电话界面
Uri telUri = Uri.parse(
"tel:100861"
);
Intent intent =
new
Intent(Intent.ACTION_DIAL, telUri);
d:直接拨打电话
Uri callUri = Uri.parse(
"tel:100861"
);
Intent intent =
new
Intent(Intent.ACTION_CALL, callUri);
e:卸载
Uri uninstallUri = Uri.fromParts(
"package"
,
"xxx"
,
null
);
Intent intent =
new
Intent(Intent.ACTION_DELETE, uninstallUri);
f:安装
Uri installUri = Uri.fromParts(
"package"
,
"xxx"
,
null
);
Intent intent =
new
Intent(Intent.ACTION_PACKAGE_ADDED, installUri);
g:播放
Uri playUri = Uri.parse(
"file:///sdcard/download/everything.mp3"
);
Intent intent =
new
Intent(Intent.ACTION_VIEW, playUri);
h:掉用发邮件
Uri emailUri = Uri.parse(
"mailto:xxxx@gmail.com"
);
Intent intent=
new
Intent(Intent.ACTION_SENDTO, emailUri);
i:发邮件
Intent intent =
new
Intent(Intent.ACTION_SEND);
String[] tos = {
"xxxx@gmail.com"
};
String[] ccs = {
"xxxx@gmail.com"
};
intent.putExtra(Intent.EXTRA_EMAIL, tos);
intent.putExtra(Intent.EXTRA_CC, ccs);
intent.putExtra(Intent.EXTRA_TEXT,
"body"
);
intent.putExtra(Intent.EXTRA_SUBJECT,
"subject"
);
intent.setType(
"message/rfc882"
);
Intent.createChooser(intent,
"Choose Email Client"
);
j:发短信
Uri smsUri = Uri.parse(
"tel:100861"
);
Intent intent=
new
Intent(Intent.ACTION_VIEW, smsUri);
intent.putExtra(
"sms_body"
,
"yyyy"
);
intent.setType(
"vnd.android-dir/mms-sms"
);
k:直接发邮件
Uri smsToUri = Uri.parse(
"smsto://100861"
);
Intent intent=
new
Intent(Intent.ACTION_SENDTO, smsToUri);
intent.putExtra(
"sms_body"
,
"yyyy"
);
l:发彩信
Uri mmsUri = Uri.parse(
"content://media/external/images/media/23"
);
Intent intent=
new
Intent(Intent.ACTION_SEND);
intent.putExtra(
"sms_body"
,
"yyyy"
);
intent.putExtra(Intent.EXTRA_STREAM, mmsUri);
intent.setType(
"image/png"
);
|
20、 Android中在非UI线程里更新View的不同方法
1
2
3
4
|
Activity.runOnUiThread( Runnable )
View.post( Runnable )
View.postDelayed( Runnable,
long
)
Hanlder
|
21、 全屏显示窗口
1
2
|
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
|
22、 取得屏幕大小
01
02
03
04
05
06
07
08
09
10
|
方法A:
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
hAndW[
0
] = display.getWidth();
hAndW[
1
] = display.getHeight();
方法B:
DisplayMetrics dm =
new
DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
hAndW[
0
] = dm.widthPixels;
hAndW[
1
] = dm.heightPixels;
|
23、 调浏览器 载入网址
1
2
3
|
Uri uri = Uri.parse(
"http://www.google.com"
);
Intent it =
new
Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
|
24、 取得内存大小
01
02
03
04
05
06
07
08
09
10
11
|
ActivityManager.MemoryInfo outInfo =
new
ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(outInfo);
//可用内存
outInfo.availMem
//是否在低内存状态
outInfo.lowMemory
取得[url=http:
//www.juapk.com/thread-325-1-1.html]ScrollView[/url]的实际高度
scrollview.getHeight()
scrollview.getMeasuredHeight()
scrollview.compute()
scrollview.getLayoutParams().height
|
25、 监听App安装/卸载事件
01
02
03
04
05
06
07
08
09
10
11
12
|
A.Define a
class
derived from
class
BroadcastReceiver;
B.Register broadcast receiver;
MyBroadcastReceiver myReceiver =
new
MyBroadcastReceiver();
IntentFilter filter =
new
IntentFilter(Intent.ACTION_PACKAGE_INSTALL);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
...
filter.addDataScheme(
"package"
);
//This line is very important. Otherwise, broadcast can't be received.
registerReceiver(myReceiver, filter);
Notes: The
package
name is Intent.mData. Intent.mData is not available in SDK
1.0
, but it can be retrieved by calling Intent.getDataString();
|
26、 取得IP地址
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
A.
//Connect via WIFI 通过wifi
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int
ipAddress = wifiInfo.getIpAddress();
B.
//Connect via GPRS通过gprs
public
String getLocalIpAddress(){
try
{
for
(Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){
NetworkInterface intf = en.nextElement();
for
(Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){
InetAddress inetAddress = enumIpAddr.nextElement();
if
(!inetAddress.isLoopbackAddress()){
return
inetAddress.getHostAddress().toString();
}
}
}
}
catch
(SocketException ex){
Log.e(S.TAG, ex.toString());
}
return
null
;
}
|
27、 ListView 后面adapter数据已更改,但是ListView没有收到Notification
1
2
|
首先,必须将 更新adapter数据的代码放在:Handler.post(Runnable)方法中执行;
然后,如果Adapter数据的来源如果是cursor([url=http:
//www.juapk.com/thread-325-1-1.html]CursorAdapter[/url])的话 可以cursor.requery一下,如果是别的可以强制调用一下notifyChange, notifyChange 会调用 invalidate 进行重绘;
|
28、 模拟HOME键
1
2
3
4
|
Intent i=
new
Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
|
29、 设置焦点
1
2
3
|
editText.setFocusable(
true
);
editText.requestFocus();
editText.setFocusableInTouchMode(
true
);
|
30、 使用Toast输出一个字符串
1
2
3
|
public
void
DisplayToast(String str) {
Toast.makeText(
this
,str,Toast.LENGTH_SHORT).show();
}
|
31、 把一个字符串写进文件
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public
void
writefile(String str, String path) {
File file;
FileOutputStream out;
try
{
// 创建文件
file =
new
File(path);
file.createNewFile();
//打开文件file的OutputStream
out =
new
FileOutputStream(file);
String infoToWrite = str;
//将字符串转换成byte数组写入文件
out.write(infoToWrite.getBytes());
//关闭文件file的OutputStream
out.close();
}
catch
(IOException e) {
// 将出错信息打印到Logcat
DisplayToast(e.toString());
}
}
|
32、 把文件内容读出到一个字符串
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public
String getinfo(String path) {
File file;
String str=
""
;
FileInputStream in;
try
{
//打开文件file的InputStream
file =
new
File(path);
in =
new
FileInputStream(file);
//将文件内容全部读入到byte数组
int
length = (
int
)file.length();
byte
[] temp =
new
byte
[length];
in.read(temp,
0
, length);
//将byte数组用UTF-8编码并存入display字符串中
str = EncodingUtils.getString(temp,TEXT_ENCODING);
//关闭文件file的InputStream
in.close();
}
catch
(IOException e) {
DisplayToast(e.toString());
}
return
str;
}
|
33、 调用Android installer安装和卸载程序
1
2
3
4
5
6
|
Intent intent =
new
Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(
new
File(
"/sdcard/WorldCupTimer.apk"
)),
"application/vnd.android.package-archive"
);
startActivity(intent);
//安装 程序
Uri packageURI = Uri.parse(
"package:zy.dnh"
);
Intent uninstallIntent =
new
Intent(Intent.ACTION_DELETE, packageURI);
startActivity(uninstallIntent);
//正常卸载程序
|
34、 结束某个进程
1
|
activityManager.restartPackage(packageName);
|
35、 设置默认来电铃声
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public
void
setMyRingtone() {
File k =
new
File(
"/sdcard/Shall We Talk.mp3"
);
// 设置歌曲路径
ContentValues values =
new
ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE,
"Shall We Talk"
);
values.put(MediaStore.MediaColumns.SIZE,
8474325
);
values.put(MediaStore.MediaColumns.MIME_TYPE,
"audio/mp3"
);
values.put(MediaStore.Audio.Media.ARTIST,
"Madonna"
);
values.put(MediaStore.Audio.Media.DURATION,
230
);
values.put(MediaStore.Audio.Media.IS_RINGTONE,
true
);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION,
false
);
values.put(MediaStore.Audio.Media.IS_ALARM,
false
);
values.put(MediaStore.Audio.Media.IS_MUSIC,
false
);
// Insert it into the database
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
Uri newUri =
this
.getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(
this
, RingtoneManager.TYPE_RINGTONE, newUri);
}
需要的权限
<uses-permission android:name=
"android.permission.WRITE_SETTINGS"
></uses-permission>
模拟HOME按键
Intent i=
new
Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
|
36、 打开某一个联系人
1
2
3
4
5
6
|
Intent intent=
new
Intent();
String data =
"content://contacts/people/1"
;
Uri uri = Uri.parse(data);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
|
37、 发送文件
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
void
sendFile(String path) {
File mZipFile=
new
File(path);
Intent intent =
new
Intent(Intent.ACTION_SEND);
// intent.setClassName("com.android.bluetooth", "com.broadcom.bt.app.opp.OppLauncherActivity");
// intent.setClassName("com.android.bluetooth", "com.android.bluetooth.opp.BluetoothOppLauncherActivity");
intent.putExtra(
"subject"
, mZipFile
.getName());
//
intent.putExtra(
"body"
,
"content by chopsticks"
);
// 正文
intent.putExtra(Intent.EXTRA_STREAM,
Uri.fromFile(mZipFile));
// 添加附件,附件为file对象
if
(mZipFile.getName().endsWith(
".gz"
)) {
intent
.setType(
"application/x-gzip"
);
// 如果是gz使用gzip的mime
}
else
if
(mZipFile.getName().endsWith(
".txt"
)) {
intent.setType(
"text/plain"
);
// 纯文本则用text/plain的mime
}
else
if
(mZipFile.getName().endsWith(
".zip"
)) {
intent.setType(
"application/zip"
);
// 纯文本则用text/plain的mime
}
else
{
intent
.setType(
"application/octet-stream"
);
// 其他的均使用流当做二进制数据来发送
}
// startActivity(intent);
startActivity(
Intent.createChooser(intent,
"选择蓝牙客户端"
));
}
|
38、 获取正在运行的进程
01
02
03
04
05
06
07
08
09
10
11
|
在Android中获取系统正在运行的进程方法是getRunningAppProcesses()。我们首先通过ActivityManager _ActivityManager = (ActivityManager)
this
.getSystemService(Context.ACTIVITY_SERVICE);
//来获取系统的全局状态,然后通过调用getRunningAppProcesses()方法就可以获得系统正在运行的进程。
ActivityManager _ActivityManager = (ActivityManager)
this
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> list = _ActivityManager
.getRunningAppProcesses();
int
i = list.size();
Log.i(
"tag"
, String.valueOf(i));
for
(
int
j =
0
; j < list.size(); j++) {
Log.i(
"tag"
, list.get(j).processName);
}
|
39、 Andriod悬浮窗口的实现
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
|
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
;
wmParams.flags=
40
;
wmParams.width=
40
;
wmParams.height=
40
;
wm.addView(bb, wmParams);
}
}
|
最后
以上就是魁梧电话为你收集整理的Android 编程实用代码大全的全部内容,希望文章能够帮你解决Android 编程实用代码大全所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复