安卓---------------启动后台服务读取SIM卡信息发送广播到前端显示

从activity启动一个service,在service里面去读取SIM卡相关信息,然后通过广播的方式将SIM信息发送出去,activity在接收到广播后,将SIM卡信息读取并显示出来。

主布局文件: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">

    <Button 
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/startservice"
        android:textSize="20sp"
        />
    <Button 
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:text="@string/stopservice"
        android:textSize="20sp"
        />
    <LinearLayout 
        android:layout_width="match_parent"
    	android:layout_height="match_parent"
    	android:layout_below="@+id/button2"
    	android:orientation="vertical"
    	>
    	<TextView
    	    android:id="@+id/SIM"
    	    android:layout_width="wrap_content"
    	    android:layout_height="wrap_content"
    	    android:textSize="20sp"
    	    android:text="@string/SIMinfo"
        />
    	<ListView 
    	    android:id="@+id/SIMInfo"
    	    android:layout_width="match_parent"
    	    android:layout_height="match_parent"
    	    ></ListView>   	    
    	</LinearLayout>
	
</RelativeLayout>
listview 布局文件:list_laytou.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView 
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:textSize="20sp"
        android:textColor="@android:color/black"
        />
    <TextView 
        android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:textSize="15sp"
        android:textColor="@android:color/darker_gray"
        />
</LinearLayout>

主程序:MainActivity.java

package com.example.getsim;

import java.util.ArrayList;
import java.util.HashMap;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private mServiceReceiver mReceiver01;
	Button button1 = null;
	Button button2 = null;
	private ListView list = null;
	private int[] items = new int[] { R.string.str_list0,R.string.str_list1,
			R.string.str_list2,R.string.str_list3,R.string.str_list4};
	private String[] valus = new String[]{null,null,null,null,null,null};
	//private List<String> item=new ArrayList<String>();
	//private List<String> value=new ArrayList<String>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button1 = (Button)findViewById(R.id.button1);
		button2 = (Button)findViewById(R.id.button2);
		list = (ListView)findViewById(R.id.SIMInfo);
		button1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//启动线程
				Intent i = new Intent(MainActivity.this,mService1.class);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startService(i);
				Toast.makeText(getApplicationContext(), "后台服务已启动",
					     Toast.LENGTH_SHORT).show();
			}
		});
		button2.setOnClickListener(new Button.OnClickListener()
	    {
	      @Override
	      public void onClick(View v)
	      {
	        // TODO Auto-generated method stub	        
	        /* 指定终止执行后台服务(mService1) */
	        Intent i = new Intent( MainActivity.this, mService1.class );        
	        /* 顺利关闭系统服务 */
	        if(stopService(i)==true)
	        {
	        	Toast.makeText(getApplicationContext(), "后台服务已关闭",
					     Toast.LENGTH_SHORT).show();
	        }
	        else
	        {
	          /* 显示关闭服务失败 */
	        	Toast.makeText(getApplicationContext(), "后台服务关闭错误",
					     Toast.LENGTH_SHORT).show();
	        }
	      }
	    });
	}

	//建议继承BroadcastReceiver的mServiceReceiver类接收广播
	public class mServiceReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			System.out.println("get broadcast------------>1");
			try {
		        /* 取并来自后台服务所Broadcast的参数 */
		        Bundle bunde = intent.getExtras();
		        String simstatus = bunde.getString("sim_status");
		        String simnumber = bunde.getString("sim_number");
		        String simoperator = bunde.getString("sim_operator");
		        String operatorname = bunde.getString("operator_name");
		        String country = bunde.getString("country");  
		        valus[0] = simstatus;
		        valus[1] = simnumber;
		        valus[2] = simoperator;
		        valus[3] = operatorname;
		        valus[4] = country;
		        System.out.println("simstatus------------>"+valus[0]);
		        System.out.println("simnumber------------>"+valus[1]);
		        System.out.println("simoperator------------>"+valus[2]);
		        System.out.println("operatorname------------>"+valus[3]);
		        System.out.println("country------------>"+valus[4]);
		        ArrayList<HashMap<String, Object>> listitem = new ArrayList<HashMap<String,Object>>();
		        //填入数据
				for(int i=0;i<items.length;i++)
				{
					//为每行填入对应数据
					HashMap<String,Object> map = new HashMap<String, Object>();
					//这里要用ID把字符串读取出来,不然最后显示的是字符串的数字ID
					map.put("ItemTitle", getResources().getText(items[i]).toString());
					//map.put("ItemTitle", items[i] );
					map.put("Values", valus[i]);
					//加入到列表中
					listitem.add(map);
				}
				SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, listitem, R.layout.list_layout, 
						new String[]{"ItemTitle","Values"}, new int[]{R.id.text1,R.id.text2});
				list.setAdapter(adapter); 
				//读取到信息后关闭后台服务
				Intent i = new Intent(MainActivity.this,mService1.class);
				if(stopService(i)==true)
		        {
		        	Toast.makeText(getApplicationContext(), "后台服务已关闭",
						     Toast.LENGTH_SHORT).show();
		        }
				System.out.println("simstatus:"+simstatus);
			} catch (Exception e) {
				// TODO: handle exception
				e.getStackTrace();
			}			
		}	
	}	
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		try
	    {
	      /* 前景程序生命周期开始 */
	      IntentFilter mFilter01;
	      
	      /* 自定义要过滤的广播讯息(DavidLanz) */
	      mFilter01 = new IntentFilter(mService1.HIPPO_SERVICE_IDENTIFIER);
	      mReceiver01 = new mServiceReceiver();
	      registerReceiver(mReceiver01, mFilter01);
	    }
	    catch(Exception e)
	    {
	      e.getStackTrace();
	    }
		super.onResume();
	}
	
	@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;
	}

}

