Android中进程process间通信的实现方式

1. Intent; 

2. Binder(AIDL); 

3. Message; 

4. BroadcastReceiver.

Demo

1. Intent:

AndroidManifest.xml


   
   

   
   
   
    
    
   
    
    
       
     
     
           
      
      
                
       
       
 
                
       
       
           
      
      
        
     
     
       
     
     
           
      
      
                
       
       
 
                
       
       
           
      
      
       
     
     
       
     
     
           
      
      
                
       
       
                
       
       
                
       
       
                
       
       
                
       
       
           
      
      
       
     
     
   
    
    

   
   

activity_main.xml


   
   

   
   
 
   
    
    
 
   
    
    
 
   
    
    
 
   
    
    
 
   
    
    

   
   

activity_01.xml


   
   

   
   
   
    
    

   
   

activity_share.xml


   
   

   
   
 
   
    
    
 
   
    
    

   
   

intentdemo\src\main\java\com\xyy\intentdemo

MainActivity.java

package com.xyy.intentdemo;
 
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
importandroid.support.v7.app.AppCompatActivity;
import android.view.View;
import java.io.File;
 
public class MainActivity extendsAppCompatActivity implements View.OnClickListener {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       findViewById(R.id.btn_1).setOnClickListener(this);
       findViewById(R.id.btn_2).setOnClickListener(this);
       findViewById(R.id.btn_3).setOnClickListener(this);
       findViewById(R.id.btn_4).setOnClickListener(this);
    }
 
   @Override
   public void onClick(View view) {
       switch (view.getId()) {
           case R.id.btn_1:
                Intent it = new Intent();
                //通过组件名这个内容来配置Intent的目标
//                ComponentName cn = newComponentName(MainActivity.this,Activity01.class);
                ComponentName cn = newComponentName(MainActivity.this,"com.xyy.intentdemo" +
                       ".Activity01");
                it.setComponent(cn);
                startActivity(it);
               break;
           case R.id.btn_2:
                Intent it1 = new Intent();
                ComponentName cn1 = newComponentName("com.xyy.webviewdemo","com.xyy.webviewdemo" +
                       ".MainActivity");
                it1.setComponent(cn1);
                startActivity(it1);
                break;
           case R.id.btn_3:
                Intent it3 = newIntent("abc123");
//               it3.setAction("abc123");
                startActivity(it3);
                break;
           case R.id.btn_4:
                Intent shareIntent = newIntent(Intent.ACTION_SEND);
               shareIntent.putExtra(Intent.EXTRA_TEXT,"Hello World");
                //配置要找系统中能发送文本的Activity
//               shareIntent.setType("text/plain");
                Uri uri = Uri.fromFile(newFile("/mnt/sdcard/temp.jpg"));
               shareIntent.setDataAndType(uri,"image/jpeg");
                //已选择框形式列出用户要分享到的Activity
                Intent intent =Intent.createChooser(shareIntent,"分享到");
                startActivity(intent);
                break;
       }
    }
}
Activity01.java

package com.xyy.intentdemo;
importandroid.support.v7.app.AppCompatActivity;
import android.os.Bundle;
 
public class Activity01 extendsAppCompatActivity {
 
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_01);
    }
}
ShareActivity.java

package com.xyy.intentdemo;
 
import android.net.Uri;
import android.os.Bundle;
importandroid.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
 
public class ShareActivity extendsAppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_share);
       ImageView iv = (ImageView) findViewById(R.id.tv);
       Uri uri = getIntent().getData();
       Log.e("m_tag","uri:"+uri.toString());
       if(uri!=null){
           iv.setImageURI(uri);
       }
    }
}

======================================================

 2.Binder:

binder机制是一种IPC机制,进程间通讯的一种工具

Java层可以利用AIDL工具来实现相应的接口生成通讯代码


service服务在后台运行

 service注册: <serviceandroid:name="com.startservice.MyService"></service>

