2

我的源代码中内置了 2 个 AlarmManager 实例 - 其中第 2 个实例应该在字符串指定的时间启动 Activity:时间。textview 显示字符串的正确时间: time 但是它似乎从未启动第二个 AlarmManager 的 Activity (KillTimer.java),我不知道为什么。我确定我忽略了一些简单的事情,但我不确定它可能是什么。

附言

我认为这可能与我实现时间字符串的方式有关——但我真的不确定。

时间字符串应表示可以在以下行中乘以 1000:

时间!=空?1000:0,品脱2);

但是,源代码永远不会识别它,并且警报永远不会像我添加时间字符串之前那样唤醒活动。

代码片段:(不会使用字符串值启动的警报:时间)

 // 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);   

完整来源:

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);

        }
    });





}};}

杀手计时器

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();

  }}

广播接收源:

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);
    }
}
4

2 回答 2

1
PendingIntent.getActivity

应该

PendingIntent.getService

不用解释,我想你明白这里的区别,它有点直截了当!

编辑:

如果你想从一个开始ActivityAlarmManager你应该创建一个BroadcastReceiver并使用方法PendingIntent.getBroadcast。然后在你的里面Receiver你应该打电话startActivity(context, KillTimer.class);

实施Receiver. 您还需要将 添加Receiver到您的Manifest中,例如:<receiver android:name=".StartKillTimerReceiver" />

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

请记住,这Receiver只有一项工作要做,那就是启动您的KillTimer. 现在,及时创建一个Receiver可以做多种事情的人会更好。因此,如果您想开始不同的活动或其他任何活动,您还应该使用Intent.

于 2013-04-22T09:05:19.723 回答
0

假设您有一个广播接收器不时触发自身..

  1. 在启动 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. 在 Manifest.xml 中声明权限:

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

3.请求许可(最好在开始活动中)

3.1 声明请求代码

public static int OVERLAY_PERMISSION_REQUEST_CODE = 3249;

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 权限回调

    @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
        }

    }

}
于 2020-12-02T14:32:26.617 回答