我必須創建一個android應用程序,當接收到新消息時發出通知,即使應用程序不工作。我正在使用Firebase數據庫。我爲firebase datasnapshot編寫代碼,但它只在應用程序工作時才起作用,如果應用程序不工作,我需要運行此代碼。創建永無止境的後臺服務通知
Mref=new Firebase("https://iyutue-30s49.firebaseio.com/");
Mref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value=dataSnapshot.getValue(String.class);
myDb.GetAllData();
String idd= String.valueOf(myDb.id);
if (value.equals(idd)==true){
NotificationCompat.Builder builder=new NotificationCompat.Builder(getApplicationContext());
builder.setSmallIcon(R.drawable.ic_tab_profile);
builder.setContentTitle("plaese").setContentText("jijo");
Intent intent =new Intent(getApplicationContext(),MainActivity.class);
TaskStackBuilder stackBuilder=TaskStackBuilder.create(getApplicationContext());
stackBuilder.addParentStack(MainActivity.this);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent=stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManager NM=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
NM.notify(0,builder.build());
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
我需要在後臺執行該代碼時,應用程序是不是也工作請幫我感謝advnace
當應用程序未處於活動狀態時保持連接處於打開狀態將導致嚴重的電量耗盡並傷害用戶體驗。相反,建議您使用Firebase雲消息傳遞功能在用戶沒有打開應用程序時通知用戶。 –
@FrankvanPuffelen但在這裏我使用firebase,但這個代碼不工作,如果應用程序不活躍如何寫這種服務類型提前感謝 –
但其他主要應用程序,如whatzaap也運行後臺進程和服務總是..是不是最好的方法? –