2013-02-05 18 views
0

我想開發一個Android應用程序,我想在發出呼叫時從手機發送消息。我想訪問和啓動廣播接收器從一個活動,並做一些事情

目標號碼取自應用程序數據庫。

我已經完成了,直到那一部分,但我不能收聽廣播接收器在我的活動:

public class PARENT_CALLActivity extends Activity 
{ 
/** Called when the activity is first created. */ 

String PARENT=null; 
EditText edparent; 
Button submit; 
String parent_number; 

public static final String BROADCAST = "sha.pcall.android.action.broadcast"; 



@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 


    edparent=(EditText)findViewById(R.id.editText1); 
    submit=(Button)findViewById(R.id.btnsubmit); 


    submit.setOnClickListener(new OnClickListener() 
    { 

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


      PARENT=edparent.getText().toString(); 

      MyDabasehandler db=new MyDabasehandler(getApplicationContext()); 

      if(db.getContact().equals(null)) 
      { 
       db.addContact(new Contacts(PARENT)); 

      } 
      else 
      { 
       db.editContact(); 
      } 

      Intent intent = new Intent(getApplicationContext(),LocationUpdateReceiver.class); 
      sendBroadcast(intent); 

      finish(); 
     } 

    });  
} 

public class LocationUpdateReceiver extends BroadcastReceiver 
{ 

    @Override 
    public void onReceive(Context context, Intent intent) 
    { 

     String outgoing_number=intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); 

     Toast.makeText(context, outgoing_number, Toast.LENGTH_LONG).show(); 
    } 

    } 

} 
+0

你在哪裏註冊廣播接收機? – drulabs

+0

我如何註冊以及我必須在哪裏做...?可以üPLZ解釋說,關於 – ishaque

+0

我會爲此添加一個答案 – drulabs

回答

0

如果您是通過擴展廣播接收器創建一個單獨的類我建議你在一個單獨的類文件做。如果您只希望在活動開放的情況下接收廣播,請創建一個私人廣播接收器變量。像在這樣的問題:

Where to register a BroadcastReceiver (Activity lifecycle fun)

在後者的情況下可以用這種方法被稱爲registerreceiver廣播接收機變量寄存器。 Here is the link

這一切實際上取決於要求。如果你想接收廣播,即使您的應用程序被關閉(或活動不是在前臺),您需要註冊您的廣播接收器清單文件是這樣的:

<receiver 
     android:name="com.example.myapp.GCMBroadcastReceiver" 
     android:permission="com.google.android.c2dm.permission.SEND"> 
     <intent-filter> 
      <action android:name="com.google.android.c2dm.intent.RECEIVE" /> 
      <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> 
      <category android:name="com.example.myapp" /> 
     </intent-filter> 
    </receiver> 

這是谷歌的一個例子云消息廣播接收器。您還需要添加意圖過濾器,以指定您想要接收的廣播類型。在上面的例子中,廣播接收器可以接收(見的意圖過濾器標籤)兩個目的與行動:

"com.google.android.c2dm.intent.RECEIVE" 

"com.google.android.c2dm.intent.REGISTRATION" 

你用這個做了之後,你可以完成在您的任務覆蓋廣播接收器的onReceive()方法。

希望這會有所幫助。