在Android上点击按钮打开和关闭广播接收器

时间:2012-02-14 14:27:07

标签: android service sms

我正在做一个短信隐藏项目,这是广播接收器 代码如下:

package com.sms.sms;



public class ReceiverClass extends BroadcastReceiver 
{

SQLiteDatabase DiaryDB = null;
String message,number;
@Override
public void onReceive(Context context, Intent intent)
{



    Bundle bundle = intent.getExtras();
    SmsMessage[ ] msgs = null;
    String str = "";
    if (bundle != null)
    {
        abortBroadcast();
        //---retrieve the received message here ---
        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";
            message = msgs[i].getMessageBody().toString();
            number = msgs[i].getOriginatingAddress();
        }
       // ........first show sms here.....
       Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); 

       String name = findNameByAddress(context, number);
       if(name.equals(number))
           name = "Unknown";           

       DiaryDB = context.openOrCreateDatabase("DIARY_DATABASE", context.MODE_PRIVATE, null);

       DiaryDB.execSQL("CREATE TABLE IF NOT EXISTS Messages (TIMESTAMP DATE DEFAULT (DATETIME('now','localtime')), MESSAGE varchar, SENDER varchar, NAME varchar);");
System.out.println("table createdddddddddddddddddddddddddd");

       DiaryDB.execSQL("INSERT INTO Messages(MESSAGE,SENDER,NAME) VALUES('" + message +"','"+ number +"','"+ name +"')");

       DiaryDB.close();
       updateName(context,name, number);

   }



}  
 public String findNameByAddress(Context ct,String address)
    {
         Uri myPerson = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(address));

         String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME };

         Cursor cursor = ct.getContentResolver().query(myPerson, projection, null, null, null);

         if (cursor.moveToFirst())
         {

             String name=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

             Log.e("","Found contact name");

             cursor.close();

             return name;

         }

         cursor.close();
         Log.e("","Not Found contact name");

         return address;
    }

 public void updateName(Context ct, String name, String sender)
 {
     DiaryDB = ct.openOrCreateDatabase("DIARY_DATABASE", ct.MODE_PRIVATE, null);

     DiaryDB.execSQL("UPDATE Messages SET NAME='"+name+"' WHERE SENDER='"+sender+"'");

     DiaryDB.close();
 }

我的主Activity中有两个按钮ON和OFF。我需要的是,当我按下ON按钮它应该启动Bordcast接收器并应该开始隐藏短信,当我按下OFF按钮我需要停止(广播接收器)隐藏消息过程或应该短信回到收件箱* < em>(当广播接收器关闭时会发生) *。现在我如何开启和关闭Boardcast接收器流程请帮助

版本回答后

我的活动类//

package com.an.oid;



public class OnoffActivity extends Activity {
int count =0;
Button a,b;
 ReceiverClass rc ;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    a=(Button)findViewById(R.id.button1);
    b=(Button)findViewById(R.id.button2);

    rc= new ReceiverClass();
    a.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
             IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
             System.out.println("onnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn");



               registerReceiver(rc,filter);


        }
    });
    b.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

             unregisterReceiver(rc);
        }
    });
}
}

我的清单//

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.an.oid"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:label="@string/app_name"
        android:name=".OnoffActivity" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
 <uses-permission android:name="android.permission.SEND_SMS">
</uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />



</manifest>

获得anser后,我尝试了这个,但它没有用?

1 个答案:

答案 0 :(得分:4)

只有在使用

在活动级别(非Manifest)注册接收器时才可以这样做
registerReceiver(BroadcastReceiver, IntentFilter)

点击该按钮,您可以使用..

取消注册
unregisterReceiver(BroadcastReceiver receiver)

编辑II

//注册按钮

register.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

           IntentFilter filter = new IntentFilter(MY_ACTIVITY);
           Sms2Activity rc = new Sms2Activity();
           registerReceiver(rc,filter);

}
    });

//取消注册按钮

 unregister.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

              unregisterReceiver(rc);

    }
        });