簡體   English   中英

如何在定制的OS手機(如Oppo,Vivo,MIUI)上處理FCM通知?

[英]How to handle FCM notifications on customized OS phones like Oppo, Vivo, MIUI?

我已經在Android應用中實現了FCM推送通知。 我在數據有效負載中獲得了所有通知JSON。 我還沒有在api上添加“ Notification”標簽。 因此,在所有狀態(前景/背景/已殺死)中,我僅在數據有效負載中收到了通知。

當應用程序為前台/背景/殺死時,在非定制OS手機(如Moto,Google等)上以及在所有國家/地區都可以正常工作。 但是問題是,當我在自定義OS手機(例如OppoVivoMIUI)上進行測試時,通知僅在應用位於前景或后台(應用位於內存中)時到達,而在應用被“殺死”時未到達/出現(不是在記憶中)。

我該怎么辦?

無論如何,謝謝您的時間。

public class MyFirebaseMessagingService extends FirebaseMessagingService{
    private static final String TAG = "MyFirebaseMsgService";

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // [START_EXCLUDE]
        // There are two types of messages data messages and notification messages. Data messages are handled
        // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
        // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
        // is in the foreground. When the app is in the background an automatically generated notification is displayed.
        // When the user taps on the notification they are returned to the app. Messages containing both notification
        // and data payloads are treated as notification messages. The Firebase console always sends notification

        // [END_EXCLUDE]

        // TODO(developer): Handle FCM messages here.

        Log.e(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0)
        {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

            if (remoteMessage.getNotification()!=null)
            sendNotification(remoteMessage.getNotification().getBody());
            else
                sendNotification("Body");

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null)
        {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            if (remoteMessage.getNotification()!=null)
                sendNotification(remoteMessage.getNotification().getBody());
            else
                sendNotification("Body");

        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }
    // [END receive_message]

    /**
     * Schedule a job using FirebaseJobDispatcher.
     */
    private void scheduleJob() {
        // [START dispatch_job]
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
        Job myJob = dispatcher.newJobBuilder()
                .setService(MyJobService.class)
                .setTag("my-job-tag")
                .build();
        dispatcher.schedule(myJob);
        // [END dispatch_job]
    }

    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String messageBody)
    {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setContentTitle("FCM Message")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

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

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }

        if (notificationManager != null) {
            notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
        }
    }

}

我的AndroidManifest.xml文件如下:

<!-- [START firebase_iid_service] -->
    <service
        android:name=".Firebase.FirebaseId">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
    <service
        android:name="Firebase.MyFirebaseMessagingService"
        android:stopWithTask="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <!-- [END firebase_iid_service] -->

    <!--
   Set custom default icon. This is used when no icon is set for incoming notification messages.

   -->
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_launcher_background" />
    <!--
         Set color used with incoming notification messages. This is used when no color is set for the incoming
         notification message.
    -->
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/colorAccent" />

    <!-- [START fcm_default_channel] -->
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="@string/default_notification_channel_id" />
    <!-- [END fcm_default_channel] -->

好吧,我已經找到了解決這個問題的方法。 為您的應用程序編寫一個自定義服務,該應用程序在后台連續運行,並編寫一個廣播接收器以終止該服務后重新啟動該服務。 這對我來說很好。 我已經在Vivo,Oppo,Redmi手機上對此進行了測試。 這是工作!

我的服務代碼如下-