启动服务service 两种方式:

   一 startservice

     启动该服务的Activity挂了,服务不会挂,大难临头各自飞;不能拿到service的实例

    Service:

              //绑定时候的回调方法

              @Override

              publicIBinder onBind(Intentintent) {

                     returnnull;

              }

 

              //最后调用的方法

              @Override

              publicvoid onDestroy() {

                     super.onDestroy();

                    Log.d("TAG","StartService onDestroy");

              }

 

              //服务启动之后的回调

              @Override

              @Deprecated

              publicvoid onStart(Intent intent,int startId) {

                    super.onStart(intent,startId);

                    Log.d("TAG","StartService onStart");

              }

 

              //最先调用的方法

              @Override

              publicvoid onCreate() {

                     super.onCreate();

                    Log.d("TAG","StartService onCreate");

              }

      //=========================

     Activity.java:

         Intent mIntent = new Intent();

         mIntent.setClass(getApplicationContext(), MyService.class);

         bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);

 

     二绑定服务

       可以拿到服务的实例,引用。启动该服务的Activity挂了,服务也会挂了。

       1 IBinder  -- 类似王婆

            IBinder是远程对象的基本接口,

              是为高性能而设计的轻量级远程调用机制的核心部分。

              但它不仅用于远程调用,也用于进程内调用。

            这个接口定义了与远程对象交互的协议。

            不要直接实现这个接口,而应该从Binder派生。

 

      2绑定服务

        Service:

              classMyBinder extends Binder{

                     //通过getStartService拿到本服务的引用

                    StartServicegetStartService(){

                            //把本服务传递出去了

                           returnStartService.this;

                     }

              }

 

              //绑定时候的回调方法

              @Override

              publicIBinder onBind(Intentintent) {

                    Log.d("TAG","StartService onBind");

                     //MyBinder--方法 getgetStartService 可以获取到本服务

                     //获取本服务实例的步骤

                     //1拿到MyBinder 2 调用 getStartService

                     returnnew MyBinder();

              }    

 

      Activity:

                 ServiceConnection mConnection= newServiceConnection() {

                     //断开服务连接的回调方法

                     @Override

                     publicvoidonServiceDisconnected(ComponentName name) {

                   

                     }

                     //服务连接的回调方法 --- 在此方法中,拿到服务的引用

                     @Override

                     publicvoidonServiceConnected(ComponentName name, IBinder service) {

                            //拿到王婆

                            MyBinderm =((MyBinder)service);

                            //通过王婆,拿到潘XX

                            mService=m.getStartService();

                            mService.playMusic("听");

                     }   

              }

      Service :

                //绑定

            Intent mIntent = new Intent();

             mIntent.setClass(getApplicationContext(),StartService.class);

              //绑定的时候自动创建

               bindService(mIntent,mConnection,Context.BIND_AUTO_CREATE);

              //拿到服务的实例可以执行服务的方法

-------------------------------------------------------------------------------

Client 端videoDemo

AndroidManifest.xml


   
   

   
   
 
    
    
    
   
    
    
 
   
    
    
       
     
     
           
      
      
               
       
       
 
                
       
       
           
      
      
       
     
     
       
     
     
   
    
    

   
   

res\layout

activity_main.xml


   
   
   
    
    
   
    
    

   
   

VideoService.java

package com.example.lesson18_6.id0.video;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.R.integer;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
 
public class VideoService extends Service {
       //王婆
       classMyBinder extends Binder {
              //返回服务实例 潘XX
              VideoServicegetVideoService() {
                     returnVideoService.this;
              }
       }
 
       //Activity 需要IBinder 。。通过IBinder 可以找到服务
       //回调方法,绑定的时候回调
       @Override
       publicIBinder onBind(Intent intent) {
              returnnew MyBinder();
       }
      
