First, the operation principle of the content observer
The run process typically modifies the data exposed by the content provider for a application, while the B application is responsible for monitoring changes in the content provider's data.
1, a simple small demo
First, the content provider writes a Mycontentprovider class inheritance ContentProvider as follows
public class Mycontentprovider extends ContentProvider
Inheritance will automatically rewrite the 6 methods (Oncreat and GetBytes) in the B application of the corresponding modified method (increase deletion) to issue a notification, GetContext (). Getcontentresolver (). Notifychange (URI, NULL);
Notification a application (viewer content changes), a applied
Uri uri=uri.parse ("CONTENT://QJQ");
Getcontentresolver (). Query (URI, NULL, NULL, NULL, NULL);
LOG.I (TAG, "Query completed");
Monitor the change of the data. Parameter Two notifyfordescendents Boolean is cascading
Getcontentresolver (). Registercontentobserver (URI, True, new Mycontentobserver (New Handler ()));
LOG.I (TAG, "The listener has been set up");
Private class Mycontentobserver extends contentobserver{}//overriding constructors and OnChange methods
Second, use content observer to monitor the change of SMS data (Master)
The location of the SMS data store,
The source of the manifest file inside
The location of the text messages stored
The URI of the core
Code:
Second, SMS Listener
Getcontentresolver (). Registercontentobserver (Uri.parse ("Content://sms"), True, new Mycontentobserver (New Handler () )); Mycontentobserver for a class of his own new Contentobserver override onchange method code as follows
public void OnChange (Boolean selfchange) {
TODO auto-generated Method Stub
Super.onchange (Selfchange);
If the message content Change method will be automatically called by the system
Get the latest text message (permission to read text messages for SMS data)
Address number, body content
Cursor C = getcontentresolver (). Query (Uri.parse ("Content://sms"), New string[]{"address", "body"}, NULL, NULL, "_id desc ");
C.movetofirst ();
String address=c.getstring (0);
String body=c.getstring (1);
LOG.I (TAG, "Address:" +address+ ", Body:" +body);
C.close (); }
Third, the ANR exception (that is, the user clicks the button 5 seconds does not respond when the Nishinaga will pop-up window) to understand
Write a ANR button
Write the following code in Mainactivity
Note that it is not possible to perform time-consuming operations within the activity, and if time-consuming operations occur, the thread should be
The Android program defaults to a single thread that is the main thread or the UI thread.
How to turn on threads
There are two ways of the thread
The first way
New Thread () {
public void Run () {
};
}.start ();
Second Way
New Thread (New Runnable () {
@Override
public void Run () {
}
}). Start ();
Iv. "Case" Implementation click the Start button TextView box shows the change process of 1+...+100 results
1. Interface an edit box a button
2.Mainactivity code as follows if you do not use the Message Processor will report an error
07-13 02:38:25.215:e/androidruntime (21713): Android.view.viewroot$calledfromwrongthreadexception:only the original Thread that created a view hierarchy can touch it views. Only the main thread can operate the display
The mainactivity code is as follows:
public class Mainactivity extends Activity {
protected static final int update_sum = 0;//is just an indication
Private TextView Tv_number;
Message Processor
Public Handler Mhandler = new Handler () {
The method of processing the message, enter handle as prompted alt+/can come out
public void Handlemessage (Android.os.Message msg) {
Switch (msg.what) {
Case Update_sum:
int sum = (Integer) msg.obj;
Tv_number.settext (sum + "");
Break
Default
Break
}
};
};
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Tv_number = (TextView) Findviewbyid (R.id.tv_number);
}
public void Add (View v) {
New Thread () {
public void Run () {
int i = 0;
int sum = 0;
while (I <= 100) {
i++;
sum + = i;
Tv_number.settext (sum+ ""); A child thread cannot manipulate the display to send a message to the main thread
/**
Ideas
* 1 Create message
* 2 Set the data to the Message object
* 3 Send Message
*/
Message msg = Message.obtain ();//obtain obtained, that is, get messages
Msg.what = update_sum;//Sets a unique identifier for the message
Msg.obj = sum;
Mhandler.sendmessage (msg);//The Handlemessage () method is handed to Mhanlder after the message is sent
Systemclock.sleep (200);
}
}
}.start ();
}
Five, Android under the implementation of the message mechanism.
1. Network protocol
Get request, data written at the back of the URL, 1kb
Post request data inside the entity
Six, "Case five" network picture viewer
Below Android2.3 can read the network picture directly using the following code, more than 2.3 must use the message processor to handle
try {//Learn a trick alt+shift+z (x, Y is case-reversed) wrap block to try ... catch
String path = Et_path.gettext (). toString ();
1 wrapper network Path URL Note is not a URI
URL url=new url (path);
2 Open Connection Url.openconnection ()
HttpURLConnection conn= (httpurlconnection) url.openconnection ();
3 Setting the parameters of the connection (timeout time, request)
Conn.setconnecttimeout (10000);
Conn.setrequestmethod ("get");//lowercase is wrong notice changed to get
4 Judgment Response code: 200 Success
if (Conn.getresponsecode () ==200) {
5 retrieving streaming data from the server loopback
InputStream is= Conn.getinputstream ();
Process the stream into a picture and show it
Bitmap Bitmap=bitmapfactory.decodestream (IS);
Set up picture display
Iv.setimagebitmap (bitmap);
}
Use the message processor and the cached picture all the code below
public class Mainactivity extends Activity {
Private final static String TAG = "mainactivity";
protected static final int success_get_image = 0;
protected static final int error_get_image = 1;
Private ImageView IV;
Private EditText Et_path;
Private Handler Mhandler = new Handler () {
public void Handlemessage (Android.os.Message msg) {
Switch (msg.what) {
Case Success_get_image:
File File = (file) msg.obj;
To set the display of a picture
Iv.setimageuri (uri.fromfile (file));
Break
Case Error_get_image:
Toast.maketext (Getapplicationcontext (), "Get Picture Failed", 0). Show ();
Break
Default
Break
}
};
};
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Et_path = (EditText) Findviewbyid (R.id.et_path);
IV = (ImageView) Findviewbyid (R.ID.IV);
}
public void Get (View v) {
New Thread () {
public void Run () {
try {
String path = Et_path.gettext (). toString ();
File File = new file (Environment.getexternalstoragedirectory (), GetFileName (path));
Determine if a picture exists
if (file.exists ()) {
Direct use
LOG.I (TAG, "Using cached Images");
Message msg = Message.obtain ();
Msg.what = Success_get_image;
msg.obj = file;
Mhandler.sendmessage (msg);
}else{
1 Wrapper network Path URL
URL url = new URL (path);
2 Open Connection Url.openconnection ()
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
Super Time
Conn.setconnecttimeout (5000);
How to request
Conn.setrequestmethod ("GET");
4 Judgment Response code: 200 Success
if (conn.getresponsecode () = = 200) {
5 retrieving streaming data from the server loopback
InputStream is = Conn.getinputstream ();
Process the stream into a picture and show it
Bitmap Bitmap = Bitmapfactory.decodestream (IS);//use bitmap factory to process as picture
Cached in SDcard
FileOutputStream stream = new FileOutputStream (file);
Format Picture
The quality of quality pictures
Stream output Streams
Bitmap.compress (Compressformat.jpeg, N, Stream);
LOG.I (TAG, "downloaded the picture, and cached it to SDcard");
Send a message to the main thread
Message msg = Message.obtain ();
Msg.what = Success_get_image;
msg.obj = file;
Mhandler.sendmessage (msg);
}else{
Message msg = Message.obtain ();
Msg.what = Error_get_image;
Mhandler.sendmessage (msg);
}
}
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
Message msg = Message.obtain ();
Msg.what = Error_get_image;
Mhandler.sendmessage (msg);
}
};
}.start ();
}
Get the name of the file
public string GetFileName (string path) {
Return path.substring (Path.lastindexof ("/") +1);
}
@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.activity_main, menu);
return true;
}
}
3. Use Smartimageview Open source space to get a picture of a webpage Copy the Loopj.android.image package to the SRC directory, and the label in the other layout should be changed to Loopj.android.image.SmartImageView package name plus Smartimageview
Iv.setimageurl ("Http://10.0.2.2:8080/tomcat.png");
Vii. getting JSON data from the server
InputStream is = Conn.getinputstream ();//is actually a JSON-formatted string
How to convert a JSON-formatted string into an object collection
1 The rheological character as a string
2 Turn string into Jsonarray
Bytearrayoutputstream BOS = new Bytearrayoutputstream ();
byte[] buffer = new byte[1024];
int len = 0;
while (len = is.read (buffer))! =-1) {
Bos.write (buffer, 0, Len);
}
String json = bos.tostring ();
Bos.close ();
Is.close ();
2 Turn string into Jsonarray
Jsonarray array = new Jsonarray (JSON);
for (int i = 0;i<array.length (); i++) {
Jsonobject Jsonobject = Array.getjsonobject (i);
int id = jsonobject.getint ("id");
String name = jsonobject.getstring ("name");
int age = Jsonobject.getint ("Age");
LOG.I (TAG, "ID:" +id+ ", Name:" +name+ ", Age:" +age ");