Android软件开发之应用程序之间的通信介绍

Android 开发中在程序之间通讯的接口做的还是非常丰富的本例主要向大家介绍程序之间是如何进行沟通,有哪几种沟通方式如何来实现沟通。

1.      使用handler传递消息

    handler 大家可以把它想象成主线程(UI线程)的一个子线程,它可以给主线程(UI线程)发送数据从而更新主线程(UI线程)UI与逻辑,handler是一个子线程所以它的耗时操作不会阻塞主线程,大家都知道在android的开发中如果代码中某个地方阻塞主线程超过5秒的话系统会提示ANR (系统提示强制关闭)所以在耗时操作上我们可以考虑开启一个子线程避免ANR handler会向主线程发送消息会以队列的形式排列着配合等待主线程更新UI逻辑等等。

下面这个例子诠释了这一点利用handler传递消息来更新主线程的UI显示内容点击按钮后每过一秒通过handler发送消息更新UI线程显示的时间直到显示时间更新到10然后结束这个线程。

package com.example.handleractivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements Runnable{
	public final static int UPDATE_TIME =0; 
	public final static int UPDATE_COMPLETED =1; 
	private int mShowNumber = 0; 
	private Button mButton = null; 
	private TextView mTextView = null; 
	private Thread mThread = null; 
	private boolean mRunning = false; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_main);
		mButton = (Button)findViewById(R.id.button0);  
		mTextView = (TextView)findViewById(R.id.textView0); 
		mThread = new Thread(this); 
		mButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mRunning = true; 
				mThread.start(); 
			} 
		});
		mTextView.setText("点击按钮开始更新时间");  
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (mRunning) { 
			try { 
			mShowNumber++; 
			Bundle bandle = new Bundle(); 
			bandle.putString("number", String.valueOf(mShowNumber));  
			Message msg = new Message(); 
			if(mShowNumber <=10) {  
				msg.what = UPDATE_TIME; 
			}else { 
				mRunning = false; 
				msg.what = UPDATE_COMPLETED;  
			}
			msg.setData(bandle);
			handler.sendMessage(msg);
			Thread.sleep(1000);
			}catch (InterruptedException e) {  
				e.printStackTrace();
			}
		}		
	}
	
	Handler handler = new Handler() { 
		public void handleMessage(Message msg) {
			Bundle bundle= msg.getData();
			String number = bundle.getString("number");
			switch(msg.what) { 
			case UPDATE_TIME: 
				mTextView.setText("正在更新时间" + number); 
				break; 
			case UPDATE_COMPLETED:  
				mTextView.setText("更新完毕");  
				break; 
			}
			super.handleMessage(msg); 
		}
	};	

	public void ShowDialog(String string) {  
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
		builder.setIcon(R.drawable.ic_launcher); 
		builder.setTitle(string);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				finish(); 
			} 
		});
		builder.show(); 
	}
	
	@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;
	}	
}

 2.  Notifation通知栏信息

    Notifation通知栏会在屏幕上方向用户提示信息但是不会打断用户正在阅读的内容,除非用户手动将 Notifation通知栏拉下。 Notifation的好处就是在于不会影响用户的操作,比如用户正在阅读非常重要的信息这时候帮他直接打开一个activity会非常不合适因为直接影响到了他当时的操作行为所以Notifation就出来了。建议大家在开发中遇到可能打断用户使用的情况下都去使用Notifation通知栏。

package com.example.notificationactivity;

import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	NotificationManager mManager = null; 
	Notification notification =null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
		notification = new Notification(R.drawable.icon, "Android专业开发群", System.currentTimeMillis()); 
		notification.flags = Notification.FLAG_AUTO_CANCEL; 
		
		Intent intent = new Intent(this, MyShowActivity.class); 
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NEW_TASK); 
		Bundle bundle = new Bundle(); 
		bundle.putString("name", "从Notification转跳过来的");  
		intent.putExtras(bundle);
		
		PendingIntent contentIntent = PendingIntent.getActivity(this, R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(this, "Android专业开发群","QQ群号 164257885", contentIntent); 
		
		Button button0 = (Button)findViewById(R.id.button1);  
		button0.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mManager.notify(0, notification); 
			}  
		});
		
		Button button1 = (Button)findViewById(R.id.button2); 
		button1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mManager.cancelAll(); 
			} 
		});
	}

	@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.      广播的发送与接收

    Android开发中如果须要对两个完全没关系的程序之间进行通信就可以使用发送广播与接收广播的机制来实现,例如程序A发送了一个广播程序B接受到做一些事情这样就达到了相互的通讯。

调用sendBroadcast()传入intent后来发送广播。

package com.example.broadcastactivity;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	public final static String SEND_OK_MESSAGE = "send.ok.message";  
	public final static String SEND_CANCLE_MESSAGE = "send.cancle.message"; 
	Button mButton0 = null;
	Button mButton1 = null; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mButton0 = (Button)findViewById(R.id.button1);  
		mButton0.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(SEND_OK_MESSAGE); 
				intent.putExtra("name", "您发送了OK这条广播哦"); 
				sendBroadcast(intent); 
			} 
		});
		
		mButton1 = (Button)findViewById(R.id.button2); 
		mButton1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(SEND_CANCLE_MESSAGE); 
				intent.putExtra("name", "您发送了Cancle这条广播哦");  
				sendBroadcast(intent);  
			}  
		});
		
		//Intent i = new Intent(this, MyService.class); 
		//startService(i);
	}

	@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;
	}

}

