java - 从正在运行的服务更新 Activity UI

标签 java android android-service

我目前有一个正在运行的服务,每次其他用户向某人发送消息时,该服务都会从套接字接收消息。现在,在 Activity 中,我可以轻松调用一个对话框来显示已收到消息的通知,但我想从正在运行的服务中执行此操作。我该如何解决这个问题?

这是我正在运行的服务。

public class MyService extends Service implements ChatCallbackAdapter {

    public StartSocket connect;
    public static Context mContent;
    private ConnectSocket connectsocket;
    final Context context = this;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

     @Override
     public void onStart(Intent intent, int startId) {
        System.out.println("Service is running");
        connectsocket= new ConnectSocket(this);
        connectsocket.start();
        connect=new StartSocket();
    }

    public void startNotification(){
        Intent intent = new Intent(this, ReceiveNotification.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

        // Build notification
        // Actions are just fake
        Notification noti = new Notification.Builder(this)
            .setContentTitle("Received a message")
            .setContentText("Subject").setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent)
            .addAction(R.drawable.ic_launcher, "Rply", pIntent)
            .build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // Hide the notification after its selected
        noti.flags |= Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(0, noti);
    }

    @Override
    public void callback(JSONArray data) throws JSONException {
        // TODO Auto-generated method stub

    }

    @Override
    public void on(String event, JSONObject data) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onMessage(String message) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onMessage(JSONObject json) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnect() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onDisconnect() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnectFailure() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onMessageReceived(Message m) {
        // TODO Auto-generated method stub
        System.out.println("Received a message in service");
        if(m.status.equals("ready")){
            connectsocket.login(SaveSharedPreference.getUserName(getApplicationContext()), SaveSharedPreference.getUserId(getApplicationContext()));
            connectsocket.subscribe();
        }
        if(m.status.equals("message")){
            //getMsg(m.msg, m.name);
            startNotification();
            System.out.println("Received a message "+m.msg+" and a name "+m.name);
            final String name=m.name;
            final String pid=m.pid;
            final String msg=m.msg;

            //Intent intenter=new Intent(TabExercise.this, CreateNotification.class);
            //startActivity(intenter);

            //runOnUiThread(new Runnable(){

            //public void run(){
            //Handler handler = new Handler(Looper.getMainLooper());

             AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    context);
             alertDialogBuilder.setTitle(name+" just sent you a message");
             alertDialogBuilder.setMessage("Click yes to go to the message");
             alertDialogBuilder

                .setCancelable(false)
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        Intent inte=new Intent(MyService.this, Chat.class);
                        Bundle extras=new Bundle();
                        extras.putString("name", name);
                        extras.putString("pid", pid);
                        extras.putString("msg", msg);
                        inte.putExtras(extras);
                        startActivity(inte);

                        dialog.cancel();
                    }
                  })
                .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
            //}
            //});

        }
    }

}

最佳答案

您有 2 个选择:

  1. 按照文档 here 中的说明使用 Messenger 模式.

  2. 使用LocalBroadcastManager从服务发出广播,并使目标 Activity 执行 BroadcastReceiver收听该广播。

Messenger 的一个优点是服务可以选择通知其所有客户端的某个特定Messenger。

关于java - 从正在运行的服务更新 Activity UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17851782/

相关文章:

background - Whatsapp 或电报等应用程序如何监听 Android 上的来电/消息事件?

java - Mapview 顶部的另一个片段(SupportMapFragment)

java - 从json数组中读取数据

java - 字符串替换android?

android - 运行此代码时出现 NullPointerException

android - 在 MediaPlayer App 中播放音乐的服务或 Activity

Java:在这种特殊情况下如何处理ConcurrentModificationException?

c# - 如何读取FoxPro启动文件数据文件(文件扩展名.FPM)

android - 无法在 HttpLoggingInterceptor Retrofit 2.0 上解析 setLevel

android - 已收到 GCM 消息但未显示 - 广播接收器结果=已取消 - 服务强制停止