2016-02-01 4 views
1

После моего предыдущего вопроса о messaging on javafx,JavaFX Gluon выполнить Вид из андроида деятельности

Я хочу, чтобы уведомить пользователя, когда сообщение прибудет. Недавно я использую NotificationCompat.

Когда пользователь прикасается к уведомлению из панели уведомлений, он должен непосредственно открывать соответствующий вид (DirectMessageView). Я настроил класс активности (NotificationActivy extends Activity) на тег приема в androidmanifest.xml и вызвал DirectMessageView и его презентатор по методу «onCreate».

При нажатии сенсорного сообщения на уведомление он не отображает DirectMessageView, но метод внутри презентатора вызывается, и вид не отображается. Может быть, это моя неправильная реализация, пожалуйста, помогите

Вот классы, которые я создал

Класс SKSAplication, который расширяет MobileAplication

public class SKSApplication extends MobileApplication{ 
    private static SKSApplication instance; 
    public static final String DIRECT_MESSAGE_VIEW = "DIRECT_MESSAGE_VIEW"; 
    public static final String GROUP_MESSAGE_VIEW = "GROUP_MESSAGE_VIEW"; 
private ViewRefresh activeView; 

    public SKSApplication() { 
     instance = this; 
    } 

    public static SKSApplication getInstance() { 
     return instance; 
    } 

@Override 
public void init() { 
    addViewFactory(HOME_VIEW,() -> { 
     HomeView homeView = new HomeView(); 
     homePresenter = (HomePresenter) homeView.getPresenter(); 
     return (View) homeView.getView(); 
    }); 

    addViewFactory(DIRECT_MESSAGE_VIEW,() -> { 
     DirectMessageView directMessageView = new DirectMessageView(); 
     return (View) directMessageView.getView(); 
    }); 

    addViewFactory(GROUP_MESSAGE_VIEW,() -> { 
     GroupMessageView groupMessageView = new GroupMessageView(); 
     return (View) groupMessageView.getView(); 
    }); 

    public void doRefreshMessageUI(Object objectModel) { 
    System.out.println("SKSApplication.doRefreshMessageUI " + getView().getName()); 
    if (getActiveView() != null) 
     getActiveView().doRefresh(objectModel); 
} 

public ViewRefresh getActiveView() { 
    return activeView; 
} 

public void setActiveView(ViewRefresh activeView) { 
    this.activeView = activeView; 
} 
} 

Класс MyGCMListenerService

public class MyGCMListenerService extends GcmListenerService { 
private final String NOTIFICATION_TAG = "NotificationExample"; 

public MyGCMListenerService() { 
} 

@Override 
public void onMessageReceived(String from, Bundle data) { 
String varMessage = data.getString("message"); 
    try { 
     JSONObject json = new JSONObject(varMessage); 

     String messageContent = getStringFromJSON(json, "message"); 
     Integer senderId = getIntegerFromJSON(json, "senderId"); 
     String senderName = getStringFromJSON(json, "senderName"); 
     String comId = getStringFromJSON(json, "communityId"); 
     String salesGroup = getStringFromJSON(json, "salesGroup"); 
     Integer messageType = getIntegerFromJSON(json, "type"); 

     doViewNotification(messageType, senderName, salesGroup); 
    SKSApplication.getInstance().doRefreshMessageUI(messageContent,senderId,senderName,comId); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
} 

private void doViewNotification(Integer messageType, String senderName, String salesGroup) { 
    StringBuilder msg = new StringBuilder() 
      .append("Message from ") 
      .append(senderName) 
      .append(" @").append(salesGroup); 


    Intent resultIntent = new Intent(FXActivity.getInstance(), NotificationActivity.class); 
    resultIntent.putExtra(Constants.EXTRA_INTENT.MESSAGE_TYPE.getValue(), messageType); 

    PendingIntent resultPendingIntent = 
      PendingIntent.getActivity(
        FXActivity.getInstance(), 
        0, 
        resultIntent, 
        PendingIntent.FLAG_UPDATE_CURRENT 
      ); 

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

    long[] v = {500, 1000}; 


    NotificationCompat.Builder builder = 
      new NotificationCompat.Builder(this) 
        .setSound(uri) 
        .setSmallIcon(FXActivity.getInstance().getApplicationInfo().icon) 
        .setContentTitle(getApplicationName(FXActivity.getInstance().getApplicationContext())) 
        .setVibrate(v) 
        .setContentText(msg.toString()) 
        .setPriority(Notification.PRIORITY_DEFAULT) 
        .setNumber(100) 
        .setWhen(System.currentTimeMillis()) 
        .setContentIntent(resultPendingIntent) 
        .setAutoCancel(true) 
        .addAction(FXActivity.getInstance().getApplicationInfo().icon, "Action", null); 

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { 
     notificationManager.notify(NOTIFICATION_TAG, 0, builder.build()); 
    } else { 
     notificationManager.notify(NOTIFICATION_TAG.hashCode(), builder.build()); 
    } 

} 
} 

раскладку XML-файл (directmessage.fxml)

<View xmlns:fx="http://javafx.com/fxml/1" fx:id="directMessageView" prefHeight="600.0" prefWidth="400.0" 
    xmlns="http://javafx.com/javafx/8.0.40" 
    fx:controller="com.tenma.mobile.message.directmessage.DirectMessagePresenter"> 
</View> 

Класс DirectMessageView

public class DirectMessageView extends FXMLView { 
} 

Класс DirectMessagePresenter

public class DirectMessagePresenter implements Initializable, ViewRefresh{ 
    @Override 
public void initialize(URL location, ResourceBundle resources) { 
    { 
     directMessageView.showingProperty().addListener((observable, oldValue, newValue) -> { 
     if (newValue) { 
      SKSApplication.getInstance().setActiveView(this); 
      doViewMessage(); 
     } 
    }); 
    } 

    private void doViewMessage() { 
    listMessage.getItems().clear(); 

    MessageStoryHelper hlp = new MessageStoryHelper(); 
    List<MessageModel> ls = null; 
    try { 
     ls = hlp.getMessages(Constants.MESSAGE_TYPE.DIRECT); 
    if (ls != null && ls.size() != 0) 
     for (MessageModel m :ls) 
      listMessage.add(m); 

    } catch (SQLException e) { 
     e.printStackTrace(); 
    } 

} 
} 

androidmanifest

<?xml version="1.0" encoding="UTF-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tenma.mobile" 
     android:versionCode="1" android:versionName="1.0"> 
<supports-screens android:xlargeScreens="true"/> 
<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

<uses-permission android:name="android.permission.VIBRATE"/> 
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/> 
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/> 
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/> 

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

<permission android:name="com.tenma.mobile.permission.C2D_MESSAGE" 
      android:protectionLevel="signature"/> 
<uses-permission android:name="com.tenma.mobile.permission.C2D_MESSAGE"/> 

<application android:label="MobileSales" android:name="android.support.multidex.MultiDexApplication" 
      android:icon="@mipmap/ic_launcher"> 
    <activity android:name="javafxports.android.FXActivity" android:label="MobileSales" 
       android:configChanges="orientation|screenSize"> 
     <meta-data android:name="main.class" android:value="com.tenma.mobile.SKSApplication"/> 
     <meta-data android:name="debug.port" android:value="0"/> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN"/> 
      <category android:name="android.intent.category.LAUNCHER"/> 
     </intent-filter> 
    </activity> 

