简体   繁体   English

Android AlarmManager 不启动 Activity

[英]Android AlarmManager Does Not Start Activity

I have 2 instances of AlarmManager built into my source code - the 2nd of which is supposed to start an Activity at the time specified by the string: time.我的源代码中内置了 2 个 AlarmManager 实例 - 其中第 2 个实例应该在字符串指定的时间启动 Activity:time。 The textview displays the correct time for the string: time however it never appears to start the 2nd AlarmManager's Activity (KillTimer.java) and I'm not sure why. textview 显示字符串的正确时间: time 但是它似乎从未启动第二个 AlarmManager 的 Activity (KillTimer.java),我不知道为什么。 I'm sure I've overlooked something simple but I'm not sure what it might be.我确定我忽略了一些简单的事情,但我不确定它可能是什么。

PS聚苯乙烯

I think it may have to do with the way I've implemented the time string - but I'm really not sure.我认为这可能与我实现时间字符串的方式有关 - 但我真的不确定。

The time string should represent which can be multiplied by 1000 on the following line:时间字符串应表示可以在以下行中乘以 1000 的时间:

time != null ?时间 != null ? 1000 : 0, pintent2); 1000 : 0, pintent2);

However the source code never recognizes it and the Alarm never wakes the activity as it did before I added the string for time.然而,源代码永远不会识别它,并且警报永远不会像在我添加时间字符串之前那样唤醒活动。

CODE SNIPPET: (Alarm which will not start using the value of the string: time)代码片段:(不会开始使用字符串值的警报:时间)

 // Start 2nd service using AlarmManager


    Intent intent2 = new Intent(Rules.this, KillTimer.class);
    PendingIntent pintent2 = PendingIntent.getActivity(Rules.this, 0, intent2,
            0);
    AlarmManager alarm2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm2.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            (time != null ? 1000 : 0), pintent2);   

FULL SOURCE:完整来源:

public class Rules extends Activity {
    private String password;
    private  PendingIntent mPendingIntent;
    String TIMELIMIT = "10";


TextView textSsid, textSpeed, textRssi, Time;
//Notification message ID
private static final int NOTIFY_ME_ID=1337;

private int count=0;
private NotificationManager notifyMgr=null;
    public Handler mHandler = new Handler();
    public long mStartRX = 0;
    public long mStartTX = 0;
    public long txBytes;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.rules);

    String NDEF_PREF = "prefs";
    SharedPreferences prefs = getSharedPreferences(NDEF_PREF, Context.MODE_PRIVATE); 
    String name = prefs.getString("name", ""); 
    String code = prefs.getString("corename", "");

    String time = prefs.getString("time", "");
    String ssid = prefs.getString("restricted", "");
    Time = (TextView) findViewById(R.id.Time);
    Time.setText(time);


   Parse.initialize(this, "7gjqmUcoqu1IZPJSSxXLdE4L8efAugCXA7snLSH6", "5NckF83MUBumQ8L8zL7Akc4p07beMRnmvgCfhZdH");

    ParseUser.enableAutomaticUser();
    ParseACL defaultACL = new ParseACL();


    defaultACL.setPublicReadAccess(true);

    ParseACL.setDefaultACL(defaultACL, true);

textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Time = (TextView) findViewById(R.id.Time);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);    
ParseAnalytics.trackAppOpened(getIntent());



mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Uh Oh!");
    alert.setMessage("Your device does not support traffic stat monitoring.");
    alert.show();
} else {
    mHandler.postDelayed(mRunnable, 1000);
}

}

