在onReceive BroadcastReceiver中启动Activity

72

我想在onReceive()方法中启动一个活动。

package com.splashscreenactivity;

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 {

    public static String trigger_message = "";

    @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 += "SMS from " + msgs[i].getOriginatingAddress();
                str += " :";
                trigger_message = msgs[i].getMessageBody().toString();
                str += trigger_message;
                str += "\n";
            }
            // ---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
            if (trigger_message.equals("dx")) {
                Toast.makeText(context, "I am triggered", Toast.LENGTH_LONG)
                        .show();
                // /////////////////////////
                // i want to start here
                // ////////////////////////
                // MainScreenActivity.trigger="Now";
                // Intent i = new Intent(context,GPS.class);
                // i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                // context.startActivity(i);
            } else {
                Toast.makeText(context, "I am not triggered,  Bbyz!!!",
                        Toast.LENGTH_LONG).show();
            }
        }
    }
}

这里是GPS.class。

package com.splashscreenactivity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.widget.TextView;
import android.widget.Toast;

public class GPS extends Activity implements LocationListener {

    TextView latitude, logitude;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gps);
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f,
                this);
        Toast.makeText(this, "i m started", Toast.LENGTH_LONG);
        // latitude = (TextView)findViewById(R.id.txtLat);
        // logitude = (TextView)findViewById(R.id.txtLongi);
        // latitude.setText("Loading...");
        // logitude.setText("Loading...");
    }

    String LATTITUDE;
    String LOGITUDE;

    @Override
    public void onLocationChanged(Location location) {
        double lat = location.getLatitude();
        double lag = location.getLongitude();
        LATTITUDE = Double.toString(lat);
        LOGITUDE = Double.toString(lag);
        // latitude.setText(LATTITUDE);
        // logitude.setText(LOGITUDE);
        // SmsManager sm = SmsManager.getDefault();
        // // here is where the destination of the text should go
        // String number = "5556";
        // sm.sendTextMessage(number, null,
        // "latitude="+latitude.getText()+"\nlongitude="+logitude.getText(),
        // null, null);
    }

    @Override
    public void onProviderDisabled(String arg0) {
    }

    @Override
    public void onProviderEnabled(String arg0) {
    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    }
    // /** Register for the updates when Activity is in foreground */
    // @Override
    // protected void onResume()
    // {
    // super.onResume();
    // lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f,
    // this);
    // }
    //
    // /** Stop the updates when Activity is paused */
    // @Override
    // protected void onPause() {
    // super.onPause();
    // lm.removeUpdates(this);
    // }
}

1
你遇到了什么问题? - Mark Fisher
你已经有启动活动的代码了。只需取消注释即可。 - jamapag
1
实际上,在onReceive方法中,startActivity方法无法工作,因为该类没有扩展Activity。 - Abhishek Gupta
1
取消此代码的注释后,我的模拟器强制退出。 - Abhishek Gupta
请将logcat中的堆栈跟踪信息发布出来,以便我们了解错误的详细信息。 - Vladimir Ivanov
3个回答

150

您将上下文作为参数传递给onRecieve()方法,所以只需使用:

 @Override
    public void onReceive(Context context, Intent intent) {
        //start activity
        Intent i = new Intent();
        i.setClassName("com.test", "com.test.MainActivity");
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }

它可以工作,当然你需要将包和活动类名称更改为你自己的。


抱歉,我不明白,请您详细说明一下! - Abhishek Gupta
@piotrpo 如果我从清单文件中注册我的广播接收器,那么我可以使用context.getApplicationContext.startActivity()从广播接收器类启动活动吗?但是我的应用程序崩溃了。 - user3233280
我认为你应该在这里寻求解决方案并粘贴你的崩溃日志。 - piotrpo
不适用于KitKat版本。我已经检查过,它可以在19以上的所有版本上工作,但无法在KitKat版本上工作。 - Reza Taghizadeh
1
@piotrpo 但是如果你在MyApplication类中注册你的广播接收器,它就不起作用了。 - Dr.jacky
显示剩余3条评论

30

我正在使用这个,它可以在我的网站上工作:

Intent intentone = new Intent(context.getApplicationContext(), DialogAct.class);
intentone.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intentone);

它不起作用了...新的活动启动时带有其他活动的后退堆栈。活动堆栈没有清除...还有其他建议吗! - CoDe

6
Intent intent1 = new Intent();
intent1.setClassName(context.getPackageName(), MainActivity.class.getName());
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);

为了防止这些软件包异常。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接