Android Messenger应用程序使用服务

时间:2014-06-29 09:28:08

标签: android web-services broadcastreceiver android-service android-broadcast

我想为Android设备实现一个简单的messenger应用程序,我正在使用一个Web服务,其中包含发送和接收所需的所有方法(通过按下发送按钮,记录将被插入数据库并通过调用接收方法检索与此接收者(用户)相关的所有行。

我在一个单独的类和onStart()中编写了一个服务,我检查了我的.Net Web服务的接收方法,我在我的活动的onCreate()中启动服务,所以服务在后台,完全接收传入的消息,我可以直接在我的服务代码中使用Toast显示新消息,但我知道,为了访问我活动中的视图,我应该使用pendingintent,也许是BroadcastReceiver,所以我可以添加新的消息到我活动的主屏幕(例如textview)。 现在我想找到一种方法来访问我的活动的textview并通过我的服务或其他任何东西设置它的文本... 请帮我解决这个问题, 这是我的活动:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MyOwnActivity extends Activity
{
    Button btnSend;
    Button btnExtra;
    EditText txtMessageBody;
    TextView lblMessages;
    BerryService BS = new BerryService();
    public  void SetMessageHistory(String value)
    {
        txtMessageBody.setText(value);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnSend = (Button) findViewById(R.id.btnSend);
        btnExtra = (Button) findViewById(R.id.btnExtraIntent);
        txtMessageBody = (EditText) findViewById(R.id.txtMessageBody);
        lblMessages = (TextView) findViewById(R.id.lblMessages);



        /////////

        //////////
        startService(new Intent(this, IncomingMessageService.class));

        btnSend.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // call webservice method to send

                BS.SetSoapAction("http://tempuri.org/Send");
                BS.SetMethodName("Send");
                String a = BS.SendMessage(txtMessageBody.getText().toString());
                lblMessages.setText(lblMessages.getText().toString() + "\n"
                        + txtMessageBody.getText().toString());
                txtMessageBody.setText("");

            }
        });
    }

}

这是我的服务:

import java.util.Timer;
import java.util.TimerTask;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.widget.Toast;

public class IncomingMessageService extends Service
{
    private static final int NOTIFY_ME_ID = 12;


    BerryService BS = new BerryService();
    String text = "";

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Bind Failed");
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "onCreate", 5000).show();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // ////////////////////////

        Toast.makeText(this, "onStart   ", 1000).show();
        // Timer Tick
        final Handler handler = new Handler();
        Timer _t = new Timer();
        TimerTask tt = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {

                        Toast.makeText(getApplicationContext(), "tick   ", 1000)
                                .show();
                        // here the receive method should be called
                        BS.SetSoapAction("http://tempuri.org/RecieveMessage");
                        BS.SetMethodName("RecieveMessage");
                        String receivedMsg = BS.ReceiveMessage("sh");
                        //Instead of toast I want to access the textview in my activity!!!!!
                        Toast.makeText(getApplicationContext(), receivedMsg, 5000).show();






                    }
                });
            }
        };
        _t.scheduleAtFixedRate(tt, 0, 1000);

    }



    // /
    @Override
    public void onDestroy() {

        Toast.makeText(this, "onDestroy", 5000).show();
    }
}

3 个答案:

答案 0 :(得分:2)

您需要了解广播的概念,在您的情况下,它是正确的解决方案。

在其活动中开始广播

public static final String ACTION = "com.yourapp.ACTION.TEXT_RECEIVED";
private BroadcastReceiver mReceiver;

@Override
public void onCreate(Bundle savedInstanceState) {
    ////////

     mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
           String msg = intent.getStringExtra("msg");
           yourTextView.setText(msg);
        }
     };

     IntentFilter filter = new IntentFilter(ACTION);
     filter.addCategory(Intent.CATEGORY_DEFAULT);
     registerReceiver(mReceiver, filter);


    ////////
}

protected void onDestroy() {
    // remember to unregister the receiver
    super.onDestroy();
    if (mReceiver != null) {
        unregisterReceiver(mReceiver);
    }
}

当您需要发送服务信息时,您应该使用:

Intent i = new Intent();
i.setAction(MyOwnActivity.ACTION);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.putExtra("msg", "the message received by webservice");
i.putExtras(b);

sendBroadcast(i);

看看这里:http://developer.android.com/reference/android/content/BroadcastReceiver.html

答案 1 :(得分:0)

为什么让自己变得复杂。使用此库https://parse.com/docs/android_guide#top 你很高兴:)

答案 2 :(得分:0)

使用广播管理器很棒,但我个人更喜欢使用square的Otto,因为在Android应用程序中组件之间进行通信非常容易。

http://square.github.io/otto/

如果你选择使用otto,你将不得不覆盖Bus的post方法,以便能够将消息发送到前台的总线。这是代码:

public class MainThreadBus extends Bus {
    private final Handler handler = new Handler(Looper.getMainLooper());

    @Override public void post(final Object event) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            super.post(event);
        } else {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    post(event);
                }
            });
        }
    }
}