    <activity 
      android:name="com.tenma.mobile.common.NotificationActivity" 
      android:parentActivityName="javafxports.android.FXActivity"> 
     <meta-data 
       android:name="android.support.PARENT_ACTIVITY" 
       android:value="javafxports.android.FXActivity"/> 
    </activity> 

    <!--start--> 
    <receiver 
      android:name="com.google.android.gms.gcm.GcmReceiver" 
      android:permission="com.google.android.c2dm.permission.SEND"> 
     <intent-filter> 
      <action android:name="com.google.android.c2dm.intent.RECEIVE"/> 
      <!-- for Gingerbread GSF backward compat --> 
      <!--<action android:name="com.google.android.c2dm.intent.REGISTRATION"/>--> 
      <category android:name="com.tenma.mobile"/> 
     </intent-filter> 
    </receiver> 
    <!--end--> 

    <service 
      android:name="com.tenma.mobile.common.MyGCMListenerService" 
      android:exported="false"> 
     <intent-filter> 
      <action android:name="com.google.android.c2dm.intent.RECEIVE"/> 
     </intent-filter> 
    </service> 
</application> 
    </manifest> 

Класс NotificationActivity расширяет активность

public class NotificationActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    Intent launchIntent = getIntent(); 

он работает, но без вида не виден

SKSApplication.getInstance().switchView(SKSApplication.DIRECT_MESSAGE_VIEW); 

возможно, используя эту строку ниже, но как установить ГЛЮОН View setContentView? или идентификатор Retreive view и setContentView?

DirectMessageView directMessageView = new DirectMessageView(); 
       Parent v = directMessageView.getView(); 
       FXActivity.getInstance().setContentView(?????????); 
     } 
} 

Любая помощь будет оценена

Спасибо заранее

+0

Возможный дубликат - http://stackoverflow.com/questions/24987787/open-activity-when-gcm-notification-was-clicked – adjuremods

+0

Спасибо, мне нужно позвонить Gluon вид внутри Android активность после NotificationActivity является инициализируется. На активность Android есть setContentView. но я еще не знаю, как заставить Gluon View включить установку android setContentView. Perhap Я пропустил некоторую реализацию –

+0

Я нашел, что вы можете установитьContentView следующим образом: 'FXActivity.getInstance(). SetContentView (R.layout.defaultlayout);' Я скопировал файл макета из проекта eclipse для Android в проект javafxports eclipse в папку res/layout в папках проекта. –

ответ

0

Если у вас есть работающее приложение, это работает для меня:

После отправки сообщения обратно в View, вам необходимо закрыть деятельность по уведомлению, позвонив по телефону finish():

public class NotificationActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     ((SKSApplication) MobileApplication.getInstance()).doRefreshMessageUI("Hi from NotificationActivity"); 

     finish(); 
    } 

} 

Обратите внимание, что вам не нужно создавать одноэлементный экземпляр SKSApplication, вы можете получить его экземпляр в любое время, вызвав MobileApplication.getInstance().

Передача сообщения в виде может быть выполнена в SKSApplication с использованием Platform.runLater(), так как вы не работаете в потоке JavaFX.

и получить соответствующий вид, просто переключиться на эту точку зрения:

public void doRefreshMessageUI(String msg) { 
    Platform.runLater(() -> { 
     messagesView.messageProperty().set(msg); 
     switchView(DIRECT_MESSAGE_VIEW); 
    }); 
} 

обеспечивая вид имеет StringProperty, который связан с какой-либо из его управления текстового свойства.

private StringProperty message = new SimpleStringProperty(); 

public StringProperty messageProperty() { 
    return message; 
}