private final Runnable mRunnable = new Runnable() {
public void run() {
    TextView RX = (TextView)findViewById(R.id.RX);      TextView TX = (TextView)findViewById(R.id.TX);

        long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
        RX.setText(Long.toString(rxBytes));
        long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
        TX.setText(Long.toString(txBytes));
        mHandler.postDelayed(mRunnable, 1000);


        final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
        myChronometer.start();



        DisplayWifiState();
        this.registerReceiver(this.myWifiReceiver, new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION));

    }

    private void registerReceiver(BroadcastReceiver myWifiReceiver2,
            IntentFilter intentFilter) {
        // TODO Auto-generated method stub

    }

    private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            // TODO Auto-generated method stub
            NetworkInfo networkInfo = (NetworkInfo) arg1
                    .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                DisplayWifiState();
            }
        }
    };

    public void DisplayWifiState() {

        ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo myNetworkInfo = myConnManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();

        if (myNetworkInfo.isConnected()) {

            textSsid.setText(myWifiInfo.getSSID());


            textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed()) + " "
                    + WifiInfo.LINK_SPEED_UNITS);
            textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
        } else {
            textSsid.setText("---");

            textSpeed.setText("---");
            textRssi.setText("---");
        };

    // Start service using AlarmManager

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, 10);
        Intent intent = new Intent(Rules.this, LMW.class);
        PendingIntent pintent = PendingIntent.getService(Rules.this, 0, intent,
                0);
        AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                7 * 1000, pintent);



        String NDEF_PREF = "prefs";
        SharedPreferences prefs = getSharedPreferences(NDEF_PREF, Context.MODE_PRIVATE); 
        String name = prefs.getString("name", ""); 
        String code = prefs.getString("corename", "");
        String time = prefs.getString("time", "");
        String ssid = prefs.getString("restricted", "");

        //String time = String.valueOf(time);




        // Start 2nd service using AlarmManager


        Intent intent2 = new Intent(Rules.this, KillTimer.class);
        PendingIntent pintent2 = PendingIntent.getActivity(Rules.this, 0, intent2,
                0);
        AlarmManager alarm2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarm2.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                (time != null ? 1000 : 0), pintent2);   




    // click listener for the button to start service
    Button btnStart = (Button) findViewById(R.id.button1);
    btnStart.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            startService(new Intent(getBaseContext(), LMW.class));            
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);



        }        

});

    // click listener for the button to stop service
    Button btnStop = (Button) findViewById(R.id.button2);
    btnStop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            stopService(new Intent(getBaseContext(), LMW.class));
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);

        }
    });





}};}

KILLTIMER.JAVA杀戮计时器.JAVA

public class KillTimer extends Activity {

    @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.killtimer);
      Toast.makeText(getApplicationContext(), "KillWifi Running!", Toast.LENGTH_SHORT).show();
      WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
      int networkId = wifiManager.getConnectionInfo().getNetworkId();
      wifiManager.removeNetwork(networkId );
      wifiManager.saveConfiguration();

  }}

Broadcast Receiver Source:广播接收器来源:

import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class StartKillTimerReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        startActivity(context, KillTimer.class);
    }
}
PendingIntent.getActivity

should be应该

PendingIntent.getService

No need to explain, I think you understand the difference here, it's kind of straight forward!无需解释,我想你明白这里的区别,这很简单!

EDIT:编辑:

If you want to start an Activity with AlarmManager you should create a BroadcastReceiver and use the method PendingIntent.getBroadcast .如果您想使用AlarmManager启动Activity ,您应该创建一个BroadcastReceiver并使用PendingIntent.getBroadcast方法。 Then inside your Receiver you should call startActivity(context, KillTimer.class);然后在你的Receiver里面你应该调用startActivity(context, KillTimer.class);

Implementing the Receiver .实现Receiver You will also need to add the Receiver to your Manifest , such as: <receiver android:name=".StartKillTimerReceiver" />您还需要将Receiver添加到您的Manifest ,例如: <receiver android:name=".StartKillTimerReceiver" />

public class StartKillTimerReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        context.startActivity(context, KillTimer.class);
    }
}

Remember that this Receiver has only one job to do, and that is to start your KillTimer .请记住,此Receiver只有一项工作要做,那就是启动您的KillTimer Now, in time it would be better to create a Receiver that can do multiple things.现在,及时创建一个可以做多种事情的Receiver会更好。 So if you wanted start different activities or whatever, you should also send data with the Intent .因此,如果您想开始不同的活动或其他活动,您还应该使用Intent发送数据。

Assuming that you have a broadcast Receiver triggering itself now and then..假设您有一个广播接收器时不时地触发自己..

  1. You need all appropriate flags for an Intent before you start it as given below:在启动 Intent 之前,您需要所有合适的标志,如下所示:

     Intent i = new Intent(Intent.ACTION_MAIN); i.setComponent(new ComponentName(this, Ring.class)); i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(i);
  2. Declare permissions in Manifest.xml:在 Manifest.xml 中声明权限:

     <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

3.Ask for the permission (in the starting activity preferably) 3.征得许可(最好在开始活动中)

3.1 Declare request code 3.1 声明请求代码

public static int OVERLAY_PERMISSION_REQUEST_CODE = 3249;

3.2 Ask/check permission 3.2 询问/检查权限

                new AlertDialog.Builder(this)
                    .setTitle("Display On Top permission")
                    .setMessage("Please grant the \"Display On Top\" permission.")
                    .setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Prompt the user once explanation has been shown
                            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                                    Uri.parse("package:" + getPackageName()));
                            startActivityForResult(intent, OVERLAY_PERMISSION_REQUEST_CODE);
                        }
                    })
                    .create()
                    .show();

3.3 Permission callback 3.3 权限回调

    @TargetApi(Build.VERSION_CODES.M)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == OVERLAY_PERMISSION_REQUEST_CODE) {
        if (!Settings.canDrawOverlays(this)) {
            // You don't have permission
            checkPermission();
        } else {
            // Do as per your logic
        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM