Подтвердить что ты не робот

Уведомление GCM push не отображается в некоторых устройствах, когда приложение не запускается

Я внедряю уведомление GCM Push в своем приложении и успешно его завершаю, но на некоторых устройствах он не показывает уведомления, когда приложение закрывается.

Список устройств, уведомление которых не отображается:

реая-2

Lenovo

Gionee

Может ли кто-нибудь объяснить мне, что является проблемой и как я ее решаю.

здесь мой манифест: -

     <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="student.skoolstar.android.catalyst.com.schoolstar.skoolstarstudent">

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


  <uses-permission android:name="android.permission.GET_ACCOUNTS" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />

  <permission
   android:name="student.skoolstar.android.catalyst.com.schoolstar.skoolstarstudent.permission.C2D_MESSAGE"
   android:protectionLevel="signature" />

  <uses-permission android:name="student.skoolstar.android.catalyst.com.schoolstar.skoolstarstudent.permission.C2D_MESSAGE" />
  <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.VIBRATE" />

  <application
   android:name="student.skoolstar.android.catalyst.com.schoolstar.skoolstarstudent.Controller"
   android:allowBackup="true"
   android:icon="@mipmap/ic_launcher"
   android:label="@string/app_name"
   android:supportsRtl="true"
   android:theme="@style/MyMaterialTheme">
   <activity android:name=".MainActivity">
    <intent-filter>
     <action android:name="android.intent.action.MAIN" />

     <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
   </activity>
   <activity
    android:name=".Login"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateHidden">
   </activity>
   <activity
    android:name=".ListOfClass"
    android:screenOrientation="portrait">
   </activity>
   <activity
    android:name=".EditProfile"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateHidden">
   </activity>
   <activity
    android:name=".ShowStudentList"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateHidden">
   </activity>
   <receiver
    android:name="student.skoolstar.android.catalyst.com.schoolstar.skoolstarstudent.GcmBroadcastReceiver"
    android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>

     <!-- Receives the actual messages. -->
     <action android:name="com.google.android.c2dm.intent.RECEIVE" />
     <!-- Receives the registration id. -->
     <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

     <category android:name="schoolstar.com.catalyst.android.skoolstar" />
    </intent-filter>
   </receiver>

   <service android:name=".GCMNotificationIntentService" />
   <activity
    android:name=".Message"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateHidden">
   </activity>
   <activity
    android:name=".Attendance"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateHidden">
   </activity>

   <activity
    android:name=".NewMessage"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateHidden">
   </activity>
   <activity
    android:name=".GroupMessage"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateHidden">
   </activity>
   <activity
    android:name=".Test_Chat"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateHidden">
   </activity>
  </application>

 </manifest>

здесь мое имя службы GCMNotificationIntentService: -

    public class GCMNotificationIntentService extends GCMBaseIntentService {
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    Database db;

    private Controller aController = null;

    public GCMNotificationIntentService() {
        // Call extended class Constructor GCMBaseIntentService
        super(Constants.GOOGLE_SENDER_ID);
    }

    public static final String TAG = "GCMNotificationIntentService";

    @Override
    protected void onRegistered(Context context, String registrationId) {

    }
    @Override
    protected void onUnregistered(Context context, String registrationId) {
        Log.d("unref",registrationId);
        if(aController == null)
            aController = (Controller) getApplicationContext();
        Toast.makeText(getApplicationContext(),"hello no",Toast.LENGTH_LONG).show();

        aController.displayMessageOnScreen(context,
                getString(R.string.gcm_unregistered));
        aController.unregister(context, registrationId);
    }

    @Override
    public void onError(Context context, String errorId) {

        Log.d("error","");

        if(aController == null)
            aController = (Controller) getApplicationContext();

        aController.displayMessageOnScreen(context,

                getString(R.string.gcm_error, errorId));
    }
    @Override
    protected void onMessage(Context context, Intent intent) {

        if(aController == null)
            aController = (Controller) getApplicationContext();

        aController.acquireWakeLock(getApplicationContext());

        String message = intent.getExtras().getString("message");
        String formuser = intent.getExtras().getString("formuser");

        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+5:30"));
        Date currentLocalTime = cal.getTime();
        DateFormat date = new SimpleDateFormat("HH:mm a");
        date.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
        String localTime = date.format(currentLocalTime);


        db = new Database(context);
        int  from_id = 0;

        List<FetchData> fetchdata = db.getAllContacts();
        for (FetchData fd : fetchdata)
        {

            from_id=fd.getID();//get ser no
        }

        db.storeMessage(420, formuser, from_id + "", message, "text", localTime, "F", "ST", "R");

        aController.displayMessageOnScreen(context, message);
        // notifies user
        sendNotification(context,message);
    }

    private void sendNotification(Context context,String msg) {
        String app_name = context.getResources().getString(R.string.app_name);
        mNotificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, ListOfClass.class), 0);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(app_name)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText("New Message")
                .setSound(alarmSound);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
        wl.acquire(15000);
        //  Log.d(TAG, "Notification sent successfully.");
    }
}

