Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android短信監聽(三)——利用Loader實現短信監聽

Android短信監聽(三)——利用Loader實現短信監聽

編輯:關於Android編程

MainActivity如下:

package cc.c;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.Loader;
import android.database.Cursor;
/**
 * Demo描述:
 * 利用Loader實現竊聽短信
 * 
 * 參考資料:
 * 1 http://blog.csdn.net/niu_gao/article/details/7244117
 * 2 http://www.cnblogs.com/jisheng/archive/2013/01/09/2852553.html
 * 3 http://blog.csdn.net/linmiansheng/article/details/25836937
 *   Thank you very much
 * 
 * 注意事項:
 * 1 Loader是3.0之後才引進來的
 * 2 若在3.0之前使用Loader那麼Activity須繼承FragmentActivity
 * 3 在Loader內部封裝好了ContentOberver
 *
 */
public class MainActivity extends Activity implements LoaderCallbacks{
    private final int LOADER_ID=9527;
    private Context mContext;
    private Uri mUri=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
	}
	
	private void init(){
		mContext=this;
		mUri = Uri.parse("content://sms/inbox");
		this.getLoaderManager().initLoader(LOADER_ID, null, this);
	}

	@Override
	public Loader onCreateLoader(int arg0, Bundle bundle) {
		String[] projection = new String[] {"_id","address","body","type"};
		Loader cursorLoader=
		new android.content.CursorLoader(mContext, mUri, projection, null, null, "date desc");
		return cursorLoader;
	}

	@Override
	public void onLoadFinished(Loader loader, Cursor cursor) {
        while (cursor.moveToNext()) {
        	String address  = cursor.getString(cursor.getColumnIndex("address"));
    		String body = cursor.getString(cursor.getColumnIndex("body"));
    		int id = cursor.getInt(cursor.getColumnIndex("_id"));
    		String type  = cursor.getString(cursor.getColumnIndex("type"));
    		System.out.println("------> 收到新的短信:"+"來自="+address+",內容="+body+",id="+id+",類別="+type);
    		break;
		}
	}

	@Override
	public void onLoaderReset(Loader loader) {
		
	}
	
	


}

main.xml如下:



    


AndroidManifest.xml如下:



    
    
      

    
        
            
                

                
            
        
    



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved