Android AlarmManager无法启动活动

时间:2013-04-22 08:47:09

标签: java android service alarmmanager

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

P.S。

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

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

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

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

CODE SNIPPET :(不会使用字符串的值开始的闹钟:时间)

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

        }
    });





}};}

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

  }}

广播接收器来源:

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

2 个答案:

答案 0 :(得分:0)

PendingIntent.getActivity

应该是

PendingIntent.getService

无需解释,我认为你理解这里的区别,它是直截了当的!

编辑:

如果您想使用Activity开始AlarmManager,则应创建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发送数据。

答案 1 :(得分:0)

假设您的广播接收器不时触发自身。.

  1. 启动Intent之前,您需要所有适当的标志,如下所示:

    smartTime(time) {
      return time < 10 ? "0" + time.toString().trim() : time;
    }
    
  2. 在Manifest.xml中声明权限:

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

3。征得许可(最好在开始活动中)

3.1声明请求代码

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

3.2询问/检查权限

public static int OVERLAY_PERMISSION_REQUEST_CODE = 3249;

3.3权限回调

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