2015-09-02 2 views
47

Я работаю над уведомлениями, и мне нужно использовать setLatestEventInfo. Тем не менее, Android Studio показывает следующее сообщение об ошибке:Невозможно решить метод setLatestEventInfo

не может решить метод setLatestEventinfo

Вот мой фрагмент кода:

private void createNotification(Context context, String registrationID) { 
    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); 
    Notification notification = new Notification(R.drawable.icon,"Registration Successfull",System.currentTimeMillis()); 
    notification.flags |= Notification.FLAG_AUTO_CANCEL; 
    Intent intent = new Intent(context,RegistrationResultActivity.class); 
    intent.putExtra("registration_ID",registrationID); 
    PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent,0); 
    notification.setLatestEventInfo(context,"Registration","Successfully Registered",pendingIntent); 
} 

Или, если их еще один способ сделать это, пожалуйста предложите мне это.

+10

'setLatestEventInfo' является' 'устаревшее сделать это с помощью' NotificationCompat.Builder' –

ответ

66

Хорошо внизу - это простой пример работы с уведомлениями, пройдите через него, надейтесь, что это поможет!

MainActivity.java

public class MainActivity extends ActionBarActivity { 

    Button btnShow, btnClear; 
    NotificationManager manager; 
    Notification myNotication; 

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

     initialise(); 

     manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

     btnShow.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       //API level 11 
       Intent intent = new Intent("com.rj.notitfications.SECACTIVITY"); 

       PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 1, intent, 0); 

       Notification.Builder builder = new Notification.Builder(MainActivity.this); 

       builder.setAutoCancel(false); 
       builder.setTicker("this is ticker text"); 
       builder.setContentTitle("WhatsApp Notification");    
       builder.setContentText("You have a new message"); 
       builder.setSmallIcon(R.drawable.ic_launcher); 
       builder.setContentIntent(pendingIntent); 
       builder.setOngoing(true); 
       builder.setSubText("This is subtext..."); //API level 16 
       builder.setNumber(100); 
       builder.build(); 

       myNotication = builder.getNotification(); 
       manager.notify(11, myNotication); 

       /* 
       //API level 8 
       Notification myNotification8 = new Notification(R.drawable.ic_launcher, "this is ticker text 8", System.currentTimeMillis()); 

       Intent intent2 = new Intent(MainActivity.this, SecActivity.class); 
       PendingIntent pendingIntent2 = PendingIntent.getActivity(getApplicationContext(), 2, intent2, 0); 
       myNotification8.setLatestEventInfo(getApplicationContext(), "API level 8", "this is api 8 msg", pendingIntent2); 
       manager.notify(11, myNotification8); 
       */ 

      } 
     }); 

     btnClear.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       manager.cancel(11); 
      } 
     }); 
    } 

    private void initialise() { 
     btnShow = (Button) findViewById(R.id.btnShowNotification); 
     btnClear = (Button) findViewById(R.id.btnClearNotification);   
    } 
} 

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" > 

    <Button 
     android:id="@+id/btnShowNotification" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Show Notification" /> 

    <Button 
     android:id="@+id/btnClearNotification" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Clear Notification" /> 

</LinearLayout> 

И деятельность, которая будет открыта щелчку уведомления,

public class SecActivity extends Activity { 

} 
+0

Спасибо так много !! –

+0

Можете ли вы взглянуть на мой вопрос? http://stackoverflow.com/questions/35570767/setlatesteventinfo-method-cannot-be-resolved –

+0

PendingIntent.getActivity (MainActivity.this, 1, intent, 0); в этом методе четвертый параметр предназначен для прохождения флагов. Что это означает, если вы пройдете 0? –

22

Вы пишите у вас есть для использования setLatestEventInfo. Означает ли это, что вы готовы к тому, чтобы ваше приложение не совместимо с более поздними версиями Android? Я настоятельно рекомендую вам использовать support library v4, который содержит класс NotificationCompat для приложения, использующего API 4 и более.

Если вы действительно не хотите использовать библиотеку поддержки (даже с оптимизацией Proguard, использование NotificationCompat добавит хороший 100Ko в конечном приложении), другой способ - использовать отражение. Если вы развертываете приложение на версию Android, которая по-прежнему имеет устаревшие setLatestEventInfo, прежде всего, вы должны проверить, находитесь ли вы в такой среде, а затем используете отражение для доступа к методу.

Таким образом, Android Studio или компилятор не будут жаловаться, поскольку метод доступен во время выполнения, а не во время компиляции. Например:

Notification notification = null; 

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { 
    notification = new Notification(); 
    notification.icon = R.mipmap.ic_launcher; 
    try { 
     Method deprecatedMethod = notification.getClass().getMethod("setLatestEventInfo", Context.class, CharSequence.class, CharSequence.class, PendingIntent.class); 
     deprecatedMethod.invoke(notification, context, contentTitle, null, pendingIntent); 
    } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException 
      | InvocationTargetException e) { 
     Log.w(TAG, "Method not found", e); 
    } 
} else { 
    // Use new API 
    Notification.Builder builder = new Notification.Builder(context) 
      .setContentIntent(pendingIntent) 
      .setSmallIcon(R.mipmap.ic_launcher) 
      .setContentTitle(contentTitle); 
    notification = builder.build(); 
} 
+0

Вы взяли это «нужно» буквально, сладостно за тщательность. ИМО ОП просто прочитал документацию, в которой говорится, что нужно использовать этот метод. Например, [Выполнение службы на переднем плане] (https://developer.android.com/guide/components/services.html#Foreground) по-прежнему содержит ссылку на этот метод. – TWiStErRob

+0

Наконец-то, что работает, поэтому я могу обновить свое приложение с файлами расширения до API 23+. Большое спасибо! –

-2

Перейти к проекту -> свойства и установить андроид-мишень 21

+0

Возможно, это правильно (я не знаю), но вы не намекаете, почему это было бы решением. –

+0

Причина, по которой это работает, заключается в том, что API доступен на Android меньше 23 и устарел, начиная с уровня API 23. – dvallejo

+0

работает как шарм ... perfect –

Смежные вопросы