Mudasar
Mudasar

Reputation: 249

How to create multi thread in android?

I am new to android and i was doing some application which might use multi threading. For example the application threads might do as follows assuming 2 threads;

Thread 1 Even if the overall application runs on foreground thread one should run at all times listening for specific sms; Imagine the sms to be Intercepted is "3456" when this message is sent to the phone then thread one will be paused and thread 2 will be activated:

Thread 2 When thread to is activated then it will use gps to track the location of the phone and will use instance of smsManager to send back the coordinates(log, lat) of the phone or even if possible google map back to the phone which sent the message "3456" and then thread one will be activated:

**How to make this happen any idea?

Upvotes: 1

Views: 10769

Answers (2)

Rich
Rich

Reputation: 36806

Have a look at Services. A lot of this does not have to be explicitly coded if you make use of Services in your application.

http://developer.android.com/reference/android/app/Service.html

Edit

In response to comments, here's how I do communication from Service to Activity using BroadcastReceiver

public class SomeActivity extends Activity {

BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        // Example of pulling a string out of the Intent's "extras"
        String msg = intent.getStringExtra("BroadcastString");

        // ...more stuff

    }
};


@Override
public void onResume()
{
    super.onResume();
    registerReceiver(receiver, new IntentFilter("SomeStringKeyForMyBroadcast"));

    // ... other stuff
}

@Override
public void onPause()
{
    super.onPause();
    unregisterReceiver(receiver);

    // ... other stuff
}

and in my Service...

public class SomeService extends Service {

Intent broadcastIntent = new Intent("SomeStringKeyForMyBroadcast");

private void someWorkerMethodInMyService()
{
        // ... other stuff

        broadcastIntent.putExtra("BroadcastString", "Some Data");
        sendBroadcast(broadcastIntent);

        // ... other stuff
}

something like that...

Upvotes: 2

Ollie C
Ollie C

Reputation: 28509

There are two answers to this question.

  1. If you want to run a thread in the background over a long period of time, to listen for events or run a regular process then Services are the way to go

  2. If you need to fire off a new thread to do some processing once and then stop, then look at AsyncTask which is a very, very easy way to do that, and includes a simple way to update the user interface during the process.

The developer docs contain an excellent page about location in Android

Here's some information about receiving SMS in your app

Upvotes: 8

Related Questions