2015-11-07 4 views
0

Я только начал с Java и Android-кодирования. Я написал заявку на научное обучение в своем университете. Приложение предназначено для местной выставки музея. У меня разные места в моем городе, каждое место со своей выставкой.iBeacon Monitoring с классом приложения

Теперь я сделал операцию для каждого из местоположений, чтобы пользователь мог увидеть полезную информацию об образце. Теперь я хочу объединить приложение с iBeacons, я купил 6 маяков из Estimote. Я хочу, чтобы приложение давало пользователю уведомление с текстом вроде: «Вы находитесь перед объектом XY. Нажмите, чтобы увидеть дополнительную информацию». После прослушивания уведомления пользователь должен открыть конкретную деятельность, которую я создал. Я также хочу, чтобы приложение искало маяки в фоновом режиме, поэтому, если пользователь приблизится к местоположению, он автоматически получает уведомление через несколько секунд.

Теперь я хочу, чтобы приложение работало в фоновом режиме. В настоящий момент пользователь получает уведомления только в том случае, когда приложение находится на переднем плане. Я взял пример Estimote и немного изменил его.

Я уже прочитал в другом потоке, что я должен держать BeaconManager в классе приложения. Но как я должен это делать. Когда я пытаюсь скопировать код, связанный радиомаяка в новый класс, который я начинаю с

public void BeaconMain extends Application{ 

, но затем я получаю много ошибок, и я не могу исправить их. Не могли бы вы мне помочь? Вот мой код до сих пор:

public class MainActivity extends ActionBarActivity 
{ 

    private static final int NOTIFICATION_ID = 123; 

    private BeaconManager beaconManager; 
    private NotificationManager notificationManager; 
    private Region mariendom; 
    private Region andreasplatz; 
    private boolean entered = false; 



    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     Beacon beacon = getIntent().getParcelableExtra("extrasBeacon"); 


     andreasplatz = new Region("andreasplatz", "B9407F30-F5F8-466E-AFF9-25556B57FE6D", 31134, 3); 
     mariendom = new Region("mariendom", "B9407F30-F5F8-466E-AFF9-25556B57FE6D", 31134, 2); 

     notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     beaconManager = new BeaconManager(this); 



     beaconManager.setBackgroundScanPeriod(500, 1000); 

     beaconManager.setMonitoringListener(new BeaconManager.MonitoringListener() 
     { 
      @Override 
      public void onEnteredRegion(Region region, List<Beacon> beacons) 
      { 

       if(region.getMinor().equals(2)){ 
        postNotification("Sie sind am Mariendom"); 
        Log.d("Estiomote", "Entered region"); 
       } 

       else if(region.getMinor().equals(3)){ 
        postNotification2("Sie sind am Andreasplatz"); 
        Log.d("Estiomote", "Entered region"); 
       } 

      } 

      @Override 
      public void onExitedRegion(Region region) 
      { 
       /*entered = false; 
       postNotification("Sie haben den Mariendom verlassen"); 
       Log.d("Estiomote", "Exited region");*/ 
      } 

    @Override 
    protected void onResume() 
    { 
     super.onResume(); 

     notificationManager.cancel(NOTIFICATION_ID); 
     beaconManager.connect(new BeaconManager.ServiceReadyCallback() 
     { 
      @Override 
      public void onServiceReady() 
      { 
       try { 
        Log.d("Estiomote", "Start monitoring"); 

        beaconManager.startMonitoring(andreasplatz); 
        beaconManager.startMonitoring(mariendom); 

       } catch (RemoteException e) 
       { 
        Log.d("Estiomote", "Error while starting monitoring"); 
       } 
      } 
     }); 
    } 
    @Override 
    protected void onDestroy() 
    { 
     notificationManager.cancel(NOTIFICATION_ID); 
     beaconManager.disconnect(); 
     super.onDestroy(); 
    } 

    private void postNotification(String msg) 
    { 
     Intent notifyIntent = new Intent("com.example.walter.him.mariendom"); 
     notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivities(
       MainActivity.this, 
       0, 
       new Intent[]{notifyIntent}, 
       PendingIntent.FLAG_UPDATE_CURRENT); 
     Notification notification = new Notification.Builder(MainActivity.this) 
       .setSmallIcon(R.drawable.ic_launcher) 
       .setContentTitle("HiM - Hildesheim im Mittelalter") 
       .setContentText(msg) 
       .setAutoCancel(true) 
       .setContentIntent(pendingIntent) 
       .build(); 
     notification.defaults |= Notification.DEFAULT_SOUND; 
     notification.defaults |= Notification.DEFAULT_VIBRATE; 
     notification.defaults |= Notification.DEFAULT_LIGHTS; 
     notificationManager.notify(NOTIFICATION_ID, notification); 

    } 

    private void postNotification2(String msg) 
    { 
     //Intent notifyIntent = new Intent(MainActivity.this, MainActivity.class); 
     Intent notifyIntent = new Intent("com.example.walter.him.andreasplatz"); 
     notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivities(
       MainActivity.this, 
       0, 
       new Intent[]{notifyIntent}, 
       PendingIntent.FLAG_UPDATE_CURRENT); 
     Notification notification = new Notification.Builder(MainActivity.this) 
       .setSmallIcon(R.drawable.ic_launcher) 
       .setContentTitle("HiM - Hildesheim im Mittelalter") 
       .setContentText(msg) 
       .setAutoCancel(true) 
       .setContentIntent(pendingIntent) 
       .build(); 
     notification.defaults |= Notification.DEFAULT_SOUND; 
     notification.defaults |= Notification.DEFAULT_LIGHTS; 
     notification.defaults |= Notification.DEFAULT_VIBRATE; 
     notificationManager.notify(NOTIFICATION_ID, notification); 

    } 


} 

ответ

0

Я предлагаю вам начать с нуля научиться ставить BeaconManager в класс Application, а не копировать-наклеивать код, который был в деятельности в Заявке, как есть некоторые различия между этими двумя подходами.

Лучшее место, чтобы начать с учебника, чтобы собрать некоторые фундаментальные понятия и общее понимание:

http://developer.estimote.com/android/tutorial/part-1-setting-up/

И есть также Notification пример, который вы можете создать с помощью Estimote Cloud:

https://cloud.estimote.com/#/apps/add/notification

Как только вы узнаете, как интегрировать BeaconManager в класс Application, должно быть довольно просто изменить onEntered/Exi чтобы вызвать различные действия, основанные на том, какой маяк вы вошли в диапазон.

Это тот порядок, который я предлагаю следовать.


Полное раскрытие: я работаю Advocate Developer в Estimote.