您的位置:首页 > 编程语言 > PHP开发

安卓获取手机短信(Contentprovider)

2017-10-19 20:55 239 查看
1.配置权限<uses-permission android:name="android.permission.READ_SMS"/>主函数
public class MainActivity extends AppCompatActivity {
private String path="content://sms";
private ListView lv;
private TextView tv1,tv2,tv3;
private View inflate ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView)findViewById(R.id.lv);

// 获取ContentRecolver 实例化对象
ContentResolver con = getContentResolver();
Cursor query = con.query(Uri.parse(path), null, null, null, null);
myspq sp = new myspq(this, query, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
lv.setAdapter(sp);

}
class myspq extends CursorAdapter {
public myspq(Context context, Cursor c, int flags) {
super(context, c, flags);
}
//直接将每个条目的View  返回即可
@Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
inflate = View.inflate(MainActivity.this, R.layout.buju, null);
return MainActivity.this.inflate;
}

/*
* 第一个参数:  当前Item的 View(ViewGroup)
* 第三个参数  就是  当前Cursor
*
*/
@Override
public void bindView(View view, Context context, Cursor c) {
tv1=inflate.findViewById(R.id.tv1);
tv2=inflate.findViewById(R.id.tv2);
tv3=inflate.findViewById(R.id.tv3);
// 电话号码
String address = c.getString(c.getColumnIndex("address"));
// 消息发送的内容
String body = c.getString(c.getColumnIndex("body"));
// 消息的类型
String type = c.getString(c.getColumnIndex("type"));
tv1.setText(address);
tv2.setText(body);
// 进行判断 是接收到的短信 还是发送出去的短信
if(type.equals("1")){
tv3.setText("接收");
}else if(type.equals("2")){
tv3.setText("发送");
}

}
}
}
主布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.example.myapplication.MainActivity"
android:orientation="vertical">

<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
Item布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 手机 短信