我想使用broadcastreceiver来开始一项活动

时间:2013-07-27 13:42:22

标签: android broadcastreceiver

我在Android 2.2.1上运行我的应用程序,我正在使用broadcastreceiver在我的屏幕解锁后立即开始活动。这不会发生......任何人都可以帮助我 这是我的代码

import com.example.app.MainActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import android.app.Activity;

public class ScreenReceiver extends BroadcastReceiver {
    Activity ac = new Activity();@Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            //Toast.makeText(context, "action received", Toast.LENGTH_LONG).show();
            Intent i = new Intent();
            i.setClass(context, MainActivity.class);
            ac.startActivity(i);
        }
    }
}

       <receiver android:name="ScreenReceiver">
         <intent-filter>

            <action android:name="android.intent.action.SCREEN_ON"/>
               </intent-filter>
            </receiver>

1 个答案:

答案 0 :(得分:0)

您绝不应使用Activity实例化new。这是纠正你应该怎么做的。只需使用方法参数context

public class ScreenReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            Intent i = new Intent(context, MainActivity.class);
            context.startActivity(i);
        }
    }
}