Custom Broadcastreceiver Broadcast Basics Demo Introduction

Source: Internet
Author: User

When an app inherits the ContentProvider class and overrides the method used to provide data and store data, it can share its data with other apps.
To create a step:
1) Create class inheritance ContentProvider parent class;
2) defines a class constant for the URI type of public static final, specifying a unique string value for it, preferably with the full name of the class. Such as:
public static final Uri Content_uri = Uri.parse ("Content://com.google.android.mycontentprovider");
3) Define the name of the data column to return to the client. If you use an Android database, you must define _ID columns to represent the uniqueness of each record.
4) Create a data storage system. Most content provider use an android file system or SQLite database to persist data.
5) Declare a variable of public static string type, specifying the data column to return from the cursor.
6) Use the Contentresover (). Notifychange () method to notify the listener about data updates.
7) Use <provider> to configure the ContentProvider in Androidmanifest.xml.

New Project

New layout layouts

<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Xmlns:tools= "Http://schemas.android.com/tools"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"
android:paddingbottom= "@dimen/activity_vertical_margin"
android:paddingleft= "@dimen/activity_horizontal_margin"
android:paddingright= "@dimen/activity_horizontal_margin"
android:paddingtop= "@dimen/activity_vertical_margin"
Tools:context= ". MainActivity2 ">

<button
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:id= "@+id/main2_bt1"
android:text= "Save"/>

<button
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:id= "@+id/main2_bt2"
android:text= "Remove"/>

</LinearLayout>

Util of the new Java class

Package com.example.android_lession8_4;



Import Android.net.Uri;
Import Android.provider.BaseColumns;


The toolkit is used to indicate the URI of the user-defined CP and the name of the corresponding field
public class Myutil {

Root Address
Public final static String authority= "Com.zyy.test.MyContentProvider";


Basecolumns default indicates two fields _id _count where ID represents an identifier, count indicates the number of rows
public static final class User implements basecolumns{

Indicates the URI address of the CP
public static final Uri content_uri=uri.parse ("content://" +authority);

Data items in the CP
public static final String user_name= "user_name";
public static final String user_pwd= "User_pwd";

}


}
Create custom content provider for multiple app data sharing

Package com.example.android_lession8_4;

Import Android.content.ContentProvider;
Import Android.content.ContentUris;
Import android.content.ContentValues;
Import Android.content.Context;
Import Android.database.Cursor;
Import android.database.SQLException;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.database.sqlite.SQLiteDatabase.CursorFactory;
Import Android.database.sqlite.SQLiteOpenHelper;
Import Android.database.sqlite.SQLiteQueryBuilder;
Import Android.net.Uri;
Import Android.util.Log;

public class Mycontentprovider extends ContentProvider {

Private sqlitedatabase sqldb;//Database library Object
private static final String database_name= "user.db"; Declaring the database name
private static final int database_version=1; Declaring the database version number
private static final String database_table= "T_user"; Stored table name
Private Mydatabasehelper DBHelper; Database helper class for creating a database and obtaining related read and Write permissions


Build SQLite Operating Environment
private static class Mydatabasehelper extends sqliteopenhelper{

Public Mydatabasehelper (Context context) {
Super (context, database_name, NULL, database_version);
TODO auto-generated Constructor stub
}

@Override
public void OnCreate (Sqlitedatabase db) {
Create a table for storing data
Db.execsql ("Create table" +database_table+ "(_id Integer primary key autoincrement,user_name text,user_pwd text);");
}
@Override
public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
Db.execsql ("drop table if exists" +database_table);
OnCreate (DB);

}
}

@Override
public int Delete (URI Uri, String selection, string[] Selectionargs) {
TODO auto-generated Method Stub
return 0;
}

@Override
Public String GetType (Uri uri) {
TODO auto-generated Method Stub
return null;
}

Save
@Override
Public URI insert (URI uri, contentvalues values) {
Sqldb=dbhelper.getwritabledatabase ();//Get Database Write objects

Returns the affected row ID
Long Rowid=sqldb.insert (database_table, null, values);
if (rowid>0) {
Create a URI corresponding to the table
Uri Rowuri=contenturis.appendid (MyUtil.User.CONTENT_URI.buildUpon (), ROWID). Build ();
LOG.D ("Zyy", "Rowuri:" +rowuri.getpath ());
Notification of CP Listener update (add-on general)
GetContext (). Getcontentresolver (). Notifychange (Rowuri, NULL);

return Rowuri;
}
throw new SQLException ("CP Insert data failed:" +uri);




}

@Override
public Boolean onCreate () {

Instantiate the database helper class object, which he creates to create the database storage table
Dbhelper=new Mydatabasehelper (GetContext ());
return dbhelper==null?false:true;
}


Take
@Override
Public Cursor query (URI uri, string[] projection, String selection,
String[] Selectionargs, String sortOrder) {
Get database Read Object
Sqldb=dbhelper.getreadabledatabase ();
Set up SQL query creator
Sqlitequerybuilder sq=new Sqlitequerybuilder ();
Set up a query table
Sq.settables (database_table);

Get the corresponding CP query result set in SQLite
Cursor cursor=sq.query (SqlDB, projection, selection, Selectionargs, NULL, NULL, sortOrder);

Background detects changes in data and returns the changed cursor if there is a change
Cursor.setnotificationuri (GetContext (). Getcontentresolver (), URI);

return cursor;
}

@Override
public int update (URI uri, contentvalues values, String selection,
String[] Selectionargs) {
TODO auto-generated Method Stub
return 0;
}

}
Create activity Activities Java class

Package com.example.android_lession8_4;

Import Android.os.Bundle;
Import android.app.Activity;
Import android.content.ContentValues;
Import Android.database.Cursor;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.Toast;

public class MainActivity2 extends Activity implements onclicklistener{
Private Button bt1,bt2;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main_activity2);
bt1= (Button) Findviewbyid (R.ID.MAIN2_BT1);
Bt2= (Button) Findviewbyid (R.ID.MAIN2_BT2);
Bt1.setonclicklistener (this);
Bt2.setonclicklistener (this);



}

@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_activity2, menu);
return true;
}

@Override
public void OnClick (View v) {
Switch (V.getid ()) {
Case R.ID.MAIN2_BT1:
Save data
Contentvalues cv=new contentvalues ();
Cv.put (MyUtil.User.USER_NAME, "zyy");
Cv.put (MyUtil.User.USER_PWD, "123");
Getapplicationcontext (). Getcontentresolver (). Insert (MyUtil.User.CONTENT_URI, CV);
Toast.maketext (Getapplicationcontext (), "Add Success", Toast.length_long). Show ();
Break

Case R.ID.MAIN2_BT2:
Fetch data
String colums[] =new string[]{myutil.user._id,myutil.user.user_name,myutil.user.user_pwd};
Cursor C=getapplicationcontext (). Getcontentresolver (). Query (MyUtil.User.CONTENT_URI, colums, NULL, NULL, NULL);
int a=10;
int id=-1;
String Username=null;
String Userpwd=null;


while (C.movetonext ()) {
Id=c.getint (C.getcolumnindex (myutil.user._id));
Username=c.getstring (C.getcolumnindex (MyUtil.User.USER_NAME));
Userpwd=c.getstring (C.getcolumnindex (MyUtil.User.USER_PWD));
}


Toast.maketext (Getapplicationcontext (), "ID:" +id+ "Name:" +username+ "Password:" +userpwd, Toast.length_long). Show ();



Break
}


}

}

Custom Broadcastreceiver Broadcast Basics Demo Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.