Android四大组件
前言
👨💻👨🌾📝记录学习成果,以便温故而知新
Gitee地址https://gitee.com/dycq/AppCode
先按部就班来四大组件
项目目录
1.Activity
由于Activity用法用到了private ActivityMainBinding binding,所以需要在“build.gradle”文件中如下图红框中的内容才能起作用
效果
直接上代码MainActivity、activity_main
package cn.fy.appcode;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import cn.fy.appcode.activity.NewActivity;
import cn.fy.appcode.databinding.ActivityMainBinding;
import cn.fy.appcode.notification.NotificationBroadcastReceiver;
import cn.fy.appcode.service.BindService;
import cn.fy.appcode.service.MyIntentService;
import cn.fy.appcode.service.StartService;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
/*** Service ***/
private BindService bindService;
private boolean isBind = false;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.e(getClass().getName(), "onServiceConnected");
bindService = ((BindService.LocalBinder) service).getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e(getClass().getName(), "onServiceDisconnected");
bindService = null;
}
};
/*** Content Provider ***/
private static final String TAB_NAME = "user";
private static final String AUTHORITY = "cn.fy.provider";
public static final Uri URI_USER_DIR = Uri.parse("content://" + AUTHORITY + "/" + TAB_NAME);
public static final Uri URI_USER_ITEM = Uri.parse("content://" + AUTHORITY + "/" + TAB_NAME + "/1");
// 数据库字段名
public static final String COLUMN_ID = "ID";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_AGE = "age";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//启动新Activity,并接收返回
binding.btnNewActivity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
launcherNewActivity.launch(true);
}
});
/*** Broadcast Receiver ***/
Button btnNotification = binding.btnNotification;
btnNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intentClick = new Intent(MainActivity.this, NotificationBroadcastReceiver.class);
intentClick.setAction("notification_clicked");
intentClick.putExtra(NotificationBroadcastReceiver.TYPE, 1);
PendingIntent pendingIntentClick = PendingIntent.getBroadcast(MainActivity.this, 0, intentClick, PendingIntent.FLAG_ONE_SHOT);
Intent intentCancel = new Intent(MainActivity.this, NotificationBroadcastReceiver.class);
intentCancel.setAction("notification_cancelled");
intentCancel.putExtra(NotificationBroadcastReceiver.TYPE, 1);
PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(MainActivity.this, 0, intentCancel, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
String CHANNEL_ID = "appcode_channel_id";
Notification notification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
.setContentTitle("这是测试通知标题") //设置标题
.setContentText("这是测试通知内容") //设置内容
.setWhen(System.currentTimeMillis()) //设置时间
.setSmallIcon(R.mipmap.ic_launcher) //设置小图标
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) //设置大图标
.setSound(defaultSoundUri)
.setContentIntent(pendingIntentClick)
.setDeleteIntent(pendingIntentCancel)
.setAutoCancel(true)
.build();
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(NotificationBroadcastReceiver.NOTIFICATION_ID, notification);
}
});
/*** Service ***/
Intent intentStart = new Intent(this, StartService.class);
Button btnStartService = binding.btnStartService;
btnStartService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.e(getClass().getName(), "onCreate1111");
startService(intentStart);
}
});
Button btnStopService = binding.btnStopService;
btnStopService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(intentStart);
}
});
Button btnBindService = binding.btnBindService;
btnBindService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isBind) {
Intent intentBind = new Intent(MainActivity.this, BindService.class);
bindService(intentBind, serviceConnection, Context.BIND_AUTO_CREATE);
isBind = true;
}
}
});
Button btnUnbindService = binding.btnUnbindService;
btnUnbindService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isBind) {
isBind = false;
unbindService(serviceConnection);
bindService = null;
}
}
});
Button btnIntentService = binding.btnIntentService;
btnIntentService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(MainActivity.this, MyIntentService.class));
}
});
/*** Content Provider ***/
binding.btnAddContentUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
providerInsert();
}
});
binding.btnEditContentUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
providerUpdate();
}
});
binding.btnDeleteContentUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
providerDelete();
}
});
binding.btnQueryContentUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
providerQuery();
}
});
}
/******Activity调用接收返回******/
ActivityResultLauncher launcherNewActivity = registerForActivityResult(new ActivityResultContract<Boolean, String>() {
@NonNull
@Override
public Intent createIntent(@NonNull Context context, Boolean input) {
Intent intent = new Intent(MainActivity.this, NewActivity.class);
intent.putExtra("b", input);
return intent;
}
@Override
public String parseResult(int resultCode, @Nullable Intent intent) {
return intent.getStringExtra("resultMsg");
}
}, result -> Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show());
// 通过ContentProvider插入数据
private void providerInsert() {
runDatabase(() -> {
ContentValues values = new ContentValues();
// 数据库字段名+当前字段值
values.put(COLUMN_NAME, "Tom");
values.put(COLUMN_AGE, 1);
Uri insertUri = getContentResolver().insert(URI_USER_DIR, values);
Log.d(getClass().getName(), "providerInsert:: " + insertUri);
});
}
private void providerUpdate() {
runDatabase(() -> {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, "Tom");
values.put(COLUMN_AGE, 1);
int updateId = getContentResolver().update(URI_USER_ITEM, values, null,
null);
Log.d(getClass().getName(), "providerUpdate:: " + updateId);
});
}
private void providerDelete() {
runDatabase(() -> {
int deleteId = getContentResolver().delete(URI_USER_ITEM, null, null);
Log.d(getClass().getName(), "providerDelete:: " + deleteId);
});
}
private void providerQuery() {
runDatabase(() -> {
Cursor cursor = getContentResolver().query(URI_USER_DIR, null, null,
null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_NAME));
Log.d(getClass().getName(), "providerQuery id:: " + id + " ,name:: " + name);
}
cursor.close();
}
});
}
private void runDatabase(Runnable target) {
new Thread(target).start();
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_start_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="90dp"
android:layout_marginTop="20dp"
android:text="开始"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/divider2" />
<Button
android:id="@+id/btn_stop_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginEnd="90dp"
android:text="停止"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/divider2" />
<Button
android:id="@+id/btn_bind_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="90dp"
android:layout_marginTop="20dp"
android:text="绑定"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_start_service" />
<Button
android:id="@+id/btn_unbind_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginEnd="90dp"
android:text="解绑"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_stop_service" />
<Button
android:id="@+id/btn_intent_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="90dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="90dp"
android:text="IntentService"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_bind_service" />
<View
android:id="@+id/divider"
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_marginStart="1dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="1dp"
android:background="?android:attr/listDivider"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_intent_service" />
<Button
android:id="@+id/btn_add_content_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="90dp"
android:layout_marginTop="20dp"
android:text="新增"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/divider" />
<Button
android:id="@+id/btn_edit_content_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginEnd="90dp"
android:text="修改"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/divider" />
<Button
android:id="@+id/btn_delete_content_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="88dp"
android:layout_marginTop="20dp"
android:text="删除"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_add_content_user" />
<Button
android:id="@+id/btn_query_content_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginEnd="90dp"
android:text="查询"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_edit_content_user" />
<View
android:id="@+id/divider2"
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_marginStart="1dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="1dp"
android:background="?android:attr/listDivider"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_notification" />
<Button
android:id="@+id/btn_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="90dp"
android:layout_marginTop="20dp"
android:text="通知"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/divider3" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="2dp"
android:layout_marginTop="2dp"
android:text="Service"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/divider2" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="2dp"
android:layout_marginTop="2dp"
android:text="Provider"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/divider" />
<Button
android:id="@+id/btn_new_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="90dp"
android:layout_marginTop="20dp"
android:text="活动"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="@+id/divider3"
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_marginStart="1dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="1dp"
android:background="?android:attr/listDivider"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_new_activity" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="2dp"
android:layout_marginTop="2dp"
android:text="Activity"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="2dp"
android:layout_marginTop="2dp"
android:text="Broadcast Receiver"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/divider3" />
</androidx.constraintlayout.widget.ConstraintLayout>
新MainActivity、activity_new
package cn.fy.appcode.activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import cn.fy.appcode.databinding.ActivityNewBinding;
public class NewActivity extends AppCompatActivity {
private ActivityNewBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_new);
binding = ActivityNewBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("新Activity");
binding.btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.putExtra("resultMsg", "按钮返回");
setResult(RESULT_OK, intent);
finish();
}
});
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent();
intent.putExtra("resultMsg", "home 返回");
setResult(RESULT_OK, intent);
finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.NewActivity">
<Button
android:id="@+id/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="90dp"
android:layout_marginTop="20dp"
android:text="返回"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
(1)开启新Activity
//启动新Activity,并接收返回
binding.btnNewActivity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
launcherNewActivity.launch(true);
}
});
/******Activity调用接收返回******/
ActivityResultLauncher launcherNewActivity = registerForActivityResult(new ActivityResultContract<Boolean, String>() {
@NonNull
@Override
public Intent createIntent(@NonNull Context context, Boolean input) {
Intent intent = new Intent(MainActivity.this, NewActivity.class);
intent.putExtra("b", input);
return intent;
}
@Override
public String parseResult(int resultCode, @Nullable Intent intent) {
return intent.getStringExtra("resultMsg");
}
}, result -> Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show());
(2)新Activity返回传参
Intent intent = new Intent();
intent.putExtra("resultMsg", "home 返回");
setResult(RESULT_OK, intent);
finish();
2.Broadcast Receiver
直接上代码NotificationBroadcastReceiver
package cn.fy.appcode.notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class NotificationBroadcastReceiver extends BroadcastReceiver {
public static final String TYPE = "type"; //这个type是为了Notification更新信息的
public static final int NOTIFICATION_ID = 1;
@Override
public void onReceive(Context context, Intent intent) {
Log.e(getClass().getName(), "onReceive");
String action = intent.getAction();
int type = intent.getIntExtra(TYPE, -1);
if (type != -1) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
}
if (action.equals("notification_clicked")) {
//处理点击事件
}
if (action.equals("notification_cancelled")) {
//处理滑动清除和点击删除事件
}
}
}
3.Content Provider
直接上代码UserContentProvider
package cn.fy.appcode.provider;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import cn.fy.appcode.db.SQLite;
import java.util.List;
public class UserContentProvider extends ContentProvider {
private static final String TAG = "UserContentProvider";
private static final String DB_NAME = "SQL.db";
private static final String TABLE_USER = "user";
private static final int USER_DIR = 0;
private static final int USER_ITEM = 1;
private static final String AUTHORITY = "cn.fy.provider";
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sUriMatcher.addURI(AUTHORITY, "user", USER_DIR);
sUriMatcher.addURI(AUTHORITY, "user/#", USER_ITEM);
}
private SQLite sqLite;
public UserContentProvider() {
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase database = sqLite.getWritableDatabase();
int deleteRows = 0;
switch (sUriMatcher.match(uri)) {
case USER_DIR:
deleteRows = database.delete(TABLE_USER, selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
break;
case USER_ITEM:
List<String> segments = uri.getPathSegments();
if (segments.size() < 2) {
return deleteRows;
}
String gestureId = segments.get(1);
deleteRows = database.delete(TABLE_USER, "id=?", new String[]{gestureId});
getContext().getContentResolver().notifyChange(uri, null);
break;
}
return deleteRows;
}
@Override
public String getType(Uri uri) {
int match = sUriMatcher.match(uri);
switch (match) {
// 1. 必须以vnd开头
// 2. 如果内容URI以路径结尾,则后接android.cursor.dir/,
// 如果内容URI以id结尾,则后接android.cursor.item/
// 3. 最后接上vnd.<authority>.<path>
case USER_DIR:
return "vnd.android.cursor.dir/vnd." + AUTHORITY + ".user";
case USER_ITEM:
return "vnd.android.cursor.item/vnd." + AUTHORITY + ".user";
default:
throw new IllegalArgumentException(String.format("Unknown URI: %s", uri));
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase database = sqLite.getWritableDatabase();
Uri uriReturn = null;
switch (sUriMatcher.match(uri)) {
case USER_DIR:
case USER_ITEM:
long userId = database.insert(TABLE_USER, null, values);
uriReturn = Uri.parse("content://" + AUTHORITY + "/user/" + userId);
getContext().getContentResolver().notifyChange(uriReturn, null);
break;
}
return uriReturn;
}
@Override
public boolean onCreate() {
Context context = getContext();
if (context == null) {
return false;
}
sqLite = new SQLite(context);
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// 查询数据
SQLiteDatabase database = sqLite.getReadableDatabase();
Cursor cursor = null;
switch (sUriMatcher.match(uri)) {
case USER_DIR:
cursor = database.query(TABLE_USER, projection, selection, selectionArgs,
null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
break;
case USER_ITEM:
List<String> segments = uri.getPathSegments();
if (segments.size() < 2) {
return null;
}
String gestureId = segments.get(1);
cursor = database.query(TABLE_USER, projection, "id=?", new String[]{gestureId},
null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
break;
}
return cursor;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase database = sqLite.getWritableDatabase();
int updateRows = 0;
switch (sUriMatcher.match(uri)) {
case USER_DIR:
updateRows = database.update(TABLE_USER, values, selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
break;
case USER_ITEM:
List<String> segments = uri.getPathSegments();
if (segments.size() < 2) {
return updateRows;
}
String gestureId = segments.get(1);
updateRows = database.update(TABLE_USER, values, "id=?", new String[]{gestureId});
getContext().getContentResolver().notifyChange(uri, null);
break;
}
return updateRows;
}
}
4.Service
直接上代码StartService、BindService、MyIntentService
package cn.fy.appcode.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
public class StartService extends Service {
@Override
public void onCreate() {
super.onCreate();
Log.e(getClass().getName(), "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(getClass().getName(), "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e(getClass().getName(), "onDestroy");
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
package cn.fy.appcode.service;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import cn.fy.appcode.R;
import cn.fy.appcode.MainActivity;
public class BindService extends Service {
//声明IBinder接口的一个接口变量mBinder
public final IBinder mBinder = new LocalBinder();
private NotificationManager mNM;
private int NOTIFICATION = 2;
//LocalBinder是继承Binder的一个内部类
public class LocalBinder extends Binder {
public BindService getService() {
return BindService.this;
}
}
@Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Log.e(getClass().getName(), "onCreate");
showNotification();
}
@Override
public void onDestroy() {
Log.e(getClass().getName(), "onDestroy");
mNM.cancel(NOTIFICATION);
Toast.makeText(this, "销毁", Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
Log.e(getClass().getName(), "onBind");
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
Log.e(getClass().getName(), "onUnbind");
return super.onUnbind(intent);
}
private void showNotification() {
CharSequence text = "开始";
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setTicker(text)
.setWhen(System.currentTimeMillis())
.setContentTitle("绑定服务")
.setContentText(text)
.setContentIntent(contentIntent)
.build();
mNM.notify(NOTIFICATION, notification);
Log.e(getClass().getName(), "通知栏已出");
}
}
package cn.fy.appcode.service;
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.util.Log;
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.e(getClass().getName(), "onHandleWork");
for (int i = 0; i < 3; i++) {
try {
Log.e(getClass().getName(), "Number:开始"+i);
Thread.sleep(10000);
Log.e(getClass().getName(), "Number:结束"+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e(getClass().getName(), "onDestroy");
}
}
5.AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AppCode"
tools:targetApi="31">
<activity
android:name=".activity.NewActivity"
android:exported="false">
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
<service
android:name=".service.StartService"
android:enabled="true"
android:exported="true" />
<service
android:name=".service.BindService"
android:enabled="true"
android:exported="true" />
<service
android:name=".service.MyIntentService"
android:enabled="true"
android:exported="false" />
<provider
android:name=".provider.UserContentProvider"
android:authorities="cn.fy.provider"
android:enabled="true"
android:exported="true" />
</application>
</manifest>
6. 其他代码
SQLite代码
package cn.fy.appcode.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class SQLite extends SQLiteOpenHelper {
public SQLite(Context context) {
super(context, "SQL.db", null, 1);
//第一个参数对应的是一个上下文,第二个参数对应的是数据库的名称,第三个参数一般为空就好了,第四个参数对应的是数据库的版本号默认为一就好了
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
Log.i(getClass().getName(), "onCreate");
//删除表
String sql = "drop table if exists user;";
sqLiteDatabase.execSQL(sql);
//创建表
sql = "create table user(ID INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(30), age Integer )";
//创建一个表,表的名称叫user这里面会有四个字段,Integer是整形,varchar数据量的大小是根据后面括号进行变化
sqLiteDatabase.execSQL(sql);
Log.i(getClass().getName(), sql);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}