Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/203.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在定制操作系统手机(如Oppo、维梧、MIUI)上处理FCM通知?_Java_Android_Firebase_Push Notification_Firebase Cloud Messaging - Fatal编程技术网

Java 如何在定制操作系统手机(如Oppo、维梧、MIUI)上处理FCM通知?

Java 如何在定制操作系统手机(如Oppo、维梧、MIUI)上处理FCM通知?,java,android,firebase,push-notification,firebase-cloud-messaging,Java,Android,Firebase,Push Notification,Firebase Cloud Messaging,我已经在我的Android应用程序中实现了FCM推送通知。 我得到了数据负载中所有的JSON通知。我还没有在api上添加“通知”标记。因此,在所有状态(前台/后台/终止)中,我只收到数据有效负载中的通知 在所有州,当应用程序处于前台/后台/死机状态时,它在Moto、Google等非定制操作系统手机上都能正常工作。但问题是,当我在定制的操作系统手机上测试时,如Oppo、Vivo或MIUI,只有当应用程序位于前台或后台(应用程序在内存中)时,通知才会到达,而当应用程序“被杀死”(不在内存中)时,通知

我已经在我的Android应用程序中实现了FCM推送通知。 我得到了数据负载中所有的JSON通知。我还没有在api上添加“通知”标记。因此,在所有状态(前台/后台/终止)中,我只收到数据有效负载中的通知

在所有州,当应用程序处于前台/后台/死机状态时,它在Moto、Google等非定制操作系统手机上都能正常工作。但问题是,当我在定制的操作系统手机上测试时,如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] -->

这是一个由来已久的故事,有MIUI、维梧等定制操作系统提供商 他们对电池优化政策非常严格,因此当应用程序关闭时,他们甚至不允许粘性服务重新启动,这是您面临此问题的主要原因。 虽然您的代码无法帮助您的用户,但您可以将他们带到他们的
安全中心
,让他们启用
自动启动
功能。 为此,您必须添加以下代码:

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);
}
试试看{
意图=新意图();
字符串制造商=android.os.Build.manufacturer;
if(“小米”。等效信号(制造商)){
setComponent(新组件名称(“com.miui.securitycenter”、“com.miui.permcenter.autostart.AutoStartManagementActivity”);
}else if(“oppo”。等效信号案例(制造商)){
setComponent(新组件名(“com.coloros.safecenter”、“com.coloros.safecenter.permission.startup.StartupAppListActivity”);
}否则,如果(“维梧”。等效信号(制造商)){
setComponent(新组件名称(“com.vivo.permissionmanager”、“com.vivo.permissionmanager.activity.BgStartUpManagerActivity”);
}else if(“oneplus.equalsIgnoreCase(制造商)){
intent.setComponent(新组件名称(“com.oneplus.security”、“com.oneplus.security.chainlaunch.view.ChainLaunchAppListAct‌​);}
List List=context.getPackageManager().QueryInputActivities(intent,PackageManager.MATCH_DEFAULT_仅限);
如果(list.size()>0){
背景。开始触觉(意图);
} 
}捕获(例外e){
Crashlytics.logException(e);
}
此应用程序会将用户带到安全中心,您必须要求他们为您的应用程序启用自动启动功能。
现在像whatsapp和instagram这样的应用程序没有这样的问题,但我不清楚原因,正如我在设备上看到的,这些应用程序默认启用自动启动。

我找到了解决这个问题的方法。为您的应用程序编写一个在后台连续运行的自定义服务,并编写一个广播接收器,以便在服务终止后重新启动该服务。这对我来说很好。我已经在维梧、Oppo、Redmi手机上测试过了。它正在工作

我的服务代码如下--

我的收音机如下--

我的AndroidManifest.xml文件如下--


添加您的代码,它将使您的服务必须运行才能捕获通知。确保应用程序被终止时,您的服务未停止。使用“stickyIntent”使您的服务在手动终止时自动启动。@AkashKhatri您可以将其示例代码发送给我吗?您可以在此处找到您要查找的内容:@AkashKhatri我的服务器端is代码与您链接的代码snipest中给出的代码完全相同。我只添加了“数据”标记以接收自定义键值对通知。如果您想在启动屏幕上添加这些行并运行一次,请注意,您的应用程序将不知道用户是否启用了自动启用,因此您可以只运行一次此代码。此外,你应该考虑提供一个很好的免责声明给你的用户,为什么你需要这个许可被启用,如果他们选择禁用它,他们可能会失去什么。找不到显式活动类{com.vivo.permissionmanager/com.vivo.permissionmanager.activity.BgStartUpManagerActivity};他们可能已经重构了他们的包,为了找到要打开的包,你必须制作一个应用程序,记录设备中打开的每个应用程序,你可以通过扩展AccessibilityService并记录正在打开的包来做到这一点,这就是我如何获得设置文件的包名的方法,虽然这有点复杂。
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);

}}
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 _________");

    }
}}
 <!-- 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>
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);
}}