android小結

一.php

對與java讀寫文件的操做:java

字節流:android

//filename  能夠是文件名,能夠是文件路徑web

FileOutputStream outputStream=new FileOutputStream(filename);數據庫

//filename  能夠是文件名,能夠是文件路徑api

//append 是否追加數組

FileOutputStream outputStream=new FileOutputStream(filenamebool append);瀏覽器

 

outputStream.write(byte[]);緩存

outputStream.close();服務器

 

//filename 文件名或文件路徑

FileInputStream inputStream=new FileInputStream(filename);

Byte[] buffer=new byte[1024];//緩存數組;

 

//inputStream.read(buffer);//返回值是int型;

讀的時候要先把這些數據放入內存中或者是一個FileOutputStream流中

//FileOutputStream outputStream=new FileOutputStream(filename);

ByteArrayOutpouStream outputStream=new ByteArrayOutputStream();

Int len=0;

While((len=inputStream.read(buffer))!=-1)

{

  outputStream.write(buffer,0,len);

}

 

.

<?xml version=」1.0」 encoding=」UTF-8」>

<persons>

  <person id=」1」>

   <name>wanghe</name>

   <age>20</age>

  </person>

  

</persons>

對於使用Pull解析器來解析XML

List<Person> persons=null;

Person person=null;

File file=new File(filename);

FileinputStream input=new FileInputStream(file);

XmlPullParser pullParser=XML.newPullParser();

pullParser.setInput(input,」UTF-8」);

Int event=pullParser.getEventType();

While(event!=XmlPullParser.END_DOCUMENT)

{

  Switch(event)

{

  Case XmlPullParser.START_DOCUMENT:

Persons=new ArrayList<Person>();

Break;

Case XmlPullParser.START_TAG

 If(「person」.equal(pullParser.getName()))

{

    Person=new Person();

   String id=pullParser.getAttributeValue(0);

  person.setId(id);

 

}

Else if(「name」.equal(pullParser.getName()))

{

 String name=pullParser.nextText();

person.setName(name);

}

Else if(「age」.equal(pullParser.getName()))

{

 String age=pullParser.nextText();

person.setAge(age);

}

Break;

Case XmlPullParser.END_TAG:

If(「person」.equal(pullParser.getName()))

{

 

   Persons.add(person);

Person=null;

}

 

 

  

}

 

 

Event=pullParser.next();

}

 

 

Return persons;

對與保存一個XML

File file=new File(filename)

FileOutputStream out=new FileOutputStream(file);

XmlSerializer ser=XML.newXmlSerializer();

Ser.setOutput(out,」UTF-8」);

ser.startDocument(「UTF-8」,true);

ser.srartTag(null,」persons」)//第一個參數是namespace 第二個是節點名稱

For(Person person:persons)

{

er.startTag(null, "person");

ser.attribute(null, "id", person.getId());

ser.startTag(null, "name");

ser.text(person.getName());

ser.endTag(null,"name");

ser.startTag(null, "age");

ser.text(person.getAge());

ser.endTag(null,"age");

ser.endTag(null, "person");

}

ser.endTag();

ser.endDocument();

Out.flush();

Out.close();

三.sharedPreferences

對於sharedPrefernces是對用戶數據的一個自定義保存數據

好比每次等qq不用本身再輸入賬號和密碼而是從之前輸入的數據存儲後再調出

SharedPreferences share=context.getSharedPreferences("ifo",Context.MODE_PRIVATE);//參數一是對xml文件名的定義,參數二是對此文件的權限定義,context是上下文的意思,如getApplicationContext()等等;

 

Editor editor=share.edit();

editor.putString(「key」,」value」);

Editor.commit();

 

 

對於怎麼取出數據就是;

SharedPreferences share=context.getSharedPreferences("ifo",Context.MODE_PRIVATE);

String value=share.getString(「key」,」defaultvalue」);//根據key來取值,那個defaultvalue是默認取到的值;

 

四.SQLiteDatabase

  對與SQLite,他要實現SQLiteOpenHelper虛擬類

定義MySQLiteOpenHelper:

Class MySQLiteOpenHelper:SQLiteOpenHelper

{

   //實現一個構造函數

 Public MySQLiteOpenHelper(Context context)

{   

  

//context 定義上下文

//databaseName 定義數據庫名字

//CursorFactory 定義遊標工廠,默認爲null,使用系統的

//version 版本號,version>0 version改變時會調用onUpgrade方法

 

Super(context,databaseNAME,CursoeFactory,version)

}

  //實現兩個方法

   

      public void onCreate(SQLiteDatabase db) //在第一次調用是使用,能夠加入多個execSQL()方法

{

// TODO Auto-generated method stub

db.execSQL("create table person (name text ,age text)");//定義一個表;

//爲表初始化數據

//db.execSQL("insert into person(name,age)values (?,?)",new String[]{「wanghe」,」20」});

    

 

}

 

@Override

public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2)//當版本號改變是執行  {

// TODO Auto-generated method stub

//version版本號改變時;

db.execSQL("alert table person add phone text");

   

      

}

}

 

定義SQLiteServer實現數據庫方法

Class SQLiteServer

{

 

 Private MySQLiteOpenHelper mySQL;

   Public SQLiteServer (Context context)

{

      mySQL=new MySQLiteOpenHelper(context);

    

}

 

//查詢

 

   Public Cursor select(String name)

{  

 

SQLiteDatabase db=mySQL.getReadableDatabase();

Cursor cursor=db.rawQuery(「select * from person  where name=?」,new String[]{name});

Db.close();

Return cursor;

 

}

//實現分頁效果,offset是開始,maxdata是查尋個數

 

Public Cursor selectLimit(int offset,int maxdata)

{

   

    SQLiteDatabase db=mySQL.getReadableDatabase();

Cursor cursor=db.rawQuery(「select * from person limit ?,?」 ,new String[]{String.valueof(offset),String.valueof(maxdata)});

Db.close();

 

Return cursor;

 

}

//插入

Public void insert(Person person)

{

  SQLiteDatabase db=mySQL.getWriteableDatabase();

  db.execSQL(「insert into person(name.age) values(?,?)」,new Object[]{person.getName(),person.getAge()});   }

//更新

Public void update(Person person)

{

  SQLiteDatabase db=mySQL.getWriteableDatabase();

  db.execSQL(「update person set age=? Where name=?」,new Object[]{person.getName(),person.getAge()});

Db.close();

    

}

//刪除

Public void delete(String name)

{

 

   SQLiteDatabase db=mySQL.getWriteableDatabase();

   db.execSQL(「delete form person where name=?」,new Object[]{name});

db.close();
}

 

//獲取查詢的個數

Public long getCount()

  SQLiteDatabase db=mySQL.getReadableDatabase();

Cursor cursor=db.rawQuery(「select count(*) from person 「,null);

//因爲只會出現一條記錄

cursor.moveToFirst();

Long count=cursor.getLong(0);

Db.close();

Return count;

 

}

}

 

對伊Cursor這個類,裏面的api

Cursor cursor

若是查詢結果是多個,則用cursro.moveToNext()這個方法

While(cursor.moveToNext())

{

 

//怎麼獲取記錄,cursor.getColumnIndex(「name「)這個方法是獲取name屬性的下標

String name=cursor.getString(cursor.getColumnIndex(「name」));

 

 

}

對於SQLite的併發控制

Public void SqlCommit()

{

  SQLiteDatabase db=mySQL.getWriteableDatabase();

 db.beginTransaction();

 Try

{

  db.execSQL(「........」);

db.execSQL(「..........」);

db.setTransactionSuccessful();//若是不使用次api就只會回滾,不會提交

   

}

 

Finally{

 db.endTransaction();

}

  

 

 

}

五.ListView及各Adapter

對與ListView的使用要用到各類構造器;

SimpleAdapter

Class Person

{

 Public String name;

Public String age;

}

List<Person>persons=new ArrayList<Person>();

List<HashMap<String,String>>listMap=new List<HashMap<String,String>>();

For(Person person:persons)

{

  Map<String ,String>map=new HashMap<String,String>();

Map.put(「name」,person.name);

Map.put(「age」,person.age);

listMap.add(map);

}

SimpleAdapter adapter=new SimpleAdapter(Context context,listMap,R.layout.xml,new String[]{「name」,」age」},new int[]{R.id.txtname,R.is.txtage});

list.setAdapter(adapter);//第一個參宿是上下文context,第二個參數是List<HashMap<String,String>>

第三個參數是,佈局layout,第四個是HashMap裏的key字符串數組,第五個是佈局裏的R.id數組;

對於怎麼取到這樣構造的形式的數據

OnItemClick(AdapterView<?> parent, View view, int position,long id)

{

  //由於存入的是HashMap,則在取時也應是hashmap

 HashMap<String,String>map=HasnMap<String,String>parent.getItemPosition(position);

String name=map.get(「name」);

String age=map.get(「age」);

 

}

 

第二種構造器就是SimpleCursorAdapter,此方法感受就是重在去SQLite裏的Cursor

由於在SQLite裏有Cursor cursor=db.rawQuery(「」,null);

SimpleCursorAdapter adapter=new SimpleCursorAdapter(Context,R.layout.xml,cursor,new String[]{「name」,」age」},new int[]{R.id.txtname,R.id.txtage});

list.setAdapter(adapter);