接收广播的话我们开启一个serviceservice中通过BroadcastReceiver来接收广播前提是须要接收的广播须要在onStart()中注册一下在AndroidManifest.xml中可以过滤只接收须要接收的广播。

<service android:name=".MyService">
	<intent-filter>
		<action android:name="cn.m15.xys.MyService"></action>  
	</intent-filter> 
	<intent-filter>
		<action android:name="send.ok.message" /> 
		<action android:name="send.cancle.message" /> 
	</intent-filter>
</service>

onStart()中注册了程序中所需要的两个广播。

package com.example.servicereceive;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
	public final static String SEND_OK_MESSAGE = "send.ok.message";  
	public final static String SEND_CANCLE_MESSAGE = "send.cancle.message"; 

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	} 
	
	public void onStart(Intent intent, int startId) {
		IntentFilter myFilter = new IntentFilter(); 
		myFilter.addAction(SEND_OK_MESSAGE); 
		myFilter.addAction(SEND_CANCLE_MESSAGE); 
		this.registerReceiver(myBroadCast, myFilter); 
		super.onStart(intent, startId); 
	}
	
	private BroadcastReceiver myBroadCast = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();  
			if (action.equals(SEND_OK_MESSAGE)) { 
				Toast.makeText(context, "接收到了一条广播为" + SEND_OK_MESSAGE, Toast.LENGTH_LONG).show(); 
			}else if(action.equals(SEND_CANCLE_MESSAGE)) { 
				Toast.makeText(context, "接收到了一条广播为" + SEND_CANCLE_MESSAGE, Toast.LENGTH_LONG).show(); 
			}
		} 
	};
	
}

这里注意一下service如果没有起来我们是接收不到广播的所以一定要保证接收的时候service是开启的,上例中的service是在打开activity时开启的但是如果用户把手机关掉然后在开机,这样的话service就不是打开状态这样就非常危险了因为这时scrvice就接收不到任何消息了除非用户再次进activity才会帮他打开scrvice所以我们可以在用户开机后就直接将scrvice打开,具体的实现方式如下。

AndroidManifest.xml中注册一个开机广播这个广播系统只会在开机发出而且只会发出一次所以我们接收这个广播就可以知道手机是否为开机状态。

        <receiver android:name=".MyBootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" /> 
            </intent-filter>
        </receiver>

注意加入权限。

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 

BroadcastRecevier中接收开机广播然后打开service就可以实现开机启动service

package com.example.servicereceive;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyBootReceiver extends BroadcastReceiver {
	static final String BOOT_COMPLETED = "android.intent.action.BOOT_COMPLETED"; 
	
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if (intent.getAction().equals(BOOT_COMPLETED)) {
			Intent i = new Intent(context, MyService.class);
			context.startService(i); 
		}
	} 
}

4. ActivityActivity之间的转跳

在软件应用的开发中肯定会有多个Activity这样它们之间就会存在相互转跳的关系转跳的实现方式还是使用Intent 然后startActivity ,当然转跳的话是可以带数据过去的。比如从A跳到B可以把A中的一些数据通过Intent传递给B

读下面这段代码大家会发现intentbandle传递数值的方式基本一样为什么还要分成两个呢?确实他们两个传递的数值的方式非常类似,他们两个的区别就是Intent属于把零散的数据传递过去而bundle则是把零散的数据先放入bundle然后在传递过去。我举一个例子比如我们现在有3activity A.B.C须要把A的数据穿给B然后在穿给C,如果使用intent一个一个传递须要在A类中一个一个传递给B然后B类中获取到所有数值然后在一个一个传递给C这样很麻烦但是如果是bundle的话 B类中直接将bundler传递给C不用一个一个获得具体的值然后在C类中直接取得解析数值。

package com.example.activityactivity;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Button botton3 = (Button)findViewById(R.id.button1); 
		botton3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MainActivity.this, ShowActivity.class);  
				intent.putExtra("name", "雨松MOMO");
				intent.putExtra("age", 25); 
				intent.putExtra("boy", true);  
				
				Bundle bundle = new Bundle(); 
				bundle.putString("b_name", "小可爱"); 
				bundle.putInt("b_age", 23);
				bundle.putBoolean("b_boy", false); 
				intent.putExtras(bundle); 
				startActivity(intent); 
			} 
		});
	}

	@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;
	}
}

接收 

package com.example.activityactivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ShowActivity extends Activity { 
	protected void onCreate(Bundle savedInstanceState) { 
		setContentView(R.layout.my); 
		Intent intent = getIntent(); 
		String name = intent.getStringExtra("name"); 
		int age  = intent.getIntExtra("age", 0); 
		boolean isboy = intent.getBooleanExtra("boy", false);
		TextView textView0 = (TextView)findViewById(R.id.textView1);
		textView0.setText("姓名  " + name + "年龄 " + age + "男孩?  " + isboy);  
		
		Bundle bundle = intent.getExtras(); 
		name = bundle.getString("b_name"); 
		age = bundle.getInt("b_age",0);
		isboy = bundle.getBoolean("b_boy", false); 
		TextView textView1 = (TextView)findViewById(R.id.textView2);
		textView1.setText("姓名  " + name + "年龄 " + age + "男孩?  " + isboy); 
		
		super.onCreate(savedInstanceState);
	}
}


转载自:http://blog.csdn.net/xys289187120/article/details/6666125

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值