2013-11-05 6 views
0

Мое оригинальное приложение получает текст и использует разделение символов для разделения и отображения в текстовых изображениях. Затем я реализовал коды, чтобы вызывать активность из BroadcastReceiver, поэтому действие выводится на передний план при получении текстов, но текстовые просмотры приложения не обновляются.'' Launch MainActivity '' предотвращает отображение текстов

Если я удаляю из SMSReceiver.java, он работает нормально, но приложение не выводится на передний план.

//--Launch the MainActivity--// 
     Intent mainActivityIntent = new Intent(context, MainActivity.class); 
     mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     context.startActivity(mainActivityIntent); 

код SMSReceiver.java:

package com.example.smssend; 

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

public class SMSReceiver extends BroadcastReceiver 
{ 
    @Override 
    public void onReceive(Context context, Intent intent) 
    { 


//--Get the SMS Message passed in---// 
     Bundle bundle = intent.getExtras(); 
     SmsMessage[] msgs = null; 
     String str = ""; 
     if (bundle != null) 
     { 


//--Retrieve the SMS message received--// 
      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 += msgs[i].getMessageBody().toString(); 


} 
      //--Display the new SMS Message--// 
      Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); 
      String sender = null; 



//--Launch the MainActivity--// 
      Intent mainActivityIntent = new Intent(context, MainActivity.class); 


mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

    context.startActivity(mainActivityIntent); 


    //--Send a broadcast intent to update the SMS received in the activity--// 


    Intent broadcastIntent = new Intent(); 
      broadcastIntent.setAction("SMS_RECEIVED_ACTION"); 
      broadcastIntent.putExtra("sms", str); 
      context.sendBroadcast(broadcastIntent); 
     } 
    } 
} 

ответ

1

Возможно, когда вы посылаете broadcastIntent Активности не был загружен или переплетены любому приемнику пока.

Вы можете избежать проблем с передачей сообщения в своем mainActivityIntent вместо использования broadcastIntent для обновления Activity.

Вы можете восстановить намерение с помощью getIntent() в Activity и затем обновить интерфейс.

Intent mainActivityIntent = new Intent(context, MainActivity.class); 
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
mainActivityIntent.putExtra("sms", str); 
context.startActivity(mainActivityIntent); 

В вашей деятельности

@Override 
    protected void onResume() 
    { 
      super.onResume(); 
      Intent myIntent = getIntent(); 
      String sms = myIntent.getStringExtra("sms"); 
      if (sms != null && !"".equals(sms)) 
      { 
          mTextView.setText(sms); 
      } 
    } 

надежда, что это помогает :)

+0

Я добавил свой onResume() часть к моему MainActivity.java: Тем не менее, текст пока не отображается. @Override \t protected void onResume() { \t \t super.onResume(); \t \t Intent myIntent = getIntent(); \t \t Строка sms = myIntent.getStringExtra ("sms"); \t \t если (смс = NULL && "" равна (смс)!). { TextView mTextView = NULL; \t \t \t \t \t mTextView.setText (смс); } \t // - Зарегистрировать приемник - // \t registerReceiver (intentReceiver, intentFilter); \t super.onResume(); } – Joshua

+0

Можете ли вы выслать полный код своей деятельности? – jDur

0

код MainActivity:

package com.example.smssend; 

import android.app.Activity; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.os.Bundle; 
import android.telephony.SmsManager; 
import android.view.Menu; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 

public class MainActivity extends Activity { 


Button btnSendSMS; 
IntentFilter intentFilter; 
String textView1; 
String textView2; 
String textView3; 

private BroadcastReceiver intentReceiver = new BroadcastReceiver(){ 

    @Override 
    public void onReceive(Context context, Intent intent){ 
     //--Display the SMS received in the TextView1--// 

     TextView SMSes3 = (TextView) findViewById(R.id.textView1); 
     TextView SMSes2 = (TextView) findViewById(R.id.textView3); 
     TextView SMSes1 = (TextView) findViewById(R.id.textView2); 
     textView3 = intent.getExtras().getString("sms"); 
     char arr[] = textView3.toCharArray(); 
     String String1 = new String(arr); 
     String[] parts = String1.split(" "); 
     String part1 = parts[0]; 
     String part2 = parts[1]; 
     String part3 = parts[2]; 
     SMSes2.setText(part2); 
     SMSes1.setText(part1); 
     SMSes3.setText(part3); 

    } 
}; 

/** Called when the activity is first created. */ 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //--Intent to filter for SMS messages received--// 
    intentFilter = new IntentFilter(); 
    intentFilter.addAction("SMS_RECEIVED_ACTION"); 

    btnSendSMS = (Button) findViewById(R.id.btnSendSMS); 
    btnSendSMS.setOnClickListener(new View.OnClickListener() 
    { 
     @Override 
     public void onClick(View v) 
     { 
      sendSMS("92200026", "Hello"); 
     } 


    }); 
} 

@Override 
protected void onResume(){ 
    //--Register the receiver--// 
    registerReceiver(intentReceiver, intentFilter); 
    super.onResume(); 
} 

@Override 
protected void onPause(){ 
    //--Unregister the receiver--// 
    unregisterReceiver(intentReceiver); 
    super.onPause(); 
} 

//--Send an SMS message to another device---// 
private void sendSMS(String phoneNumber, String message) 
{ 
    SmsManager sms = SmsManager.getDefault(); 
    sms.sendTextMessage(phoneNumber, null, message, null, null); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

}

Смежные вопросы