user1831490
user1831490

Reputation:

Android Messenger Application using services

I want to implement a simple messenger application for Android devices,I'm working with a web service which contains all the required methods for sending and receiving(by pressing the send button a record will be inserted in the DB and by calling the receive method all the rows related to this receiver(user) are retrieved).

I've written a service in a separate class and in onStart() I check the receive method of my .Net web service,I start the service in onCreate() of my activity ,so the service is in the background and receives the incoming messages perfectly,I can show the new message by using a toast directly in my service code,but I know that for accessing the views which are in my activity I should use pendingintent and maybe a BroadcastReceiver,so I can add the new messages to the main screen of my activity(for example a textview). Now I want to find a way to access the textview of my activity and set the text of it through my service or anything else... please help me on this issue, Here is my activity:

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("");

            }
        });
    }

}

Here is my service:

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();
    }
}

Upvotes: 1

Views: 510

Answers (2)

Andre Perkins
Andre Perkins

Reputation: 7800

Using a broadcast manager is great but I personally prefer to use square's Otto because it is just so easy to perform communication between components in an android application.

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

If you do choose to use otto, you are going to have to override the Bus's post method to be able to talk post messages to a bus on the foreground. Here is the code for that:

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);
                }
            });
        }
    }
}

Upvotes: 0

Eduardo Lagares
Eduardo Lagares

Reputation: 116

You need to understand the concept of Broadcast, in your case it is the correct solution.

Start Broadcast in its activity

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);
    }
}

When you need to send the message of service you should use:

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);

Have a look here: http://developer.android.com/reference/android/content/BroadcastReceiver.html

Upvotes: 2

Related Questions