Service程序:mservice1.java

package com.example.getsim;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.TelephonyManager;

public class mService1 extends Service{

	/* 建立Handler对象 */
	private Handler objHandler = new Handler();
	private TelephonyManager telMgr;
	
	/* 自定义要过滤的广播讯息(DavidLanz) */
	public static final String HIPPO_SERVICE_IDENTIFIER = "SIMINFO"; 
	
	private Runnable mtasks = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			//获取手机相关信息
			telMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
			//发生广播
			Intent i = new Intent(HIPPO_SERVICE_IDENTIFIER);
			//获取要传递的信息并放入
			if(telMgr.getSimState()==TelephonyManager.SIM_STATE_READY)
		    {
		      i.putExtra("sim_status", "良好");
		    }
		    else if(telMgr.getSimState()==TelephonyManager.SIM_STATE_ABSENT)
		    {
		    	i.putExtra("sim_status", "无SIM卡");
		    }
		    else
		    {
		    	i.putExtra("sim_status", "SIM卡被锁定或未知的状态");
		    }
			
			/* 取得SIM卡卡号 */
		    if(telMgr.getSimSerialNumber()!=null)
		    {
		    	i.putExtra("sim_number", telMgr.getSimSerialNumber());
		    }
		    else
		    {
		    	i.putExtra("sim_number", "无法取得");
		    }
		    
		    /* 取得SIM卡供货商代码 */
		    if(telMgr.getSimOperator().equals(""))
		    {
		    	i.putExtra("sim_operator", "无法取得");
		    }
		    else
		    {
		    	i.putExtra("sim_operator", telMgr.getSimOperator());
		    }
		    
		    /* 取得SIM卡供货商名称 */
		    if(telMgr.getSimOperatorName().equals(""))
		    {
		    	i.putExtra("operator_name", "无法取得");
		    }
		    else
		    {
		    	i.putExtra("operator_name", telMgr.getSimOperatorName());
		    }
		    
		    /* 取得SIM卡区域 */
		    if(telMgr.getSimCountryIso().equals(""))
		    {
		    	i.putExtra("country", "无法取得");
		    }
		    else
		    {
		    	i.putExtra("country", telMgr.getSimCountryIso());
		    }
		    sendBroadcast(i);
		    System.out.println("send broadcast------------>1");
		    objHandler.postDelayed(mtasks, 5000); 
		}
	};
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		System.out.println("stop service------------>1");
		 objHandler.removeCallbacks(mtasks);
		super.onDestroy();
	}

	@Override
	@Deprecated
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		System.out.println("start service------------>1");
		objHandler.postDelayed(mtasks, 1000);
		super.onStart(intent, startId);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub	
		return null;
	}

}

最后还要使用<uses-permission android:name="android.permission.READ_PHONE_STATE"/> 在mainfest中注册读取SIM的权限。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值