   //还没下载状态
   final static String DOWN_UNDO = "DOWN_UNDO";
   //正在下载状态
   final static String DOWN_DOING = "DOWN_DOING";
   //下载结束状态
   final static String DOWN_DONE = "DOWN_DONE";
   //下载状态变量
   public String downState = DOWN_UNDO;
   
       voiddownLoad(final String path, final File pFile) {
              newThread() {
                     publicvoid run() {
                            //刚开始下载时发送广播出来
                            IntentmIntent = new Intent();
                            mIntent.setAction("com.example.lesson18_6.id0.video");
                            mIntent.putExtra("STATE","BEGIN");
                            sendBroadcast(mIntent);
                           
                            Log.d("TAG","down load path is " + path);
                            URLConnectionconnection = null;
                            InputStreaminputStream = null;
                            try{
                                   connection= new URL(path).openConnection();
                                   connection.setRequestProperty("accept","*/*");
                                   connection.setRequestProperty("connection","Keep-Alive");
                                   connection.setRequestProperty("user-agent",
                                                               "Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                                   connection.connect();
                            }catch (IOException e) {
                                   e.printStackTrace();
                            }
 
                            try{
                                   inputStream= connection.getInputStream();
                                   Log.d("TAG","connection.getInputStream");
                                   //如果文件不存在的情况下,创建文件
                                   pFile.createNewFile();
                                   FileOutputStreammFileOutputStream = new FileOutputStream(
                                                 pFile);
 
                                   //在下载的过程中写入文件
                                   byte[]data = new byte[1024];
                                   intlength = 0;
                                   downState= DOWN_DOING;
                                   while((length = inputStream.read(data)) != -1) {
                                          mFileOutputStream.write(data,0, length);
                                          Log.d("TAG","write length --> " + length);
                                   }
                                   downState= DOWN_DONE;
                                   //下载结束,并且把文件长度打印出来
                                   Log.d("TAG","**********finish*********" + pFile.length());
                                   mFileOutputStream.close();
                                   //刚开始下载时发送广播出来
                                   mIntent= new Intent();
                                   mIntent.setAction("com.example.lesson18_6.id0.video");
                                   mIntent.putExtra("STATE","FINISH");
                                   sendBroadcast(mIntent);
                                                                     
                            }catch (IOException e) {
                                   //TODO Auto-generated catch block
                                   e.printStackTrace();
                            }
                     };
              }.start();
       }
}

MainActivity.java

empty

==========================================

3. Message:

MainActivity.java

import org.w3c.dom.Text;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.talk.TCPThread.ITcp;

public class MainActivity extends Activity {

	LinearLayout mLayout = null;
	EditText mEditText = null;
	Button mButtonsend = null;
	TCPThread mTcpThread = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mTcpThread = new TCPThread("192.168.1.250", 9000);
        mLayout = (LinearLayout) findViewById(R.id.contentLayout);
        mEditText = (EditText) findViewById(R.id.editText1);
        mButtonsend = (Button) findViewById(R.id.buttonsend);
        
        mButtonsend.setOnClickListener(new OnClickListener() {
        	int index = 0;
			@Override
			public void onClick(View v) {
			
				//获取布局解析器并创建一个布局给我们
				LayoutInflater mInflater = LayoutInflater.from(getApplicationContext());
				View mView = mInflater.inflate(R.layout.talkitem, null);
				
				//设置文字
				TextView mTextViewcontent = (TextView) mView.findViewById(R.id.tvcontentitem);
				mTextViewcontent.setText(mEditText.getText().toString());
				
				mTextViewcontent.setTextColor(Color.BLACK);
				
				//设置参数
				LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT); 
				//第一次发送的图片从左边出现。
				//第二次发送的图片从右边出现。。
				//第三次发送的图片从左边出现。
				mLayoutParams.gravity = Gravity.LEFT;
				//添加view
				mLayout.addView(mView,mLayoutParams);
				mTcpThread.sendData((mEditText.getText().toString().getBytes()));
			}
		});
        