對於這種的取數據,固然要用到Cursor

OnItemClick(AdapterView<?> parent, View view, int position,long id)

{

   Cursorcursor=(Cursor)parent.getItemPosition(position);

String name=cursor.getString(cursor.getColumnIndex(「name」));

String age=cursor.getString(cursor.getColumnIndex(「n\age」));

 

 

 

}

第三種就是本身寫構造器,繼承BaseAdapter

Class PersonAdapter implements BaseAdapter

{

Private List<Person> persons;//傳入的List

Private int Resouce;//傳入自定義佈局

Private LayoutInflater inflater;//構造一個View

public PersonAdapter(Context context,List<Person> persons,int resource)

   {

   this.persons=persons;

   this.Resource=resource;

inflater=(LayoutInflater)ontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

   }

 

 

@Override

public int getCount() {

// TODO Auto-generated method stub

return persons.size();

}

 

@Override

public Object getItem(int arg0) {

// TODO Auto-generated method stub

return persons.get(arg0);

}

 

@Override

public long getItemId(int arg0) {

// TODO Auto-generated method stub

return arg0;

}

 

對伊getView這個方法,有兩種,一個效率高,一個效率低

@Override

public View getView(int position, View view, ViewGroup arg2) {

// TODO Auto-generated method stub

TextView txtname=null;

TextView txtage=null;

If(view==null)

{

        View=inflater.inflate(this.Resource,null);

 

}

Txtname=(TextView)view.findViewById(R.id.txtname);

Txtage=(TextView)view.findViewById(R.id.txtage);

 

Person person=persons.get(position);

txtname.setText(person.name);

txtage.setText(person.age);

Return view;

 

 

  

}

  //第二種getView

@Override

public View getView(int position, View view, ViewGroup arg2) {

// TODO Auto-generated method stub

      TextView txtname=null;

      TextView txtage=null;

If(view==null)

{

  View=inflater.inflater(Resouce,null);

   CacheView cache=new CacheView();

   Txtname=(TextView)view.findViewById(R.id.txtname);

Txtage=(TextView)view.findViewById(R.id.txtage);

Cache.txtname=txtname;

Cache.txtage=txtage;

view.setTag(cache);

 

 

}

Else

{

 CacheView cache=(CacheView)view.getTag();

 Txtname=cache.txtname;

  Txtage=cache.txtage;

}

Person person=persons.get(position);

txtname.setText(person.name);

txtage.setText(perosn.age);

Return view;

 

     

}

Private final class CacheView

{

 

Public TextView txtname;

Public TextView txtage;

}

 

 

 

}

 

對於這樣的取就簡單了

OnItemClick(AdapterView<?> parent, View view, int position,long id)

{

  Person Person=(Person) parent.getItemAtPosition(position);

String name=person.name;

String age=person.age;

 

 }

六.ContentProvider

 爲別的應用提供數據源

繼承ContentProvider

 

public class TestProvider extends ContentProvider {

   //定義一個全局的變量UriMatcher

private UriMatcher matcher=new UriMatcher(UriMatcher.NO_MATCH);

//定義三個標識變量

private final static int PERSON =1;

private final static int STUDENT=2;

private final static int PERSONID=0;

//爲了取得數據庫因此調用本身定義的SQLiteOpenHelper

private OPSQLHelper SQLHelper=null;

 

   //至關與構造函數

    @Override

    public boolean onCreate() {

// TODO Auto-generated method stub

SQLHelper=new OPSQLHelper(getContext());

matcher.addURI("com.example.dbprovider.prodiver", "person", PERSON);//添加person的匹配,若是匹配則返回PERSON

matcher.addURI("com.example.dbprovider.prodiver", "student", STUDENT);//添加student的匹配,若是匹配則返回STUDENT

 

matcher.addURI("com.example.dbprovider.prodiver", "person/#", PERSONID);//添加person/id的匹配,若是匹配則返回PERSONID

return true;

   }

@Override

public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3,

String arg4) {

// TODO Auto-generated method stub

 

SQLiteDatabase db=SQLHelper.getReadableDatabase();

//能夠經過判斷傳入的Uri來肯定去操做哪一個表

switch(matcher.match(arg0))

{

 

case PERSONID:

long id=ContentUris.parseId(arg0);//這個方法能夠解析出id的值;

if(arg2==null)

{

arg2="id="+id;

}

else

{

arg2+="and id="+id;

}

 

case PERSON:

 

return  db.query("person", arg1, arg2, arg3, null, null, arg4);

 

case STUDENT:

 

default:

throw Exception ;

break;

}

 

return null;

}

@Override

public int delete(Uri arg0, String arg1, String[] arg2) {

// TODO Auto-generated method stub

return 0;

}

 

