认识安卓四大组件
Activity
创建一个新的界面的步骤
1、通过Intent启动
Intent intent = new Intent(MainActivity.this,SubActivity02.class)
|
2、新的界面绑定.xml
setContentView(R.layout.activity_sub02)
|
3、清单文件注册新的Activity
<activity android:name=".SubActivity02"> <activity>
|
4、新的Activity要继承Activity
public class SubActivity02 extends Activity
|
Activity界面切换
1、老方法(通过复写onActivityResult函数来接受返回结果),部分代码
@Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(data == null) { return; } if(resultCode == requestCode && requestCode == 234) { String ret = data.getStringExtra("key1"); Log.i("This is ret",ret); } } protected void onCreate(Bundle savedInstanceState) { btn_start = findViewById(R.id.btn_startActivity); btn_start.setOnClickListener(new View.onClickListener(){ @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, SubActivity02.class); stratActivity(intent); } }); @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, SubActivity03.class); startActivityForResult(intent, 234); } }
|
2、新方法接受返回结果(通过ActivityResultLauncher),部分代码
ActivityReustltLauncher launcher = registerForActivity(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<Activity>() { @Override public void onActivityResult(ActivityResult result) { Log.i(lotTag, result.getData().getStringExtra("key1")); } btn_startForResult = findViewById(R.id.btn_startActivityGetResult); btn_saartForResult.setOnClickListener(new View.OnClickListerer(){ Intent intent = new Intent(MainActivity.this, SubActivity03); launcher.launch(intent); }); });
|
SubActivity03.java,部分代码
public class SubActivity03 extends Activity { TestView tv; @Override super.onCreate(savadInstanceState); setContentView(R.layout.activity_03); tv.setOnClickListener(new View.OnClickerListener(){ @Override public void onClick(View view) { Intent intent = new Intent(); intent.setClass(SubActivity03.this, MainActivity.class); intent.putExtra("key1","这是结果1,来自SubActivity03"); setResult(234, intent); SunActivity03.this.finish(); } }); }
|
Service
1、通过startService、stopService,部分代码
在清单文件中注册Service
<service android:name=".service.MyService01"></service>
|
btn_startService = findViewById(R.id.btn_startService); btn_startService.setOnClickeListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, MyService01.class); startService(intent); } }); btn_stopService = findViewById(R.id.btn_stopService); btn_stopService.setOnClickListener(new View.OnClickLintener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, MyService01.class); stopService(intent); } })
|
2、通过bindService和unbindService,部分代码
在清单文件中注册Service
<service android:name=".service.MyBindService"></service>
|
ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { if(iBinder instanceof MyBindService.MyBinder) { myBinder = (MyBinderService.MyBinder)iBinder; } } @Override public void onServiceDisconnected(ComponentName componentName) { Log.i(logTag,"onServiceDisconnected"); } };
btn_bindService = findViewBtId(R.id.btn_bindService); btn_binService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, MyBindService.class); bindService(intent, conn, Context.BIND_AUTO_CREATE); } }); btn_unBindService = findViewById(R.id.btn_unbindService); btn_unBindService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { unbindService(conn); }catch(Exception e) { e.printStackTrace(); } } });
|
MyBindService,部分代码
public class MyBindService extends Service { String logTag = "qqqqqqqq"; private MyBinder binder = new MyBinder(); public class MyBinder extends Binder { public MyBinder() { Log.i(logTag,"in MyBinder"); } public MyBinderService getServiceBinder() { return MyBinderService.this; } @Override public void onCreate() { super.onCreate; } @Override public void onDestroy() { super.onDertroy; } @Nullable @Override public IBinder onBind(Intent intent) { return binder; } @Override public boolean onUnbind(Intent intent) { Log.i(logTag, "onUnbind"); return super.onUnbind(intent); } } }
|
BroadcastReceiver介绍
静态注册
无序广播
<receiver android:name=".MyReceiver.MyReceiver" android:exported="false">
<intent-filter> <action android:name="golvRuleaa"></action> </intent-filter>
</receiver>
|
有序广播(设置优先级)
<receiver android:name=".MyReceiver.OrderReceiver01" android:exported="false"> <intent-filter android:priority="1000"> <action android:name="guolvRuleaaa"></action> </intent-filter> </receiver> <receiver android:name=".MyReceiver.OrderReceiver02" android:exprted="false"> <intent-filter android:priority="500"> <action android:name="guolvRuleaaa"></action> </intent-filter> </receiver> <receiver android:name=".MyReceiver.OrderReceiver02" android:exported="false"> <intent-filter android:priority="100"> <action android:name="guolvRuleaaa"></action> </intent-filter> </receiver>
|
动态注册(在MainActivity中)
OrderReceiver01 orderReceiver01 = new OrderReceive01(); OrderReceiver02 orderReceiver02 = new OrderReceive02(); OrderReceiver03 orderReceiver03 = new OrderReceiver03(); IntentFileter intentFileter = new IntentFilter(); intentFliter.addAction("guolvRuleaaa"); registerReceiver(orderReceiver01, intentFilter); registerReceiver(orderReceiver02, intentFilter); registerReceiver(orderReceiver03, intentFilter);
|
有序广播和无序广播,部分代码
btn_sendBroadcast = findViewById(R.id.btn_broadcast); btn_sendBroadcast = setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, MyReceiver.class); intent.setAction("guolvRuleaaa"); intent.putRxtra("key2","这是无序广播的内容1"); sendBroadcast(intent); } }); OrderReceiver01 orderReceiver01 = new OrderReceiver01(); OrderReceiver02 orderReceiver02 = new OrderReceiver02(); OrderReceiver03 orderReceiver03 = new OrderReceiver03(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("guolvRuleaaa"); registerReceiver(orderReceiver01, intentFilter); registerReceiver(orderReceiver02, intentFilter); registerReceiver(orderReceiver03, intentFilter); btn_orderBroadcast = findViewById(R.id.btn_orderBroadcast); btn_orderBroadcast.setOnClickListener(new View.OnCLickListener) { @Override public void onClick(View view) { Intent intent = new Intent(); intent.setAction = "guolvRuleaaa"; String data = "这是原始数据"; Bundle extData = new Bundle(); sendOrderedBroadcast(intent, null, new MyReceiver(),null,0,data,extData); } }
|
OrderReceiver01.java
public class OrderReceiver01 extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals("guolvRuleaaa")) { String data = getResultData(); Log.i("OrderReceiver01,","接收到内容"+data); setResultData("内容已经被OrderReceive01修改"); } } }
|
OrderReceiver02.java
public class OrderReceiver02 extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = "guolvRuleaaa"; if(action.equals("guolvRuleaaa")) { Log.i("OrderReceiver02","接收到内容,"+data); setResultData("内容已经被OrderReceiver02修改") } } }
|
OrderReceiver03.java
public class OrderReceiver03 extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals("guolvRuleaaa")) { Log.i("OrderReceiver03","接收到内容,"+data); setResultData("内容已经被OrderReceiver03修改"); } } }
|
Content Provider
在数据库的清单中申请创建权限
<permisson android:name="myDB.permisson" android:protectionLevel="normal"></permisson>
|
在要使用该数据库的Moudle的清单文件中申请使用权限
<uses-permission android:name="myDB.permission"></uses-permission>
|
MainActivity.java,部分代码
int uid = 40; static final Uri uri = Uri.parse("content://a.b.c.db.authority/user");
btn_add = findViewById(R.id.btn_add); btn_add.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { ContentValues values = new ContentValues(); values.put("uid",uid++); valuse.put("name","hyq"); valuse.put("age","20"); values.put("score",78); ContentResolver contentResolver = getContentResolver(); contentResolver.insert(uri,values); } }); btn_del = findViewById(R.id.btn_del); btn_del.setOnClickListener(new View.OnclickListener() { @Override public void onClick(View view) { ContentResolver contentResolver = getContentResolver(); int delCount = contentResolver.delete(uri,"uid>?",new String[]{"4"}); if(delCount > 0) { Log.i(logTag,"del Count:" + delCount); } } }); btn_update = findViewById(R.id.btn_update); btn_update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ContentValues values= new ContentValues(); vlaues.put("age","20"); ContentResolver contentResolver = getContentResolver(); ing updateCount = contentResolver.update(uri,values,"uid=?",new String[]{"3"}); if(updateCount>0) { Log.i("qqqqqqqq","update Count"+updateCount); } } }); btn_search = findViewById(R.id.btn_search); btn_search = setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ContentResolver contetnResolver = getContentResolver(); Cursor cursr = contentResolver.query(uri,new String[]{"uid","name","age","score"},null,null,null); if(cursor == null) { return; } while(cursor.moveToNext()) { @SuppressLint("Range") int uid = cursor.getInt(cursor.getColumnIndex("uid")); @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name")); @SuppressLint("Range") int age = cursor.getInt(cursor.getColumnIndex("age")); @SuppressLint("Range") int score= cursor.getInt(cursor.getColumnIndex("score")); Log.i(logtag,"uid="+uid+",name="+name+",age="+age+",score="+score); } }
});
|
DBHelper.java
public class DBHelper extends SQLiteOpenHelper { private static final String DBNAME = "myDbName.db"; private static final int VERSION = 1; public static final String TABLE_USER = "user"; public DBHelper(@Nullable Contextt context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) { super(context, DBNAME,factory, VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { String sqlStr = "create table if not exits " + TABLE_USER + "(uid INTERGER PRIMARY KEY AUTOINCREMENT,"+ "name VARCHAR(30),"+ "age INTERGER,"+ "score DOUBLE)"; sqLiteDatabase.execSQL(sqlStr); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase,int i,int i1) { } }
|
MyProvider.java
public class MyProvider extends ContentProvider { private static final UriMatcher uriMatcher; private static final String AUTHORITY_PROVIDER = "a.b.c.db2.authority"; private static final int CODE_PROVIDER_USER = 11; private DBHelper dbHelper; private SqLiteDatabase db; uriMatcher = new UriMatcher(UriMather.NO_MATCH); uriMatcher.addURI(AUTHRITY_PROVIDER,DBHelper.TABLE_USER,CODE_PROVIDER_USER); @Override public boolean onCreate() { dbHelper = new DBHelper(getContext(),"",null,1); db = dbHelper.getWritableDatabase(); db.execSQL("insert into "+DBHelper.TABLE_USER+" values(1,'张三',19,87)" ); db.execSQL("insert into "+DBHelper.TABLE_USER+" values(2,'李四',18,87)" ); return true; } public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] string1, @Nullable String s1) { return null;
} @Nullable @Override public String getType(@NonNull Uri uri) { return ""; } public String getTableName(Uri uri) { String tableName = ""; if(uriMatcher.match(uri)==CODE_PROVIDER_USER) { tableName = DBHelper.TABLE_USER; } return tableName; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentvalues) { String tableName = getTableName(uri); if(TextUtils.isEmpty(tablename)) { return null; } long insetCount = db.insert(tableName,null,contentValues); if(inserCount>0) { Log.i("qqqqqqqq","insert ok"); } else { Log.i("qqqqqqqq","insert fail"); } return uri; } @Override public int delete(@NonNUll Uri uri, @Nullabe String s, @Nullable String[] strings)
{ String tableName = getTableName(uri); if(TextUtils.isEmpty(tableName)) { return 0; } int deleteCount = db.delete(tableName,s,strings); if(deleteCount>0) { Log.i("qqqqqqqq","delete ok"); } else { Log.i("qqqqqqqq","delete fail"); } return deleteCOunt; } @Override public int update(@NonNull Uri uri, @Nullable ContentValues contentValues,@Nullabel String s,@Nullable String[] strings) { String tableName = getTableName(uri); if(TextUtils.isEmpty) { return 0; } int updateCount = db.update(tableName,contentValues,s,strings); if(updateCount>0) { Log.i("qqqqqqqq","update ok"); } else { Log.i("qqqqqqqq","upadte fail"); } return updateCount; } }
|