        //设置TCP的回调
        mTcpThread.setITcp(new ITcp() {
			@Override
			public void reflushUI(byte[] data) {
				//接收到了服务端的数据   ---   
				//1 run方法接收到
				//2 传到handler
				//3 通过回调传到MainActivity
				Log.d("TAG", "MAIN -- "+new String(data));
				
				//设置mTextView属性
				TextView mTextView = new TextView(getApplicationContext());
				mTextView.setBackgroundResource(R.drawable.qqtalksave);
				mTextView.setGravity(Gravity.CENTER);
				mTextView.setTextColor(Color.BLACK);
				
				//设置mTextView在布局中的属性
				LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
				mLayoutParams.gravity = Gravity.RIGHT;
				mTextView.setText("你接收的消息为" + new String(data));
				
				//添加进布局
				mLayout.addView(mTextView,mLayoutParams);
			}
		});
    }
}

TCPThread

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Arrays;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class TCPThread extends Thread{
	//成员变量
	Socket mSocket = null;
	//IP地址 127.0.0.1 -- 指的是 手机,不是PC
	private String maddr = "";
	private int mport = 0;
	
	//通过参数 传递进 IP地址,端口号。。启动线程
	TCPThread(String addr,int port){
		maddr = addr;
		mport = port;
		start();
	}
	
	//TCP发送数据
	public void sendData(byte[] data){
		//判断socket不为空,是否连接
		if(mSocket!=null){
			if(mSocket.isConnected()){
				try {
					mSocket.getOutputStream().write(data);
					Log.d("TAG", "成功发送消息");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	//定义回调接口
	interface ITcp{
		void reflushUI(byte[] data);
	}
	//定义接口的引用
	private ITcp mITcp = null;
	//传递接口进来
	public void setITcp(ITcp mITcp) {
		this.mITcp = mITcp;
	}
	
	//在主线程创建的,只要run方法里才是子线程
	Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			Log.d("TAG",  "what " + msg.what );
			//获取Massege中的Object,即接收到的byte数组
			byte[] handlerdata = (byte[]) msg.obj;
			
			for(int index = 0;index < handlerdata.length;index++){
				Log.d("TAG", "index "+ handlerdata[index]);
			}
			//如果接口不为空的话 ,调用刷新回调方法
			if(mITcp !=null){
				mITcp.reflushUI(handlerdata);
			}
		};
	};
	
	@SuppressLint("NewApi") @Override
	public void run() {
		//不能在主线程里 创建TCPsocket
		Log.d("TAG", maddr + "" + mport);
		try {
			Log.d("TAG", "开始连接TCP");
			//创建socket 
			mSocket = new Socket(maddr, mport);
			Log.d("TAG", "成功连接");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//接收TCP数据的缓冲区
		byte[] readdata = new byte[1024];
		while(true){
			//判断socket是否为空,是否正在连接中
			if(mSocket!=null){
				if(mSocket.isConnected()){
					try {
						//socket 输入流读取信息 返回读取的长度
						int length = mSocket.getInputStream().read(readdata);
						
						//封装一条消息
						Message message = new Message();
						message.what = 0xaa;
						//把数组方法 message中
						message.obj = Arrays.copyOfRange(readdata, 0, length);
						
						mHandler.sendMessage(message);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
}

res\layout

activity_main.xml


    
    

    
     
     
    
     
     

    
     
     

        
      
      
            
       
       
        
      
      

        
      
      
    
     
     

    
    
Talkitem


   
   

   
   
    
    
    
    
    
    
    
    
        
     
     
        
        
     
     
    
    
    

   
   

talkTCPhandlerClient\res\drawable-hdpi

.9.patch pic

talkTCPhandlerServer\src\com\demo

ServerThread

package com.xykj.demo;

import java.io.IOException;
import java.net.Socket;
import net.sf.json.JSONObject;

public class ServerThread extends Thread{
	Socket mSocket = null;
	public ServerThread(Socket pSocket){
		mSocket = pSocket;
		System.out.println("RemoteSocketAddress" + mSocket.getRemoteSocketAddress());
		start();
	}
	public void run() {
		byte[] data = new byte[1024];
		int length = 0;
		while(true){
			try {
				length = mSocket.getInputStream().read(data);
				System.out.println(new String(data,0,length));
				mSocket.getOutputStream().write(data, 0, length);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

Demo.java

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Demo {
	public static void main(String[] args) {
		try {
			//创建serversocket 指定端口号为9000
			ServerSocket mServerSocket = new ServerSocket(9000);
			
			while(true){
				System.out.println("等待对方连接");
				//等待连接 获取socket对象
				Socket mSocket = mServerSocket.accept();
				System.out.println("已经有客户端连接");
				//开启线程处理客户端
				new ServerThread(mSocket);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

==========================================

4. BroadcastReceiver:

DemoNotificationBroadcastMusic

AndroidManifest.xml

Local music no need manifest

-----------------------------------------------------------------------

notificationlayout.xml


   
   

   
   
    
    
    

    
    
    

    
    
    

   
   
MainActivity.java

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.NotificationCompat;
import android.view.Menu;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MainActivity extends Activity {
	MediaPlayer mediaPlayer = null;
	NotificationManager manager = null;
	NotificationCompat.Builder mBuilder = null;
	Notification mNotification = null;
	RemoteViews remoteViews = null;
	MyReciever myReciever = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// ==========================
		Intent intentStart = new Intent();
		intentStart.setAction("com.example.lesson17_5.id0.music");
		intentStart.putExtra("KEY_OPRATE", "START");
		PendingIntent pendingIntentStart = PendingIntent.getBroadcast(
				getApplicationContext(), 1, intentStart, 0);

		Intent intentPause = new Intent();
		intentStart.setAction("com.example.lesson17_5.id0.music");
		intentStart.putExtra("KEY_OPRATE", "START");
		PendingIntent pendingIntentPause = PendingIntent.getBroadcast(
				getApplicationContext(), 2, intentPause, 0);

		Intent intentStop = new Intent();
		intentStart.setAction("com.example.lesson17_5.id0.music");
		intentStart.putExtra("KEY_OPRATE", "START");
		PendingIntent pendingIntentStop = PendingIntent.getBroadcast(
				getApplicationContext(), 3, intentStop, 0);

		// ==========================
		mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.login);
		// mediaPlayer.start();
		remoteViews = new RemoteViews(getPackageName(),
				R.layout.notificationlayout);
		
		// 通过remoteview 设置按钮的点击事件
		remoteViews.setOnClickPendingIntent(R.id.buttonstart,
				pendingIntentStart);
		
		remoteViews.setOnClickPendingIntent(R.id.buttonpause,
				pendingIntentPause);
		
		remoteViews.setOnClickPendingIntent(R.id.buttonstop, 
				pendingIntentStop);
		// 创建penddingintent 。点击 跳转到下个界面

		// 创建notification builder
		mBuilder = new NotificationCompat.Builder(getApplicationContext());
		mBuilder.setContentTitle("这是个title").setContentText("这是个text")
				.setSmallIcon(R.drawable.ic_launcher).setTicker("这是个ticker")
				.setContent(remoteViews);

		// 创建出notification。包含通知的信息
		mNotification = mBuilder.build();
		manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		manager.notify(0, mNotification);

		myReciever = new MyReciever();
		IntentFilter mFilter = new IntentFilter();
		mFilter.addAction("com.example.lesson17_5.id0.music");
		registerReceiver(myReciever, mFilter);
	}

	class MyReciever extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// 获取是哪个按钮按下的
			String oprate = intent.getStringExtra("KEY_OPRATE");
			Toast.makeText(getApplicationContext(), "@@@@" + oprate,
					Toast.LENGTH_SHORT).show();
			// mediaPlayer.start();
		}
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值