@Override

public String getType(Uri arg0) {

// TODO Auto-generated method stub

return null;

}

 

@Override

public Uri insert(Uri arg0, ContentValues arg1) {

// TODO Auto-generated method stub

return null;

}

 

 

 

 

 

@Override

public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {

// TODO Auto-generated method stub

return 0;

}

 

}

 

 

怎麼調用Provider提供的方法:

Uri uri=Uri.parse(「」);

ContentReslover reslover=this.getContentReslover();

Reslover.query(uri,,,,,);

Reslover.insert(uri,,);

......

 

 

 

對於ContentProvider要進行監聽事件,包括兩方面,一個是註冊一個監聽觀察者,一個是要有一個發佈者,當觀察者觀察到發佈者發佈改變消息後,就作出反應;

下面一個例子,當插入一個數據後,而後發佈者發佈一個消息,觀察者收到作出反應

 

發佈者:

   getContext().getContentResover().notifyChange(Uri,ContentObserver);發佈一條改變消息

 

觀察者:

this.getContentResolver().registerContentObserver(Uri, true, new ContentObserver1());

 

Class ContentObserver extends ContentObserver

{

     public ContentObserver1() {

super(new Handler());

// TODO Auto-generated constructor stub

}

 

@Override

public void onChange(boolean selfChange) {

// TODO Auto-generated method stub

 

//Do something

 

 

}

  

}

七.網絡服務