public class MyService extends Service
{

private static final String TAG = "MyService";


@Override
public void onStart(Intent intent, int startId)
{
    // TODO Auto-generated method stub
    super.onStart(intent, startId);
}

@Override
public boolean onUnbind(Intent intent) {
    return super.onUnbind(intent);
}


@Override
public void onCreate()
{
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    //call to onTaskRemoved
    onTaskRemoved(intent);
    //return super.onStartCommand(intent, flags, startId);
    Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();

    return START_NOT_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent)
{
    return null;
}

@Override
public void onDestroy()
{
    Toast.makeText(this, "Service Destroyed!", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent("com.myapp.startservice");
    //Intent intent = new Intent("android.intent.action.BOOT_COMPLETED");
    intent.putExtra("yourvalue", "torestore");
    sendBroadcast(intent);
    super.onDestroy();

}



@Override public void onTaskRemoved(Intent rootIntent)
{
    Log.e("onTaskRemoved", "Called!");

    //thread = new Thread(this);
    //startThread();

    /*Intent alarm = new Intent(this.getApplicationContext(), MyBroadCastReceiver.class);
    boolean alarmRunning = (PendingIntent.getBroadcast(this.getApplicationContext(), 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
    //if(!alarmRunning)
    {
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, alarm, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        if (alarmManager != null) {
            alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 10000, pendingIntent);
        }
    }*/

     //send broadcast to your BroadcastReciever
    Intent intent = new Intent("com.myapp.startservice"); //unique String to uniquely identify your broadcastreceiver
    //Intent intent = new Intent("android.intent.action.BOOT_COMPLETED");
    intent.putExtra("yourvalue", "torestore");
    sendBroadcast(intent);

     //intent to restart your service.
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    if (alarmService != null) {
        alarmService.set(
                AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime() + 1000,
                restartServicePendingIntent);
    }

    super.onTaskRemoved(rootIntent);

}}

我的BroadcastReceiver如下-

public class MyBroadCastReceiver extends BroadcastReceiver
{

@Override
public void onReceive(Context context, Intent intent)
{
    Log.e("MyBroadCastReceiver", "onReceive");

    //if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
    {
        Intent service = new Intent(context, MyService.class);
        context.startService(service);
        Log.e("BootCompleteReceiver", " __________BootCompleteReceiver _________");

    }
}}

我的AndroidManifest.xml文件如下-

 <!-- My Service -->
    <service
        android:name=".Service.MyService"
        android:exported="false"
        android:stopWithTask="false" />


    <!-- My Broadcast Receiver -->
    <receiver
        android:name=".Service.MyBroadCastReceiver"
        android:enabled="true"
        android:exported="false">

        <intent-filter>
            <action android:name="com.myapp.startservice" />
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE"/>
            <category android:name="android.intent.category.DEFAULT"/>

        </intent-filter>

    </receiver>

和我的MainActivity.java文件代碼一起啟動服務-

public class MainActivity extends AppCompatActivity
{

Button btnStopService;

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

    btnStopService = findViewById(R.id.btnStopService);

    //get FirebaseToken
    getToken();

    //start Service
    startService();



    btnStopService.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, MyService.class);
            stopService(intent);
        }
    });

}


private void getToken()
{
    FirebaseId firebaseId=new FirebaseId();
    String token_firebase=firebaseId.getFireBaseToken();
}


private void startService()
{

    Intent myIntent = new Intent(this, MyService.class);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
    Log.e("TAG", "++++++++++222222++++++++");
    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    // calendar.setTimeInMillis(System.currentTimeMillis());
    //calendar.add(Calendar.SECOND, 10);
    if (alarmManager != null) {
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    }

    Toast.makeText(this, "Start Alarm", Toast.LENGTH_LONG).show();

}

private void s()
{
    Intent intent = new Intent(this, MyService.class);
    startService(intent);
}}

這是自定義操作系統提供商(例如MIUI,Vivo等)的悠久歷史,他們對電池優化策略非常嚴格,因此即使關閉應用程序,他們也不允許粘性服務重新啟動,這就是您選擇該操作系統的主要原因正在面對這個問題。 盡管您無法通過代碼執行任何操作來幫助您的用戶,但是您可以將他們帶到其Security Center並要求他們啟用auto-start功能。 為此,您必須添加以下代碼:

try {
    Intent intent = new Intent();
    String manufacturer = android.os.Build.MANUFACTURER;
    if ("xiaomi".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
    } else if ("oppo".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"));
    } else if ("vivo".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
    } else if("oneplus".equalsIgnoreCase(manufacturer)) { 
        intent.setComponent(new ComponentName("com.oneplus.security", "com.oneplus.security.chainlaunch.view.ChainLaunchAppListAct‌​ivity")); }

    List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    if  (list.size() > 0) {
        context.startActivity(intent);
        } 
    } catch (Exception e) {
        Crashlytics.logException(e);
}

此應用會將用戶帶到安全中心,在該中心您必須要求他們為您的應用啟用自動啟動功能。 現在,諸如whatsapp和instagram之類的應用程序沒有此類問題,但我不清楚原因。正如我在設備上看到的那樣,默認情況下,這些應用程序已啟用自動啟動。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM