如何从扩展的BroadcastReceiver类调用MainActivity函数

时间:2013-08-10 23:41:54

标签: android sms broadcastreceiver

我找不到这个问题的答案。 我正在构建一些基于短信服务的Android应用程序 我发现回调非常困难。 我希望/需要从函数MainActivity(类onReceive)内部调用我的主要应用程序类SMSReceiver。 Toast工作得很好但是任何调用public void OnSmsReceived()(类MainActivity)的尝试都不成功。

// Main class
public class MainActivity extends Activity {
  public void OnSmsReceived() {
    System.out.println(TAG + ": OnSmsReceived " + "OK ");
  }
  /* more not important at this moment code bellow */
}


// Brodcast class
public class SMSReceiver extends BroadcastReceiver {
  private static final String TAG = "SMSReceiver";
  @Override
  public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "SMS received.", Toast.LENGTH_LONG).show();
    System.out.println(TAG + ": " + "onReceive");

    //How to call MainActivity form here?

  }
}

4 个答案:

答案 0 :(得分:1)

好的,我最终完成了这项工作:
这是真正有效的代码
感谢您intent ...

//Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="sms.pack.sms201"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />
    <uses-permission android:name="android.permission.BROADCAST_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="sms.pack.sms201.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>        
        <receiver 
            android:name="sms.pack.sms201.SMSReceiver" 
            android:enabled="true" 
            android:exported="true" 
            android:permission="android.permission.BROADCAST_SMS"> 
            <intent-filter android:priority="1000"> 
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/> 
            </intent-filter> 
        </receiver>        
    </application>
</manifest>

//SMSReceiver class
public class SMSReceiver extends BroadcastReceiver {
  private static final String TAG = "SMSReceiver";
  public static String Test = "empty";
  @Override
  public void onReceive(Context context, Intent intent) {
    Log.v(TAG, "onReceive");
    Toast.makeText(context, "SMS received.", Toast.LENGTH_LONG).show();
    Bundle bundle = intent.getExtras();
    if( bundle != null) {
      Log.v(TAG, "onReceive.bundle != null");
      Test = String.valueOf(bundle.size());
    }    
    Intent callingIntent = new Intent(context, MainActivity.class);
    callingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    callingIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    String value = "Extra val=" + Test;
    callingIntent.putExtra("SMSR", value);
    context.startActivity(callingIntent);    
  }
}

//MainActivity class
public class MainActivity extends Activity {
  private static final String TAG = "MainActivity";
  TextView tvGenLog;    
    protected void appendGenLog(String txt) {
      txt = tvGenLog.getText() + txt + "\r\n";
        tvGenLog.setText(txt);
    }
    private String memberFieldString;
    @Override
  protected void onNewIntent(Intent intent) {
    appendGenLog(TAG + ".onNewIntent");
    memberFieldString = intent.getStringExtra("SMSR");
    appendGenLog("memberFieldString=" + memberFieldString);    
    appendGenLog("Take data from SMSReceiver,");    
    appendGenLog("SMSR=" + SMSReceiver.Test);    
    super.onNewIntent(intent);
    } // End of onNewIntent(Intent intent)
  @Override
  protected void onResume() { 
    super.onResume();   
    //appendGenLog(TAG + ".onResume");   
    if (getIntent()!=null && getIntent().getExtras()!=null) {
      appendGenLog(TAG + ".onResume" + ":" + getIntent().getExtras().getString("SMSR"));  
    }
      else {
      appendGenLog(TAG + ".onResume" + ": null");  
    }
  }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     
        Log.v(TAG, ".onCreate");        
        tvGenLog = (TextView) findViewById(R.id.tvGenLog);        
        appendGenLog(TAG + " Created");
    }   
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }    
}

答案 1 :(得分:0)

在onReceive方法中使用context并调用context.startActivity(context,yourActivity.class);

答案 2 :(得分:0)

你不能使用context.startActivity(context,MainActivity.class);

但您可以选择以下方法来解决此问题:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
context.startActivity(intent, bundle)

答案 3 :(得分:0)

我尝试了很多方法。

我没有说,但它是针对targetSdkVersion =“8”
你给我的一些功能在这个旧系统上没有用 我无法找到使用上下文和意图的工作方式。这总是导致崩溃。

我在MainActivity中找到了静态字段和功能的方法,即使是工作和打印的东西,它也会在那之后粉碎....

毕竟这对我很有用。
当然是草案,但这允许与主要班级合作。

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="sms.pack.sms0"
        android:versionCode="1"
        android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" /> 
    <uses-permission android:name="android.permission.BROADCAST_SMS"/>
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="sms.pack.sms0.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>         
    </application>
</manifest>

的strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">sms0</string>
    <string name="action_settings">Settings</string>
    <string name="sGenInfo">GenInfo</string>
</resources>

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/sms.pack.sms0"
    android:id="@layout/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/tvGenInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/sGenInfo" />    
</LinearLayout>

MainActivity.java

package sms.pack.sms0;

import android.util.Log;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
  private static final String TAG = "MainActivity";
  private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
  TextView tvGenInfo;  
  public void appendGenInfo(String txt) {  
    Log.v(TAG, "genLog, txt=" + txt);
    txt = tvGenInfo.getText() + txt + "\r\n";
    tvGenInfo.setText(txt);
  }  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);    
    Log.v(TAG, "onCreate");
    tvGenInfo = (TextView) findViewById(R.id.tvGenInfo);    
    IntentFilter filter = new IntentFilter(Intent.ACTION_DEFAULT);
    filter.addAction(SMS_RECEIVED);
    filter.setPriority(1000);
    this.registerReceiver(this.smsReceiver, filter);    
    appendGenInfo("Created");
  }
  private BroadcastReceiver smsReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) { 
      Log.v(TAG, "smsReceiver.onReceive, " + "");
      Toast.makeText(context, "smsReceiver.onReceive, " + "", Toast.LENGTH_SHORT).show();
      System.out.println(TAG + ", smsReceiver.onReceive, " + "");
      Bundle bundle = intent.getExtras();
      if( bundle != null) {
        System.out.println(TAG + ", smsReceiver.onReceive.bundle, size=" + bundle.size());
        appendGenInfo(TAG + ", smsReceiver.onReceive.bundle, " + "bundle.size=" + bundle.size());//this works
      }
    }
  };   
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }
}