java 在 Android 1.5 中删除短信

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2183680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:55:00  来源:igfitidea点击:

Delete SMS in Android 1.5

javaandroidsms

提问by Dmytro

There are many questions about it, no answers are working in my application :(

关于它有很多问题,在我的应用程序中没有答案:(

I need to remove SMS from a receiver, even if the user can see it, but it must be removed programmatically.

我需要从接收器中删除 SMS,即使用户可以看到它,但必须以编程方式删除它。

How can I do it?

我该怎么做?

The most suitable I have used was the following, but it doesn't work :(

我用过的最合适的是以下,但它不起作用:(

context.getContentResolver().delete(
                deleteUri,
                "address=? and date=?",
                new String[] { msg.getOriginatingAddress(),
                        String.valueOf(msg.getTimestampMillis()) });

回答by Dmytro

After refactoring my code I found that next solution works:

重构我的代码后,我发现下一个解决方案有效:

private int deleteMessage(Context context, SmsMessage msg) {
    Uri deleteUri = Uri.parse("content://sms");
    int count = 0;
    Cursor c = context.getContentResolver().query(deleteUri, null, null,
            null, null);
    while (c.moveToNext()) {
        try {
            // Delete the SMS
            String pid = c.getString(0); // Get id;
            String uri = "content://sms/" + pid;
            count = context.getContentResolver().delete(Uri.parse(uri),
                    null, null);
        } catch (Exception e) {
        }
    }
    return count;
}

Thanks everyone for help!

感谢大家的帮助!

ps if this code is useful for some one - remember that catch(Exception) is not good.

ps 如果此代码对某些人有用 - 请记住 catch(Exception) 不好。

回答by Ashekur Rahman Molla Asik

Just use this simple code in your broadcast receiver.

只需在您的广播接收器中使用这个简单的代码。

try {
        Uri uriSms = Uri.parse("content://sms/inbox");
        Cursor c = context.getContentResolver().query(
                uriSms,
                new String[] { "_id", "thread_id", "address", "person",
                        "date", "body" }, "read=0", null, null);

        if (c != null && c.moveToFirst()) {
            do {
                long id = c.getLong(0);
                long threadId = c.getLong(1);
                String address = c.getString(2);
                String body = c.getString(5);
                String date = c.getString(3);
                if (message.equals(body) && address.equals(number)) {
                    // mLogger.logInfo("Deleting SMS with id: " + threadId);
                    context.getContentResolver().delete(
                            Uri.parse("content://sms/" + id), "date=?",
                            new String[] { <your date>});
                    Log.e("log>>>", "Delete success.........");
                }
            } while (c.moveToNext());
        }
    } catch (Exception e) {
        Log.e("log>>>", e.toString());
    }

回答by Christopher Orr

What's the value of deleteUri?

的价值是deleteUri什么?

Are you sure that the SMS has been written to the local storage beforeyou're trying to delete it? If you're handling the SMS_RECEIVEDbroadcast, it's not guaranteed that the SMS will have been processed by the native SMS app yet...

在尝试删除SMS之前,您确定该 SMS 已写入本地存储吗?如果您正在处理SMS_RECEIVED广播,则不能保证本机 SMS 应用程序已经处理了 SMS...

Also, I would note that the SMS content provider API isn't publicly documented by Android and could be subject to change in the future. But if you're only targeting Android 1.5 (or current devices), then you may be ok.

另外,我要指出的是,Android 并未公开记录 SMS 内容提供程序 API,将来可能会发生变化。但如果您只针对 Android 1.5(或当前设备),那么您可能没问题。

回答by Donal Rafferty

This link may be useful

这个链接可能有用

http://blog.chinaunix.net/u/9577/showart_1850111.html

http://blog.chinaunix.net/u/9577/showart_1850111.html

I have not fully implemented it myself but what I have implemented works

我自己还没有完全实施,但我实施的工作有效

Note that it is not fully documented and so is likely to change in future versions of Android

请注意,它没有完整记录,因此可能会在未来的 Android 版本中更改

EDIT:

编辑:

Here is the way I implemented the code myself:

这是我自己实现代码的方式:

String url = "content://sms/"; 
        Uri uri = Uri.parse(url); 
        getContentResolver().registerContentObserver(uri, true, new MyContentObserver(handler)); 

        Uri uriSms = Uri.parse("content://sms/inbox");
        Cursor c = getContentResolver().query(uriSms, null,null,null,null); 

        Log.d("COUNT", "Inbox count : " + c.getCount());


}

class MyContentObserver extends ContentObserver { 

    public MyContentObserver(Handler handler) { 

        super(handler); 

    }

@Override public boolean deliverSelfNotifications() { 
    return false; 
    }

@Override public void onChange(boolean arg0) { 
    super.onChange(arg0);

     Log.v("SMS", "Notification on SMS observer"); 

    Message msg = new Message();
    msg.obj = "xxxxxxxxxx";

    handler.sendMessage(msg);

    Uri uriSMSURI = Uri.parse("content://sms/");
    Cursor cur = getContentResolver().query(uriSMSURI, null, null,
                 null, null);
    cur.moveToNext();
    String protocol = cur.getString(cur.getColumnIndex("protocol"));
    if(protocol == null){
           Log.d("SMS", "SMS SEND"); 
           int threadId = cur.getInt(cur.getColumnIndex("thread_id"));
           Log.d("SMS", "SMS SEND ID = " + threadId); 
           getContentResolver().delete(Uri.parse("content://sms/conversations/" + threadId), null, null);

    }
    else{
        Log.d("SMS", "SMS RECIEVE");  
         int threadIdIn = cur.getInt(cur.getColumnIndex("thread_id"));
         getContentResolver().delete(Uri.parse("content://sms/conversations/" + threadIdIn), null, null);
    }

}


} 

The code listens for changes in the SMS Content Provider.

该代码侦听 SMS 内容提供程序中的更改。

This is the line you would be interested in if you wish to delete an SMS

如果您想删除短信,这是您感兴趣的线路

getContentResolver().delete(Uri.parse("content://sms/conversations/" + threadIdIn), null, null);

You have to delete an entire conversation to delete the SMS, I haven't been able to just delete the last message of a conversation

您必须删除整个对话才能删除短信,我无法删除对话的最后一条消息

回答by megin from czech

use this and be happy guys

使用它并成为快乐的人

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SmsMessage;
import android.widget.Toast;
import android.net.Uri;

public class SmsReceiver extends BroadcastReceiver {

    private Handler mHandler = new Handler();
    private SmsMessage[] msgs;
    private Context con;

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        Bundle bundle = intent.getExtras();        
        msgs = null;
        String str = "";            

        if (bundle != null)
        {
            Object[] pdus = (Object[]) bundle.get("pdus");

            msgs = new SmsMessage[pdus.length];            

            for (int i=0; i<msgs.length; i++)
            {
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                

                str += "SMS from " + msgs[i].getOriginatingAddress();                     
                str += ":";
                str += msgs[i].getMessageBody().toString();
                str += "\n";
            }

            con = context;

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    deleteSMS();     
                }
            }, 5000);

            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }                         
    }

    private void deleteSMS() 
    { 
        try 
        { 
            for (int i=0; i<msgs.length; i++)
            {
                con.getContentResolver().delete(Uri.parse("content://sms"), "address=? and date=?", new String[] {msgs[i].getOriginatingAddress(), String.valueOf(msgs[i].getTimestampMillis())});             
            }
        } 
        catch (Exception ex) 
        { 
            Toast.makeText(con, "Error: " + ex, Toast.LENGTH_SHORT).show(); 
        } 
    } 
}