您的位置:首页 > 编程语言

10分钟过“第一行代码”

2016-01-24 00:48 288 查看
1.不显示标题:
requestWindowFeature(Window.FEATURE_NO_TITLE);


2.打开网页:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(“http://www.baidu.com”));
startActivity(intent);


3.解决活动被回收时数据得不到保存的问题:
(1)先保存数据:
Protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
String tempData = “临时数据”;
outState.putString(“data_key”,tempData);
}


(2)恢复数据:
//1.在OnCreate中恢复
If(savedInstanceState != null){
String tempData = savedInstanceState.getString(“data_key”);
}
//2.在onRestoreInstanceState中恢复
public void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
message = savedInstanceState.getString("data_key");
}

4.新建ActivityCollector类作为活动管理器
/**
*1.在继承Activity的BaseActivity中的onCreate方法中调用ActivityCollector.addActivity(this);
*2.在onDestroy方法中ActivityCollector.removeActivity(this);
*3.最后在其他继承BaseActivity的activity中用ActivityCollector.finishAll()就可直接退出程序
*/
Public class ActivityCollector{
Public static List<Activity> activities = new ArrayList<Activity>();

Public static void addActivity(Activity activity){
Activities.add(activity);
}

Public static void removeActivity(Activity activity){
Activities.remove(activity);
}

Public static void finishAll(){
Activities.clear();
}
}

5.引用外部布局:
<include layout="@layout/title"/>

6.动态添加碎片:
(1)创建待添加的碎片实例
(2)获取到FragmentManager,在活动中可以直接调用getFragmentManager()方法得到。
(3)开启一个事务,通过调用beginTransaction()方法开启。
(4)向容器内加入碎片,一般使用replace()方法实现,需要传入容器的id和待添加的碎片实例。
(5)提交事务,调用commit()方法来完成。
7.在碎片中模拟返回栈:在第6点的(4)小点加入transaction.addToBackStack(null);
8.碎片和活动之间进行通信:
//Activity获取碎片实例
OthersFragment otherFragment = (OthersFragment)getFragmentManager.findFragmentById(R.id.others_fragment);
//碎片获取Activity实例
MainActivity activity = (MainActivity)getActivity();

9.碎片回调方法:
EndFragment
(1)onAttach()当碎片和活动建立关联时调用
(2)onCreateView()为碎片创建视图(加载布局)时调用
(3)onActivityCreated()确保与碎片相关联的活动一定已经创建完毕时调用
(4)onDestroyView()当与碎片关联的视图被移除时调用
(5)onDetach()当碎片和活动解除关联时调用
10.动态加载布局的技巧:使用限定符
11.动态注册监听网络变化:在MainActivity中定义一个内部类NetworkChangeReceiver(继承自BroadcastReceiver),并重写父类的onReceive()方法
//注册广播
private IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(“android.net.conn.CONNECTIVITY_CHANGE”);
private NetworkChangeReceiver networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver,intentFilter);

//动态注册的需在onDestroy()中解除广播:
unregisterReceiver(networkChangeReceiver);

//广播接收者:
class NetworkChangeReceiver extends BroadcastReceiver{
public void onReceive(Context context,Intent intent){
//接收到广播处理事务
ConnectivityManager connectionManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
If(networkInfo != null&&networkInfo.isAvailable()){
//有网
}else{
//无网
}
}
}

12.静态注册实现开机启动:新建一个BootCompleteReceiver类继承BroadcastReceiver,然后在AndroidManifest.xml把广播接收器的类名注册进去
<receiver android:name=”.BootCompleteReceiver”>
<intent-filter>
<action android:name=”android.intent.action.BOOT_COMPLETED”/>
</intent-filter>
</receiver>
//监听系统开机广播声明权限:
<uses-permission android:name=”android.permission.RECEIVE_BOOT_COMPLETED”/>

13.发送自定义广播:
(1)标准广播:
//注册:
<receiver android:name=”.MyBroadcastReceiver”>
<intent-filter>
<action android:name=”com.example.broadcasttest.MY_BROADCAST”/>
</intent-filter>
</receiver>;
//发送广播:
Intent intent = new Intent(“com.example.broadcasttest.MY_BROADCAT”);sendBroadcast(intent);

(2)有序广播(可以拦截)
//发送广播:
sendOrderedBroadcast(intent,null);
//注册:添加
<intent-filter android:priority=”100”><action ../>…;
//截断广播:
abortBroadcast();