獲取網頁內容:

   URL url=new URL(「http://www.baidu.com」);

HttpURLConnection conn=(HttpURLConnection)url.openConnection();

conn.setConnectTimeout(5000);

    conn.setRequestMethod("GET");

    if(conn.getResponseCode()==200)

    {

    

     InputStream is=conn.getInputStream();

     ByteArrayOutputStream os=new ByteArrayOutputStream();

     byte[] buff=new byte[1024];

             Int len=0;

While((len=is.read(buff))!=-1)

{

  Os.write(buff,0,len);

}

String str=os.toString();

Is.close();

Os.close();

 

獲取網頁圖片

 

URL url;

try {

url = new URL(urlPath);

 

HttpURLConnection conn=(HttpURLConnection)url.openConnection();

conn.setConnectTimeout(5000);

conn.setRequestMethod("GET");

if(conn.getResponseCode()==200)

 

{

 

InputStream is=conn.getInputStream();

 

      Bitmap bit=BitmapFactory.decodeStream(is);

      img.setImageBitmap(bit);

 

}

Intent

 對與intent,經常使用來激活下一個activity

經常使用的方法就是:

Intent intent=new Intent(this,newActivity.class);

對於傳數據,有如下幾種方式:

第一種:

放數據:

Intent intent=new Intent(MainActivity.this,NextActivity.class);

intent.putExtra("name", "王賀");

intent.putExtra("age", 21);

startActivity(intent);

取數據:

Intent intent=getIntent();

String name=intent.getStringExtra("name");

int age=intent.getIntExtra("age",0);

Toast.makeText(getApplicationContext(), name+"   "+age, 1).show();

 

第二種:

放數據:

Intent intent=new Intent(MainActivity.this,NextActivity.class);

Bundle bun=new Bundle();

bun.putString("name", "王賀");

bun.putInt("age", 21);

intent.putExtras(bun);

startActivity(intent);

取數據:

Intent intent=getIntent();

Bundle bun=intent.getExtras();

String name=bun.getString("name");

int age=bun.getInt("age");

Toast.makeText(getApplicationContext(), name+"   "+age, 1).show();

 

第三種:傳遞對象:

要對對象類進行封裝:

public class Person implements Parcelable{

 

private int id ;

private String name;

private int age;

 

public int describeContents() {

// TODO Auto-generated method stub

return 0;

}

 

//把數據寫入到Parcel對象

public void writeToParcel(Parcel dest, int flags) {

// TODO Auto-generated method stub

dest.writeInt(id);

dest.writeString(name);

dest.writeInt(age);

}

 

    public static final Parcelable.Creator<Person> CREATOR

    = new Parcelable.Creator<Person>() {

     //從Parcel對象裏面讀取數據

public Person createFromParcel(Parcel in) {

    return new Person(in);

}

 

public Person[] newArray(int size) {

    return new Person[size];

}

};

 

public Person(Parcel in) {

// TODO Auto-generated constructor stub

id = in.readInt();

name = in.readString();

age = in.readInt();

}

 

public Person(int id, String name, int age) {

super();

this.id = id;

this.name = name;

this.age = age;

}

 

@Override

public String toString() {

return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";

}

 

 

}

 

放數據:

 

Intent intent=new Intent(MainActivity.this,NextActivity.class);

Person person=new Person(1,"wanghe",20);

intent.putExtra("person", person);

startActivity(intent);

 

取數據:

Intent intent=getIntent();

Person person=intent.getParcelableExtra("person");

關於IntentstartActivityForResult

代碼:

Intent intent=new Intent(this,NextActivity.class);

//參數:意圖,請求碼

startActivityForResult(intent,100);

要重寫protected void onActivityResult(int requestCode, int resultCode, Intent data) {

// TODO Auto-generated method stub

super.onActivityResult(requestCode, resultCode, data);

 

if(requestCode==100)

If(data!=null)

{

Toast.makeText(getApplicationContext(),   data.getStringExtra("name"), 1).show();

}

}

NextActivity:

              Intent intent=new Intent();

intent.putExtra("name", name);

//參數 結果碼,意圖

setResult(200, intent);

finish();

線程

 

當要訪問的數據使反應的時間特別長,如獲取網頁數據,傳輸的文件等,就要用到線程

 

線程就要用到Handler這個中間類來連接主進程和線程的聯繫:

Handler handler=new Handler(){

@Override

public void handleMessage(Message msg) {

// TODO Auto-generated method stub

super.handleMessage(msg);

            Switch(msg.what)

{

Case 1:

      Msg.obj//獲取消息內容,

//dosomething

Case 2:

 

}

}

 

 

};

 

New Thread(){

Public void run(){

  

 Message msg=new Message();

Msg.what=1;//由於可能有多個消息,因此msg.what標識一惟一消息標識

Msg.obj=」」;//msg.obj發送消息的內容

handler.sendMessage(msg);//發送信息

}

 

}.start();

 

Dialog

 簡單對話框:

AlertDialog.Builder builder=new AlertDialog.Builder(this);

     builder.setTitle("簡單對話框");

     builder.setMessage("肯定嗎");

     builder.setPositiveButton("肯定", new DialogInterface.OnClickListener() {

 

@Override

public void onClick(DialogInterface arg0, int arg1) {

// TODO Auto-generated method stub

 

}

});

    

     builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

 

@Override

public void onClick(DialogInterface arg0, int arg1) {

// TODO Auto-generated method stub

 

}

});

     AlertDialog dialog=builder.create();

     dialog.show();

 

單選對話框:

final String[] items=new String[]{"JAVA","PHP","ASP"};

     AlertDialog.Builder builder=new AlertDialog.Builder(this);

     builder.setTitle("單選對話框");

     builder.setItems(items, new DialogInterface.OnClickListener() {

 

@Override

public void onClick(DialogInterface arg0, int arg1) {

// TODO Auto-generated method stub

Toast.makeText(getApplicationContext(), items[arg1], 0).show();

 

}

});

     AlertDialog dialog=builder.create();

     dialog.show();

     多選對話框:

final String[] items = new String[]{"java","C#","php"};

     final boolean[] checkedItems=new boolean[]{false,false,false};

     AlertDialog.Builder builder=new AlertDialog.Builder(this);

    

     builder.setTitle("選擇");

     builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {

 

@Override

public void onClick(DialogInterface arg0, int arg1, boolean arg2) {

// TODO Auto-generated method stub

 

}

});

     builder.setPositiveButton("肯定",new DialogInterface.OnClickListener() {

 

@Override

public void onClick(DialogInterface arg0, int arg1) {

// TODO Auto-generated method stub

for(int i=0;i<items.length;i++)

{

if(checkedItems[i]==true)

{

str+=items[i];

}

}

Toast.makeText(getApplicationContext(), str, 1).show();

}

});

    

     AlertDialog dialog=builder.create();

     dialog.show();

     自定義對話框:

 LayoutInflater infalter = LayoutInflater.from(this);;

    View view=infalter.inflate(R.layout.item,null);

    AlertDialog.Builder builder=new AlertDialog.Builder(this);

    builder.setTitle("hh");

    builder.setView(view);

    AlertDialog dialog=builder.create();

dialog.show();

 

Broadcast

對於BroadcastReceiver

對於攔截短信:

Xml配置

 <uses-permission android:name="android.permission.RECEIVE_SMS"/>

 <receiver android:name=".SmsBroadCast">

            

            <intent-filter android:priority="1000">

                

                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>

            </intent-filter>

        </receiver>

 

代碼:

public class SmsBroadCast extends BroadcastReceiver {

 

@Override

public void onReceive(Context arg0, Intent arg1) {

// TODO Auto-generated method stub

 

Log.i("i", "攔截到短信");

Bundle bundle=arg1.getExtras();

Object[] objects=(Object[]) bundle.get("pdus");//接收一個key=pdus

for(Object object:objects)

{

SmsMessage message=SmsMessage.createFromPdu((byte[]) object);

String address=message.getDisplayOriginatingAddress();

String body=message.getDisplayMessageBody();

long date=message.getTimestampMillis();

SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

String formatDate=formater.format(date);

Log.i("i", address+" "+body+" "+formatDate);

abortBroadcast();

}

 

 

 

}

 

}

