Communicate Between A Service And An Activity

Description

The following code shows how to Communicate Between A Service And An Activity.

Example

Populate the MyService.java file with the following code:


package com.java2s.myapplication3.app;
/*w w  w .j av  a 2s  .c  o  m*/
import java.net.MalformedURLException;
import java.net.URL;

import android.app.IntentService;
import android.content.Intent;
public class MyService extends IntentService {

    public MyService() {
        super ("MyService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            int result = DownloadFile(new URL("http://www.your server.com/somefile.pdf"));
            //send a broadcast to inform the activity
            //that the file has been downloaded
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");
            getBaseContext().sendBroadcast(broadcastIntent);

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

    private int DownloadFile(URL url) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 100;
    }
}

In the AndroidManifest.xml file, add the following statement:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.Services"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="14" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
         android:label="@string/app_name"
         android:name=".ServicesActivity" >
         <intent-filter >
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
     <service android:name=".MyService" />
 </application>

</manifest>

Main layout xml file


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Service"
    android:onClick="startService"/>

<Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stop Service"
    android:onClick="stopService" />

</LinearLayout>

Main Activity Java code


package com.java2s.myapplication3.app;
//from ww w .j a v a  2 s  .  c  o m

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
    IntentFilter intentFilter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onResume() {
        super.onResume();
        //intent to filter for file downloaded intent
        intentFilter = new IntentFilter();
        intentFilter.addAction("FILE_DOWNLOADED_ACTION");

        //register the receiver
        registerReceiver(intentReceiver, intentFilter);
    }

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

        //unregister the receiver
        unregisterReceiver(intentReceiver);
    }

    public void startService(View view) {
        startService(new Intent(getBaseContext(), MyService.class));
    }

    public void stopService(View view) {
        stopService(new Intent(getBaseContext(), MyService.class));
    }

    private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText (getBaseContext(), "File downloaded!",
                    Toast.LENGTH_LONG).show();
        }
    };

}

Note

Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.





















Home »
  Android »
    Android Basics »




Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS