当Firebase数据库值更改时,我需要在android应用程序中查看Toast消息。当应用关闭时,它也应该在后台运行,并且在那个时候没有在最近的应用中运行。我还需要查看带有后台服务的Toast消息。 Firebase实时数据库上的哪个值更改。
是否可以在android中做到这一点?请告诉我某人该怎么做以及我需要在Android应用中执行哪些服务?
下面是我的源代码
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.assistant.firebasebackground">
<application
android:name="com.assistant.firebasebackground.FireBaseService"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FireBaseService">
<intent-filter>
<action android:name="com.assistant.firebasebackground.FirebaseBackgroundService" />
</intent-filter>
</service>
<receiver android:name=".StartFirebaseAtBoot" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" >
</action>
</intent-filter>
</receiver>
</application>
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, FireBaseService.class);
startActivity(intent);
}}
FireBaseService.java
public class FireBaseService extends Service {
FirebaseDatabase firebaseDatabase;
private DatabaseReference f;
@Override
public void onCreate() {
super.onCreate();
firebaseDatabase = FirebaseDatabase.getInstance();
f = firebaseDatabase.getReference("https://firebaseurl.com/");
f.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
Toast.makeText(FireBaseService.this, dataSnapshot.getValue().toString(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}}
StartFirebaseAtBoot.java
public class StartFirebaseAtBoot extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context,FireBaseService.class);
context.startActivity(i);
}
}