在我的服务中无法停止Firebase服务

时间:2017-02-21 06:32:29

标签: android firebase firebase-cloud-messaging

public class FirstService extends Service {

    private static String TAG = "Service";
    Boolean isLoggedIn;
    SharedPreferences sharedPreferences;


    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub

        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Log.d(TAG, "FirstService started");
        sharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE);
        isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
        if(isLoggedIn){
            Intent intent1 = new Intent(this,MyFirebaseMessagingService.class);
            startService(intent1);
        }
        else
        {
            stopService(new Intent(this, MyFirebaseMessagingService.class));
            stopService(new Intent(this, MyFirebaseInstanceIDService.class));
        }


    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        sharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE);
        isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
        if(isLoggedIn){
            Intent intent = new Intent(this,MyFirebaseMessagingService.class);
            startService(intent);
        }
        else
        {
            stopService(new Intent(this, MyFirebaseMessagingService.class));
            stopService(new Intent(this, MyFirebaseInstanceIDService.class));

        }
        Log.d(TAG, "FirstService destroyed");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        sharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE);
        isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
        if(isLoggedIn){
            Intent intent = new Intent(this,MyFirebaseMessagingService.class);
            startService(intent);
        }
        else
        {
            stopService(new Intent(this, MyFirebaseMessagingService.class));
            stopService(new Intent(this, MyFirebaseInstanceIDService.class));
        }
        Log.d(TAG, "FirstService tastremove");
    }
}

如何在自定义服务中停止FCM服务?第一项服务开始,但在后台,我的服务无法正常工作,即使我没有在我的应用程序中登录,FCM服务也会自动启动并向我发送通知?

1 个答案:

答案 0 :(得分:2)

FirebaseMessagingService在接收邮件方面没有积极的作用。它仅用于在收到消息后处理消息。

即使您停止了Android,当新邮件到达时,Android也会再次启动它。

如果您希望应用停止接收消息,可以停止发送,也可以使用weights

删除您的FCM令牌