Reputation: 81
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. 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. I'm sure I've overlooked something simple but I'm not sure what it might be.
P.S.
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:
time != null ? 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
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);
}
}
Upvotes: 2
Views: 3774
Reputation: 981
Assuming that you have a broadcast Receiver triggering itself now and then..
You need all appropriate flags for an Intent before you start it as given below:
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);
Declare permissions in Manifest.xml:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
3.Ask for the permission (in the starting activity preferably)
3.1 Declare request code
public static int OVERLAY_PERMISSION_REQUEST_CODE = 3249;
3.2 Ask/check permission
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
@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
}
}
}
Upvotes: 0
Reputation: 22064
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
. Then inside your Receiver
you should call startActivity(context, KillTimer.class);
Implementing the Receiver
. You will also need to add the Receiver
to your Manifest
, such as: <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
. Now, in time it would be better to create a Receiver
that can do multiple things. So if you wanted start different activities or whatever, you should also send data with the Intent
.
Upvotes: 1