Android实训八

实训8   service服务

一、【实训目的】

(1) service的生命周期。

(2) 跨进程调用AIDLserver

二、【实训内容和步骤】

1、按下图写一个布局管理,使用Service原理并实现以下按键功能,

        单击“启动Service”启动一个后台service,依次输出素数(时间间隔1秒);

        单击“停止Service”,停止后台service服务;

        单击“绑定Service”,绑定后台service服务,依次输出素数(时间间隔1秒);

        单击“解绑Service”,解除绑定后台service服务;

        单击“获取数据”,用弹出框显示当前service多线程运行到的最后一个素数。

1)写出Activity_main.xml中的代码: 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/start" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/stop" />
    
    <Button
        android:id="@+id/bind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bind" />

    <Button
        android:id="@+id/unbind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/unbind" />

    <Button
        android:id="@+id/getData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/getData" />
    
</LinearLayout>

2)写出Activity_main.xml中的代码:

import com.example.oldbaby.MyService.MyBinder;

import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
	private Button start, stop,bind,unbind,getData;
    private MyBinder myBinder;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		start = (Button) findViewById(R.id.start);
		stop = (Button) findViewById(R.id.stop);
		bind= (Button)findViewById(R.id.bind);
		unbind= (Button)findViewById(R.id.unbind);
		getData=(Button)findViewById(R.id.getData);
		final Intent intent =new Intent();
		intent.setAction("com.example.oldbaby.MyService");
		start.setOnClickListener(new OnClickListener() {	
			public void onClick(View v) {
				// TODO Auto-generated method stub
			startService(intent);
			}
		});
		stop.setOnClickListener(new OnClickListener() {	
			public void onClick(View v) {
				// TODO Auto-generated method stub
			stopService(intent);
			}
		});
		bind.setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View v) {	
				// TODO Auto-generated method stub
				bindService(intent, conn, BIND_AUTO_CREATE);
			}
		});
		unbind.setOnClickListener(new OnClickListener() {		
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				unbindService(conn);
			}
		});
		getData.setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//弹出提示信息框类Toast的静态成员方法makeText
				Toast.makeText(MainActivity.this, "获取到的数据为:"+myBinder.getCount(), Toast.LENGTH_LONG).show();
			}
		});
	}
     private ServiceConnection conn=new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			System.out.println("ServiceConnection's onServiceDisconnected invoked!");
		}
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			System.out.println("ServiceConnection's onServiceConnected invoked!");
		    myBinder=(MyBinder)service;
		}
	};   
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}

3)写出MyService.java中的代码:

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class MyService extends Service {
	private int count=0;
	private boolean flag=true;
	private MyBinder myBinder = new MyBinder();
	public class MyBinder extends Binder {
		public MyBinder() {
			System.out.println("MyBinder's constructor invoked!");
		}
		public int getCount(){
			return count;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		System.out.println("服务已经绑定!");
		return myBinder;
	}
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		System.out.println("后台进程创建!");
		new Thread() {
			public void run() {
				int i,j;
				int k=0,q=0;
				int[] s=new int[100];
				
					for(i=2;i<100;i++)
					{	boolean haha=true;
						for(j=2;j<i;j++)
						{
							if(i%j==0)
							{		haha=false;
									break;
							}
						}	
						if(haha)
						{
							s[k]=i;
							k++;
							if(k>=s.length)
							{
								break;
							}
						}
					}
				
				while (flag) {
					try {
						Thread.sleep(500);
						q++;
						count=s[q];
						System.out.println("count="+s[q]);
					} catch (Exception ex) {
						ex.printStackTrace();
						// TODO: handle exception
					}
				}
			}
		}.start();
		super.onCreate();
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		System.out.println("后台进程启动!");
		return super.onStartCommand(intent, flags, startId);
	}
	@Override
	public boolean onUnbind(Intent intent) {
		System.out.println("后台进程解绑!");
		return super.onUnbind(intent);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		System.out.println("后台进程结束!");
		flag=false;
		super.onDestroy();
	}
}

4)写出AndroidManifest.xml中的代码:

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.oldbaby.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

5)运行结果截图:

 2、按下图写一个布局管理,使用AIDLserver原理并实现以下按键功能,

 单击“获取信息”按钮,可以随机生成国家和对应的位置。国家和位置信息如下:

private String[] country = new String[] { "中国", "美国", "法国", "澳大利亚" };

private String[] positions = new String[] { "亚洲", "美洲", "欧洲", "澳洲" };

请完整的写出步骤:

1)写出AIDLServer的MyServer.java源代码:

import java.util.Random;

import iet.jxufe.cn.server.Song.Stub;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

public class MyService extends Service {
	private String[] country = new String[] { "中国", "美国", "法国", "澳大利亚"};
	private String[] positions = new String[] {"亚洲", "美洲", "欧洲", "澳洲" };
	private boolean flag = true;
	private String theCountry;
	private String thePosition;
	private SongBinder songBinder = new SongBinder();

	public class SongBinder extends Stub {
		public String getName() throws RemoteException {
			return theCountry;
		}

		public String getAuthor() throws RemoteException {
			return thePosition;
		}
	}

	public void onCreate() {
		new Thread() {
			public void run() {
				while (flag) {
					try {
						Thread.sleep(500);
						Random rand = new Random();//随机数
						int index = rand.nextInt(4);
						theCountry=country[index];
						thePosition=positions[index];
						System.out.println("国家名为:" +theCountry );
						System.out.println("所在位置为:" +thePosition);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}.start();
		super.onCreate();
	}

	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return songBinder;
	}

	public void onDestroy() {
		flag = false;
		super.onDestroy();
	}

}

2)写出Song.aidl源代码:

package iet.jxufe.cn.server;
interface Song{
  String getName();
  String getAuthor();
}

3)写出AIDLServer添加的清单源代码:

<service android:name=".MyService">
            <intent-filter >
                <action android:name="iet.jxufe.cn.server.MyService"/>
            </intent-filter>
</service>

4)写出AIDLClient的MainActivity.java源代码:

import iet.jxufe.cn.server.Song;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;


public class MainActivity extends Activity {

	private Button getData;
	private EditText country, positions;
	private Song songBinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getData = (Button) findViewById(R.id.getData);
        country = (EditText) findViewById(R.id.country);
		positions = (EditText) findViewById(R.id.position);
		final Intent intent = new Intent();
		intent.setAction("iet.jxufe.cn.server.MyService");
		getData.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try {
					bindService(intent, conn, Service.BIND_AUTO_CREATE);
					country.setText(songBinder.getName());
					positions.setText(songBinder.getAuthor());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
    }

    public ServiceConnection conn = new ServiceConnection() {
		public void onServiceDisconnected(ComponentName name) {

		}

		public void onServiceConnected(ComponentName name, IBinder service) {
			songBinder = Song.Stub.asInterface(service);
		}
	};

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}

5)写出AIDLClient的布局文件源代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="20dp"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/getData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/getData"
        android:textSize="20sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/country"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/country"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:enabled="false"
            android:textColor="#ff0000"
            android:textSize="20sp" >
        </EditText>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/positions"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/position"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:enabled="false"
            android:textColor="#ff0000"
            android:textSize="20sp" >
        </EditText>
    </LinearLayout>

</LinearLayout>

6) 写出AIDLClient的String.xml源代码:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">AIDLClient</string>
    <string name="action_settings">Settings</string>
    <string name="getData">获取其它应用信息</string>
	<string name="country">国家名为:</string>
 	<string name="positions">所在位置为:</string>

</resources>

运行结果截图:

 

 附注:该专栏是博主上学时的实训项目,可供访客练习与参考。代码质量不是很好,但能实现,仅供参考!  

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值