外撥電話:

Xml配置:

 <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>

 <receiver android:name=".PhoneBroadCast">

            

            <intent-filter >

                

                <action android:name="android.intent.action.NEW_OUTGOING_CALL"/>

            </intent-filter>

        </receiver>

        代碼:

public class PhoneBroadCast extends BroadcastReceiver {

 

@Override

public void onReceive(Context arg0, Intent arg1) {

// TODO Auto-generated method stub

 

String num=getResultData();//獲得號碼

setResultData("");//設置號碼

Log.i("i", num);

 

}

 

}

自定義廣播

自定義發送:

Intent intent=new Intent();

intent.setAction("cn.mydefine.broadcase");

intent.putExtra("msg", txt.getText().toString());

sendBroadcast(intent);

Xml配置:

<receiver android:name=".CustomRec">

            

            <intent-filter>

                

                <action android:name="cn.mydefine.broadcase"/>

            </intent-filter>

        </receiver>

接收廣播:

public class CustomRec extends BroadcastReceiver {

 

@Override

public void onReceive(Context arg0, Intent arg1) {

// TODO Auto-generated method stub

 

String msg=arg1.getStringExtra("msg");

Log.i("msg", msg);

 

}

 

}

 

服務 Service

服務須要手動打開:

例:

打開服務:

Intent intent=new Intent(this,PhoneService.class);

 

startService(intent);

服務代碼:監聽電話狀態:

public class PhoneService extends Service {

 

 

private TelephonyManager tm;

@Override

public void onCreate() {

// TODO Auto-generated method stub

super.onCreate();

tm=(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

tm.listen(new PhoneStateListener1(), PhoneStateListener.LISTEN_CALL_STATE);

 

 

 

}

private final class PhoneStateListener1 extends PhoneStateListener

{

 

@Override

public void onCallStateChanged(int state, String incomingNumber) {

// TODO Auto-generated method stub

super.onCallStateChanged(state, incomingNumber);

 

Log.i("電話號碼:", incomingNumber+"");

switch(state)

{

 

case TelephonyManager.CALL_STATE_IDLE:

Log.i("i:", "無狀態");

break;

case TelephonyManager.CALL_STATE_OFFHOOK:

Log.i("i:", "接聽狀態");

break;

 

case TelephonyManager.CALL_STATE_RINGING:

Log.i("i:", "響鈴狀態");

break;

 

}

 

 

 

}

 

}

@Override

public IBinder onBind(Intent arg0) {

// TODO Auto-generated method stub

return null;

}

 

}

Xml配置:

 <service android:name=".PhoneService"></service>

訪問本地自定義服務

 <service android:name=".StudentService"></service>

 

1.綁定服務:Intent intent=new Intent(this,StudentService.class);

    //bindService三個參數,意圖,服務鏈接ServiceConnection,還有自動連接字段

bindService(intent, conn, Context.BIND_AUTO_CREATE);

2.繼承ServiceConnection藉口,重寫ServiceConnection

 private class MyServiceConnection implements ServiceConnection

 

 

{

 

@Override

public void onServiceConnected(ComponentName arg0, IBinder arg1) {

// TODO Auto-generated method stub

            //返回值是IBinder接口,因此轉換爲iStudentService接口來查詢

iStudentService=(IStudentService) arg1;

}

 

 

@Override

public void onServiceDisconnected(ComponentName arg0) {

// TODO Auto-generated method stub

 

conn=null;

iStudentService=null;

}

 

}

 

      @Override

//釋放連接

protected void onDestroy() {

// TODO Auto-generated method stub

super.onDestroy();

unbindService(conn);

}

 

 

3.定義接口:

public interface IStudentService {

 

 

public Student getStudent(int no);

4.寫服務:

 public class StudentService extends Service {

 

 

private final Student[] students=new Student[]{new Student(1,"王賀",20),new Student(2,"黎明",22),new Student(3,"線路",23)};

private QueryStudent  queryStudent=null;

@Override

//返回值是IBinder,因此QueryStudent繼承BinderIstudentService

public IBinder onBind(Intent arg0) {

// TODO Auto-generated method stub

queryStudent=new QueryStudent();

return queryStudent;

}

 

public final class QueryStudent extends Binder implements IStudentService

{

 

@Override

public Student getStudent(int no) {

// TODO Auto-generated method stub

return query(no);

}

 

public Student query(int no)

{

return students[no-1];

}

 

}

 

}

 

兩個應用之間的服務通訊;要用到dial文件;在傳輸對象時,對象要繼承Parcelable

服務端代碼:

Student.java

package domin;

 

import android.os.Parcel;

import android.os.Parcelable;

 

public class Student implements Parcelable {

 

private int no;

private String name;

private int age;

@Override

public int describeContents() {

// TODO Auto-generated method stub

return 0;

}

 

@Override

public void writeToParcel(Parcel arg0, int arg1) {

// TODO Auto-generated method stub

arg0.writeInt(no);

arg0.writeString(name);

arg0.writeInt(age);

}

 

