android - 在后台获取聊天消息

标签 android firebase android-service

此代码在应用程序处于前台并为任何新消息生成通知时运行。但是我想在我的应用程序在后台时实现新聊天消息的通知。所以根据我的说法,当我使用“服务”在后台运行它时会发生这种情况,但我对实现它感到困惑。关于如何实现它的任何想法或建议。

package com.gyaanify.groups.campfire;

import android.app.NotificationManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.firebase.ui.database.FirebaseListAdapter;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.firebase.database.FirebaseDatabase;

import static android.R.id.message;

public class chat extends AppCompatActivity {

    private FirebaseListAdapter<ChatMessage> adapter;
    String domain;
    String name;
    String name_desig;
    String desig;
    String mesg;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        domain = getIntent().getStringExtra("domain");
        name = getIntent().getStringExtra("user");
        desig = getIntent().getStringExtra("desig");

        name_desig = name + " [" + desig + "]";

        displayChatMessages();

        FloatingActionButton fab =
                (FloatingActionButton) findViewById(R.id.fab);

        fab.setOnClickListener(new View.OnClickListener() {
                                   @Override
                                   public void onClick(View view) {
                                       EditText input = (EditText) findViewById(R.id.input);
                                       mesg = input.getText().toString();
                                       getmsg();

                                       // Read the input field and push a new instance
                                       // of ChatMessage to the Firebase database
                                       FirebaseDatabase.getInstance()
                                               .getReference(domain)
                                               .push()
                                               .setValue(new ChatMessage(input.getText().toString(), name_desig));

                                       // Clear the input


                                       input.setText("");
                                   }
                               }
        );

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    public String getmsg() {

        return mesg;


    }

    private void displayChatMessages() {

        ListView listOfMessages = (ListView) findViewById(R.id.list_of_messages);

        adapter = new FirebaseListAdapter<ChatMessage>(this, ChatMessage.class,
                R.layout.message, FirebaseDatabase.getInstance().getReference(domain)) {
            @Override
            protected void populateView(View v, ChatMessage model, int position) {
                // Get references to the views of message.xml
                TextView messageText = (TextView) v.findViewById(R.id.message_text);


                String abc = messageText.getNotification().getBody();

                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("Firebase Push Notification")
                        .setContentText(abc)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

                NotificationManager notificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                notificationManager.notify(0, notificationBuilder.build());


                TextView messageUser = (TextView) v.findViewById(R.id.message_user);
                TextView messageTime = (TextView) v.findViewById(R.id.message_time);

                // Set their text
                messageText.setText(model.getMessageText());
                messageUser.setText(model.getMessageUser());

                // Format the date before showing it
                messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)",
                        model.getMessageTime()));
            }
        };

        listOfMessages.setAdapter(adapter);

    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("chat Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
}

最佳答案

首先,根据您的要求使用 Service 或 IntentService 扩展您的类。在 AndroidManifest.xml 文件中进行更改,例如,您有一个类名 MyApp,

<service 
    android:name=".MyApp"
    android:exported="false">            
</service>

然后您可以使用 intent 启动您的服务:

startService(new Intent(getApplicationContext(), MyApp.class));

并停止你的服务:

stopService(new Intent(getApplicationContext(), MyApp.class));

关于android - 在后台获取聊天消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40957198/

相关文章:

android - getReference() 与 getChild()

javascript - Firebase 检索某个子项下的数据

android - 在android应用程序的后台服务中强制关闭

android - 如何在android中显示通知?

android - 在非 Activity 类之间传递字符串

swift - 从 firebase 下载图像链接时得到零

android - 运行一个服务的多个实例

android - 如何删除vcf文件中的重复联系人

android - 如何像 Whatsapp 和 Viber 一样在电话簿/联系人中添加我的应用程序连接?

android - 写入服务内的数据库