入门android广播简单例子

效果图如下:

点击检查网络按钮,提醒网络是否连接
入门android广播简单例子
 AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="14" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".activity.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="com.lesson.service.MyService"
            ></service>
    </application>

</manifest>

 activity_main.xml:

<RelativeLayout 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"
    tools:context="${relativePackage}.${activityClass}" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="18dp"
        android:text="检查网络" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="195dp"
         />

</RelativeLayout>

 MainActivity.java

package com.lesson.activity;

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

import com.lesson.R;
import com.lesson.service.MyService;

public class MainActivity extends Activity {

	private Button button;

	private ImageView imageView;// 要加载的图片

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button = (Button) findViewById(R.id.button1);
		imageView = (ImageView) findViewById(R.id.imageView1);
		
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			//启动service来处理广播任务
				Intent intent=new Intent(MainActivity.this,MyService.class);
				startService(intent);
				
			}
		});
		
		
	}
	

	
	
}

 MyService.java

package com.lesson.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;



public 	class MyService extends Service{
	BroadcastReceiver networkBroadcast=null;  
	@Override
	public IBinder onBind(Intent intent) {
		
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		
		super.onStart(intent, startId);
		IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);  
		networkBroadcast = new BroadcastReceiver() {

			public void onReceive(Context context, Intent intent) {
				Log.i("tga", "network state changed.");
				if (!isNetworkAvailable(context)) {
					Toast.makeText(context, "network disconnected!", 0).show();
					Log.i("tga", "network state wrong.");
				} else {
					Toast.makeText(context, "network connected!", 0).show();
					Log.i("tga", "network state ok.");
				}

			}

			/**
			 * 网络是否可用
			 * 
			 * @param context
			 * @return
			 */
			public boolean isNetworkAvailable(Context context) {
				ConnectivityManager mgr = (ConnectivityManager) context
						.getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo[] info = mgr.getAllNetworkInfo();
				if (info != null) {
					for (int i = 0; i < info.length; i++) {
						if (info[i].getState() == NetworkInfo.State.CONNECTED) {
							return true;
						}
					}
				}
				return false;
			}
		};
		          
		registerReceiver(networkBroadcast, filter);  
	}

	@Override
	public void onCreate() {
		
		super.onCreate();
		//动态注册广播接收者
		
        
	
	}

	@Override
	public void onDestroy() {
		
		super.onDestroy();
		unregisterReceiver(networkBroadcast); 
	}
	
}

 注意点:

相关推荐