Когда я вижу приложение whatsapp, поход и другие уведомления, он всегда будет работать в фоновом потоке, но мое приложение не работает всегда в фоновом режиме. Так может быть и по этой причине. Я недавно работал над андроидом, пожалуйста, помогите мне. Спасибо заранее!

4b9b3361

Ответ 1

Я столкнулся с аналогичной проблемой с Redmi-2. В коде нет никаких проблем, но это связано с пользовательским интерфейсом, предоставленным производителем, таким как MIUI 6. Итак, чтобы включить уведомления GCM

Перейдите в приложение "Безопасность" → Нажмите "Разрешения" → Нажмите "Автозапуск" и включите автозапуск приложения.

Ответ 2

Для этого есть две основные причины:

1 - Некоторые устройства не позволяют вам запускать службу на фоне, например redmi-2 (почти на всех устройствах xiaomi). Даже то, что приложение не может нормально работать на них, если пользователь не разрешит их, перейдя в приложение "Безопасность" → Нажмите "Разрешения" → Нажмите "Автозапуск" и включите автозапуск для whatsapp и т.д. В этом случае все, что вы можете сделать, это показать детали это для пользователя при запуске приложения. И откройте этот экран и направьте пользователя (если возможно), как чистый мастер.

2- Вторая причина заключается в том, что он не работал на одном из телефонов, приложение Google Play Services установлено неправильно (и его необходимо для GCM). Вы также ничего не можете сделать на этих устройствах. Единственное, что вы можете сделать в этом случае, это просто показать пользователю сообщение об этом.

Таким образом, по моему опыту всегда найдется несколько пользователей (но очень маленький процент), которые не получат push GCM.

Ответ 3

Существует концепция белого списка в телефоне Xiaomi. Итак, если вы ввели logon onReceive gcm, вы заметите, что gcm получает, но не обрабатывает его дальше. Это связано с тем, что ваше приложение не включено в белый список.

Xiaomi для целей безопасности отключает уведомление для каждого приложения. Выполните следующие шаги, чтобы получать сообщения в фоновом режиме, как только они покидают приложение, используя очиститель.

  • Включить автозапуск
  • Включить плавающее и заблокированное уведомление на экране

Включить автозапуск

  • Открыть приложение безопасности.
  • Получите разрешения, затем нажмите "Автоматическое управление запуском".
  • Добавить/включить приложения для автоматического запуска (например, Whatsapp).

Включить оповещение плавающего и заблокированного экрана

  • Откройте приложение "Настройки".
  • Нажмите "Уведомления", затем нажмите "Управление уведомлениями".
  • Нажмите на приложение, которое вы ищете (например, WhatsApp).
  • Включить показ в тени уведомлений/Показать на заблокированном экране и в раскрывающемся меню.

Для справки проверьте это: http://support.hike.in/entries/55998480-I-m-not-getting-notification-on-my-Xiaomi-Phone-For-MIUI-6-

Я добился успеха в этом. Надеюсь, это поможет.

Ответ 4

Опираясь на одну и ту же проблему, единственное, что мы сделали, - это обучить пользователей xiaomi выполнению шагов, упомянутых в @anup-dasari, и установить высокий приоритет gcm, с возможностью иметь постоянное обслуживание в будущем