栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android实训八

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android实训八

实训8   service服务

一、【实训目的】

(1) service的生命周期。

(2) 跨进程调用AIDLserver

二、【实训内容和步骤】

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

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

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

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

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

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

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


    
    

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=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中的代码:




    

    
        
            
                

                
            
        
        
            
                
            
        
        
    

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添加的清单源代码:


            
                
            

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的布局文件源代码:



    

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




    AIDLClient
    Settings
    获取其它应用信息
	国家名为:
 	所在位置为:

运行结果截图:

 

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/820405.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号