14.发送本地广播(动态注册):先通过LocalBroadcastManager的getInstance()得到实例,注册广播:LocalBroadcastManager.registerReceiver();发送广播LocalBroadcastManager.sendBroadcast()
15.文件存储:
//(1)
public void save(){
String data=”save content”;
FileOutputStream fos = null;
BufferedWriter writer = null;
try{
fos = openFileOutput(“data”,Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write(data);
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(writer!=null){
writer.close()}
}catch(IOException e){
e.pr
4000
intStackTrace();
}
}
}
//(2)
public String load(){
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try{
in = openFileInput(“data”);
reader = new BufferedReader(new InputStreamReader(in));
String line = “”;
while((line = reader.readLine())!=null){
content.append(line);
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(reader!=null){
try{
reader.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
return content.toString();
}

16.SharedPreferences存储:
//(1)
SharedPreferences.Editor editor = getSharedPreferences(“data”,MODE_PRIVATE).edit();
editor.putString(“name”,”Tom”);
editor.putInt(“age”,28);
editor.commit();
//(2)
SharedPreferences pref = getSharedPreferences(“data”,MODE_PRIVATE);
String name = pref.getString(“name”,””);
int age = pref.getInt(“age”,0);

17.内容提供器(Content Provider):
内容URI最标准的格式写法(协议(content),权限(包名+provider)和路径(表名));如content://com.example.app.provider/table1
//(1)读取系统联系人数据:
List<String> contactsList = new ArrayList<String>();
private void readContacts(){
Cursor cursor = null;
try{
//查询联系人数据
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
while(cursor.moveToNext()){
//获取联系人姓名
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
//获取联系人手机号
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsList.add(displayName+”\n”+number);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(cursor!=null){cursor.close();}
}
}
<uses-permission android:name=”android.permission.READ_CONTACTS”/>
(2)创建内容提供器:
public class MyProvider extends ContentProvider {
@Override
public boolean onCreate() {
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
return 0;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@Override
public String getType(Uri uri) {
return null;
}
}
//getType()方法用于获取Uri对象所对应的MIME类型。一个内容URI所对应的MIME字符串由3部分组成。(必须以vnd开头。如果内容URI以//路径结尾,则后接android.cursor.dir/,如果内容URI以id结尾,则后接android.cursor.item/。最后接上vnd.<authority>.<path>)
//例content://com.example.app.provider/table这个内容URI,对应MIME类型为:vnd.android.cursor.dir/vnd.com.example.app.provider.table

<provider
android:name=”com.example.databasetest.DatabaseProvider”
android:authorities = “com.example.databasetest.provider”>
</provider>

18.通知:
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,”This is ticker text”,System.currentTimeMillis());
Intent intent = new Intent(this,NotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatesEventInfo(this,”This is content title”,”This is content text”,pi);
notification.defaults = Notification.DEFAULT_ALL;
manager.notify(1,notification);
//取消通知:
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
manager.cancel(1);

19.接收短信:
private IntentFilter receiveFilter = new IntentFilter();
receiveFilter.addAction(“android.provider.Telephony.SMS_RECEIVED”);
receiveFilter.setPriority(100);//设置权限
private MessageReceiver messageReceiver = new MessageReceiver();
registerReceiver(messageReceiver,receiveFilter);

class MessageReceiver extends BroadcastReceiver{
public void onReceive(Context context,Intent intent){
abortBroadcast();//拦截短信

Bundle bundle = intent.getExtras();
Object[] pdus = (Object[])bundle.get(“pdus”);//提取短信消息
SmsMessage[] message = new SmsMessage[pdus.length];
for(int i = 0;i<messages.length;i++){
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
String address = messages[0].getOriginatingAddress();//获取发送方号码
String fullMessage = “”;
for(SmsMessage message:message){
fullMessage += message.getMessageBody();//获取短信内容
}
sender.setText(address);
content.setText(fullMessage);
}
}
<uses-permission android:name=”android.permission.RECEIVE_SMS”/>

20.发送短信:
private IntentFilter sendFilter;
private SendStatusReceiver sendStatusReceiver;

sendFilter = new IntentFilter();
sendFilter.addAction(“SENT_SMS_ACTION”);
sendStatusReceiver = new SendStatusReceiver();
registerReceiver(sendStatusReceiver,sendFilter);

SmsManager smsManager = SmsManager.getDefault();
Intent sentIntent = new Intent(“SENT_SMS_ACTION”);
PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this,0,sentIntent,0);
smsManager.setTextMessage(“手机号码”,null,”内容”,pi,null);

class SendStatusReceiver extends BroadcastReceiver{
public void onReceive(Context context,Intent intent){
if(getResultCode() == RESULT_OK){//短信发送成功}else{//短信发送失败}
}
}
<uses-permission android:name=”android.permission.SEND_SMS”/>

21.调用摄像头拍照
public class MainActivity extends Activity{
public static final int TAKE_PHOTO = 1;
public static final int CROP_PHOTO = 2;
private Button takePhoto;
private ImageView picture;
private Uri imageUri;

protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePhoto.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//创建File对象,用于存储拍照后的图片
File outputImage = new File(Environment.getExternalStorageDirectory(),”tempImage.jpg”);
try{
if(outputImage.exists()){
outputImage.delete()
};
outputImage.createNewFile();
}catch(IOException e){
e.printStackTrace();
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent(“android.media.action.IMAGE_CAPTURE”);
Intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,TAKE_PHOTO);//启动相机程序
}
});
}
protected void onActiviyResult(int requestCode,int resultCode,Intent data){
switch(requestCode){
case TAKE_PHOTO:
if(resultCode == RESULT_OK){
Intent intent = new Intent(“com.android.camera.action.CROP”);
intent.setDataAndType(imageUri,”image/*”);
intent.putExtra(“scale”,true);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,CROP_PHOTO);//启动裁剪程序
}
break;
case CROP_PHOTO:
if(resultCode == RESULT_OK){
try{
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
Picture.setImageBitmap(bitmap);
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
break;
}
}
}
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>

22.从相册中选择照片
//创建File对象,用于存储选择的照片

File outputImage = new File(Environment.getExternalStorageDirectory(),"output_image.jpg");

try{

if(outputImage.exists()){
outputImage.delete();
}

outputImage.createNewFile();

}catch(IOException e){
e.printStackTrace();
}

imageUri = Uri.fromFile(outputImage);

Intent intent = new Intent("android.intent.action,GET_CONTENT");

intent.setType("image/*");

intent.putExtra("crop",true);

intent.putExtra("scale",true);

intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);

startActivityForResult(intent,CROP_PHOTO);

23.播放音频:
private MediaPlayer mediaPlayer = new MediaPlayer();
//初始化MediaPlayer
private void initMediaPlayer(){
try{
File file = new File(EnvironMent.getExternalStorageDirectory(),”music.mp3”);
mediaPlayer.setDataSource(file.getPath());//指定音频文件路径
mediaPlayer.prepare();//让MediaPlayer进入准备状态
}catch(Exception e){e.printStackTrace():}
}

24.播放视频:
private VideoView videoView = (VideoView)findViewById(R.id.video_view);
private void initVideoPath(){
File file = new File(Environment.getExternalStorageDirectory(),”movie.3gp”):
videoView.setVideoPath(file.getPath());//指定视频文件路径
}
if(!videoView.isPlaying()){videoView.start();}
if(videoView.isPlaying()){videoView.pause();}
if(videoView.isPlaying()){videoView.resume();}

25.线程:
//1.
class MyThread extends Thread{
public void run(){}
}
new MyThread().start();
//2.
class MyThread implements Runnable{
public void run();
}
//3.
MyThread myThread = new MyThread();
new Thread(myThread).start();
//4.
new Thread(new Runnable(){public void run(){}}).start();

26.子线程更新UI:
//1.
public static final int UPDATE_TEXT = 1;
private Handler handler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
case UPDATE_TEXT:
//在这里进行UI操作
break;
default:
break;
}
}
}

new Thread(new Runnable(){
public void run(){
Message message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);//将Message对象发送出去
}
}).start();
//2.使用AsyncTask:
class DownloadTask extends AsyncTask<Void,Integer,Boolean>{
protected void onPreExecute(){
progressDialog.show();//显示进度对话框
}
//子线程中运行,执行具体的耗时任务
protected Boolean doInBackground(Void… params){
try{
while(true){
int downloadPercent = doDownload();//获取进度
publishProgress(downloadPercent);
if(downloadPercent >= 100){break;}
}
}catch(Exception e){return false;}
return true;
}
//可进行UI操作
protected void onProgressUpdate(Integer… values){
//在这里更新下载进度
progressDialog.setMessage(“Downloaded ”+values[0] +”%”);
}
//主线程中运行,进行一些任务的收尾工作
protected void onPostExecute(Boolean result){
progressDialog.dismiss();//关闭进度对话框
//提示下载结果
if(result){Toast.makeText(context,”succeeded”,Toast.LENGTH_SHORT).show();}
else{ Toast.makeText(context,”failed”,Toast.LENGTH_SHORT).show();}
}
}

//启动:
new DownloadTask().execute();

27.服务:
public class MyService extends Service{
public IBinder onBind(Intent intent){return null;}
public void onCreate(){super.onCreate();}
public int onStartCommand(Intent intent,int flags,int startId){return super.onStartCommand(intent,flags,startId);}
public void onDestory(){super.onDestory();}
}
<service android:name=”.MyService”/>
//启动:
Intent i = new Intent(this,MyService.class); startService(i);
//停止:
Intent i = new Intent(this,MyService.class); stopService(i);
//自行停止:
stopSelf();

28.活动与服务进行通信:
//1.
public class MyService extends Service{
private DownloadBinder mBinder = new DownloadBinder();
class DownloadBinder extends Binder{
public void startDownload(){}
public int getProgress(){}
}
public IBinder onBind(Intent intent){return mBinder}
}
//2.
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection(){
public void onServiceDisconnected(ComponentName name){}
public void onServiceConnected(ComponentName name,IBinder service){
downloadBinder = (MyService.DownloadBinder)service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
}
//3.
Intent bindIntent = new Intent(this,MyService.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE);//绑定服务
unbindService(connection);//解绑服务

29.前台服务(防止服务被回收掉或需求)
public class MyService extends Service{
…
public void onCreate(){
super.onCreate();
Notification notification = new Notification(R.drawable.ic_launcher,”Notification comes”,System.currentTimeMillis());
Intent notificationIntent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
notification.setLatesEventInfo(this,”This is title”,”this is content”,pendingIntent);
startForeground(1,notification);
}
}

30.后台定时任务:
//1.
public class LongRunningService extends Service{
public IBinder onBind(Intent intent){return null;}
public int onStartCommand(Intent intent,int flags,int startId){
new Thread(new Runnable(){
public void run(){}
}).start();
AlarmManager manager = (AlarmManager)getSystemService(ALARM_SERVICE);
int anHour = 60*60*1000;//一小时的毫秒数
long triggerAtTime = SystemClock.elapsedRealtime()+anHour;
Intent i = new Intent(this,AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this,0,i,0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,trigerAtTime,pi);
return super.onStartCommand(intent,flags,startId);
}
}
//2.
public class AlarmReceiver extends BroadcastReceiver{
public void onReceive(Context context,Intent intent){
Intent i = new Intent(context,LongRunningService.class);
context.startService(i);
}
}
//3.
Intent i = new Intent(this,LongRunningService.class);
startService(i);
//4.
<service android:name=”.LongRunnigService”/>
<receiver android:name=”.AlarmReceiver”/>


32.发送HTTP请求:
//1.HttpURLConnection:
private void sendRequestWithHttpURLConnection(){
new Thread(new Runnable(){
public void run(){
HttpURLConnection connection = null;
try{
URL url = new URL(“http://www.baidu.com”);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod(“GET”);
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
//对获取到的输入流进行读取
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
While((line = reader.readLine())!=null){response.append(line);}
Message message = new Message();
Message.what = 0;
Message.obj = response.toString();//将服务器返回的结果放到Message中
Handler.sendMessage(message);
}catch(Exception e){e.printStackTrace();}
finally{if(connection!=null){conncetion.disconnect();}}
}
}).start();
}
//2.HttpClient:
ad8c

private void sendRequestWithHttpClient(){
new Thread(new Runnable(){
public void run(){
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(“http://www.baidu.com”);
HttpResponse httpResponse = httpClient.excute(httpGet);
If(httpResponse.getStatusLine().getStatusCode()==200){
HttpEntity entity = httpResponse.getEntity();
String response = EnityUtils.toString(entity,”utf-8”);
Message message = new Message();
message.what = 0;
message.obj = response.toString();
handler.sendMessage(message);
}
}
}
}).start();
}

33.解析xml数据:pull和sax
34.解析json数据:
//1.使用JSONObject
private void parseJSONWithJSONObject(String jsonData){
JSONArray jsonArray = new JSONArray(jsonData);
for(int i = 0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString(“id”);
String name = jsonObject.getString(“name”);
}
}
//2.使用GSON:
//先添加GSON的Jar包:http://code.google.com/p/google-gson/downloads/list
public class App{
private String id;
private String name;
//get和set方法
}

private void parseJSONWithGSON(String jsonData){
Gson gson = new Gson();
List<App> appList = gson.fromJson(jsonData,new TypeToken<List<App>>(){}.getType());
for(App app:appList){app.getId();app.getName();}
}

35.优化网络编程:
//1.定义一个接口:
public interface HttpCallbackListener{
void onFinish(String response);
void onError(Exception e);
}
//2.网络请求:
public class HttpUtil{
public static void sendHttpRequest(final String address,final HttpCallbackListener listener){
new Thread(new Runnable(){
public void run(){
HttpURLConnection connection = null;
try{
URL url = new URL(address);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod(“GET”);
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while((line = reader.readLine())!=null){
response.append(line);
}
if(listener!=null){
//回调onFinish()方法
listener.onFinish(response.toString());
}
}catch(Exception e){
if(listener!=null){
//回调onError();方法
listener.onError(e);
}
}finally{
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
}

//3.调用:
HttpUtil.sendHttpRequest(address,new HttpCallbackListener(){
public void onFinish(String response){//在这里根据返回内容执行具体的逻辑}
public void onError(Exception e){//在这里对异常情况进行处理}
});
--以上是用来回顾“第一行代码”,如需详细资料,自行看书。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息