 public static final Parcelable.Creator<Student> CREATOR

    = new Parcelable.Creator<Student>() {

  //Parcel對象裏面讀取數據

public Student createFromParcel(Parcel in) {

    return new Student(in);

}

 

public Student[] newArray(int size) {

    return new Student[size];

}

};

 

public Student(Parcel in) {

// TODO Auto-generated constructor stub

no= in.readInt();

name = in.readString();

age = in.readInt();

}

 

public Student(int no,String name,int age)

{

this.no=no;

this.name=name;

this.age=age;

}

 

@Override

public String toString() {

// TODO Auto-generated method stub

return no+"   "+name+"    "+age;

}

 

 

}

新建一個dial文件來標明它:

Student.dial

package domin;//標明包名

parcelable Student;//標明類名,parcelable要小寫

接口:IStudentService.java

package inter;

 

import domin.Student;

 

 interface IStudentService {

 Student queryStudent(int no);

}

創建這個接口後要改成dial文件

而後系統會爲此接口改寫代碼,裏面有一個Stub類,這個類繼承BinderIStudentService接口

而後是student服務

StudentService.java

package serve;

 

import domin.Student;

import inter.IStudentService.Stub;

import android.app.Service;

import android.content.Intent;

import android.os.IBinder;

import android.os.RemoteException;

 

public class StudentService extends Service{

 

 

private MyStudentService binder=new MyStudentService();

 

private Student[] students=new Student[]{new Student(1,"王賀",21),new Student(2,"黎明",22),new Student(3,"線路",23)}; 

@Override

public IBinder onBind(Intent arg0) {

// TODO Auto-generated method stub

return binder;

}

     

private final class MyStudentService extends Stub//因爲系統對代碼的改寫,因此只須要繼承Stub類就是對BinderIStudentService接口的繼承

{

 

@Override

public Student queryStudent(int no) throws RemoteException {

// TODO Auto-generated method stub

return query(no-1);

}

 

public Student query(int no)

{

return students[no-1];

 

}

 

 

}

 

 

}

 

因爲是兩個應用因此要對次服務註冊下,

Xml配置:

  <service android:name="serve.StudentService">

            <intent-filter>

                

                <action android:name="com.example.MyServer"/>

            </intent-filter>

