我想快速删除从电话号码收到的短信,以免向用户显示短信(为了阻止"阻止该用户的电话号码)。我也希望我的Android应用程序显示一个布局,但似乎不可能同时做两个!
这是我删除短信的方法:
public void deleteSMS(Context context, String number) {
try {
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = context.getContentResolver().query(uriSms,
new String[] { "_id", "thread_id", "address",
"person", "date", "body" }, null, null, null);
if (c != null && c.moveToFirst()) {
do {
long id = c.getLong(0);
String address = c.getString(2);
if (address.equals(number)) {
context.getContentResolver().delete(
Uri.parse("content://sms/" + id), null, null);
Toast.makeText(this, "SMS deleted", Toast.LENGTH_SHORT).show();
}
} while (c.moveToNext());
}
} catch (Exception e) {
}
然后,为了阻止电话号码" 123456",我这样做:
setContentView(R.layout.activity_main);
int r = 0;
while (r<1){
deleteSMS(this, "123456");}
应用程序会在我发送短信时完美删除短信,但它不会显示任何布局或祝酒词。当我这样做的时候:
setContentView(R.layout.activity_main);
deleteSMS(this, "123456");
它显示所有布局,祝酒词和删除短信。你有想法解决它吗?
答案 0 :(得分:0)
只是为了给你一个开始,因为(在一些评论之后)似乎你打算在应用程序总是在运行的地方做它)
public class MainActivity extends Activity{
private final static int SERVICE_ID = 1234;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent notificationIntent = new Intent(this, DeleteSmsService.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notice = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setContentText("Deleting SMS Messages")
.setContentIntent(pendingIntent).build();
notice.flags |= Notification.FLAG_NO_CLEAR;
startForeground(SERVICE_ID, notice);
}
}
然后创建服务
public DeleteSmsService extends Service{
private ContentResolver contentResolver;
@Override
public void onCreate(){
super.onCreate();
contentResolver = getContext().getContentResolver();
new Thread(){
@Override
public void run(){
while(true){
deleteSms(contentResolver, "123456");
}
}
}.start();
}
public void deleteSMS(ContentResolver cr, String number) {
try {
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = cr.query(uriSms,
new String[] { "_id", "thread_id", "address",
"person", "date", "body" }, null, null, null);
if (c != null && c.moveToFirst()) {
do {
long id = c.getLong(0);
String address = c.getString(2);
if (address.equals(number)) {
cr.delete(Uri.parse("content://sms/" + id), null, null);
Toast.makeText(this, "SMS deleted", Toast.LENGTH_SHORT).show();
}
} while (c.moveToNext());
}
} catch (Exception e) {
}
}
我还没有测试过这些,我不知道是否有错误,或者格式化可能会关闭,因为我只是快速输入它。这是为了让你开始做你想做的最好的方式我可以想到这样做而不会阻碍UI线程和维护正常的约定。您可能需要使用线程处理程序,不确定(再次测试它)。
同样,我不会这样做,但这只是为了帮助您开始尝试做的事情,因为这是您似乎打算做的事情。