本文介绍: 实训8 service服务一、【实训目的】(1) service生命周期。(2) 跨进程调用AIDLserver二、【实训内容步骤】1、按下图一个布局管理使用Service原理实现以下按键功能单击启动Service启动一个后台service,依次输出素数(时间间隔1秒);单击“停止Service”,停止后台service服务单击绑定Service”,绑定后台service服务,依次输出素数(时间间隔1秒)…

实训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" /&gt;
    
    <Button
        android:id="@+id/bind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bind" /&gt;

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

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

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>

运行结果截图:

 

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

原文地址:https://blog.csdn.net/weixin_47077788/article/details/124327947

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_11257.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注