        </service>

 

客戶端代碼,要把服務器端的除了StudentService類外,把別的類和包複製到客戶端的src裏面以保持一致

package com.example.client;

 

import domin.Student;

import inter.IStudentService;

import inter.IStudentService.Stub;

import android.os.Bundle;

import android.os.IBinder;

import android.os.RemoteException;

import android.app.Activity;

import android.content.ComponentName;

import android.content.Context;

import android.content.Intent;

import android.content.ServiceConnection;

import android.view.Menu;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;

 

public class MainActivity extends Activity {

 

 

private EditText txt=null;

private TextView msg=null;

private IStudentService iStudentService;

private MyServiceConnection conn;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

txt=(EditText)findViewById(R.id.txt);

msg=(TextView)findViewById(R.id.msg);

conn=new MyServiceConnection();

Intent intent=new Intent();

intent.setAction("com.example.MyServer");

bindService(intent,conn,Context.BIND_AUTO_CREATE);

 

}

 

private final class MyServiceConnection implements ServiceConnection

{

 

@Override

public void onServiceConnected(ComponentName arg0, IBinder arg1) {

// TODO Auto-generated method stub

iStudentService=Stub.asInterface(arg1);

}

 

@Override

public void onServiceDisconnected(ComponentName arg0) {

// TODO Auto-generated method stub

conn=null;

iStudentService=null;

}

 

}

public void query(View v)

{

try {

Student student=iStudentService.queryStudent(Integer.valueOf(txt.getText().toString()));

msg.setText(student.toString());

} catch (NumberFormatException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (RemoteException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

}

 

 

@Override

protected void onDestroy() {

// TODO Auto-generated method stub

super.onDestroy();

unbindService(conn);

}

 

 

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

 

}

 

HTTP

 

/**

 * @author Dylan

 * 本類封裝了Android中向web服務器提交數據的兩種方式四種方法

 */

public class SubmitDataByHttpClientAndOrdinaryWay {

 

/**

 * 使用get請求以普通方式提交數據

 * @param map 傳遞進來的數據,以map的形式進行了封裝

 * @param path 要求服務器servlet的地址

 * @return 返回的boolean類型的參數

 * @throws Exception

 */

public Boolean submitDataByDoGet(Map<String, String> map, String path) throws Exception {

// 拼湊出請求地址

StringBuilder sb = new StringBuilder(path);

sb.append("?");

for (Map.Entry<String, String> entry : map.entrySet()) {

sb.append(entry.getKey()).append("=").append(entry.getValue());

sb.append("&");

}

sb.deleteCharAt(sb.length() - 1);

String str = sb.toString();

System.out.println(str);

URL Url = new URL(str);

HttpURLConnection HttpConn = (HttpURLConnection) Url.openConnection();

HttpConn.setRequestMethod("GET");

HttpConn.setReadTimeout(5000);

// GET方式的請求不用設置什麼DoOutPut()之類的嗎?

if (HttpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {

return true;

}

return false;

}

 

/**

 * 普通方式的DoPost請求提交數據

 * @param map 傳遞進來的數據,以map的形式進行了封裝

 * @param path 要求服務器servlet的地址

 * @return 返回的boolean類型的參數

 * @throws Exception

 */

public Boolean submitDataByDoPost(Map<String, String> map, String path) throws Exception {

// 注意Post地址中是不帶參數的,因此newURL的時候要注意不能加上後面的參數

URL Url = new URL(path);

// Post方式提交的時候參數和URL是分開提交的,參數形式是這樣子的:name=y&age=6

StringBuilder sb = new StringBuilder();

// sb.append("?");

for (Map.Entry<String, String> entry : map.entrySet()) {

sb.append(entry.getKey()).append("=").append(entry.getValue());

sb.append("&");

}

sb.deleteCharAt(sb.length() - 1);

String str = sb.toString();

 

HttpURLConnection HttpConn = (HttpURLConnection) Url.openConnection();

HttpConn.setRequestMethod("POST");

HttpConn.setReadTimeout(5000);

HttpConn.setDoOutput(true);

HttpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

HttpConn.setRequestProperty("Content-Length", String.valueOf(str.getBytes().length));

OutputStream os = HttpConn.getOutputStream();

os.write(str.getBytes());

if (HttpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {

return true;

}

return false;

}

 

/**

 * HttpClientDoGet方式向服務器發送請數據

 * @param map 傳遞進來的數據,以map的形式進行了封裝

 * @param path 要求服務器servlet的地址

 * @return 返回的boolean類型的參數

 * @throws Exception

 */

public Boolean submitDataByHttpClientDoGet(Map<String, String> map, String path) throws Exception {

HttpClient hc = new DefaultHttpClient();

// 請求路徑

StringBuilder sb = new StringBuilder(path);

sb.append("?");

for (Map.Entry<String, String> entry : map.entrySet()) {

sb.append(entry.getKey()).append("=").append(entry.getValue());

sb.append("&");

}

sb.deleteCharAt(sb.length() - 1);

String str = sb.toString();

System.out.println(str);

HttpGet request = new HttpGet(sb.toString());

 

HttpResponse response = hc.execute(request);

if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {

return true;

}

return false;

}

 

/**

 * HttpClientDoPost方式提交數據到服務器

 * @param map 傳遞進來的數據,以map的形式進行了封裝

 * @param path 要求服務器servlet的地址

 * @return 返回的boolean類型的參數

 * @throws Exception

 */

public Boolean submintDataByHttpClientDoPost(Map<String, String> map, String path) throws Exception {

// 1. 得到一個至關於瀏覽器對象HttpClient,使用這個接口的實現類來建立對象,DefaultHttpClient

HttpClient hc = new DefaultHttpClient();

// DoPost方式請求的時候設置請求,關鍵是路徑

HttpPost request = new HttpPost(path);

// 2. 爲請求設置請求參數,也便是將要上傳到web服務器上的參數

List<NameValuePair> parameters = new ArrayList<NameValuePair>();

for (Map.Entry<String, String> entry : map.entrySet()) {

NameValuePair nameValuePairs = new BasicNameValuePair(entry.getKey(), entry.getValue());

parameters.add(nameValuePairs);

}

// 請求實體HttpEntity也是一個接口,咱們用它的實現類UrlEncodedFormEntity來建立對象,注意後面一個String類型的參數是用來指定編碼的

HttpEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");

request.setEntity(entity);

// 3. 執行請求

HttpResponse response = hc.execute(request);

// 4. 經過返回碼來判斷請求成功與否

if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {

return true;

}

return false;

}

}

相關文章
相關標籤/搜索