无法让 AlarmManager 在 Galaxy III 或模拟器上工作
Cannot get AlarmManager to work at all on Galaxy III or an emulator
我浏览了两打样本、文章等,试图找出我的代码无法运行的原因。我有一个非常简单的广播监听器,我正试图与警报管理器通话。这是我的代码:
主要Activity onCreate 和函数(MapsActivity.java)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(240 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(80 * 1000); // 1 second, in milliseconds
Button clickButton = (Button) findViewById(R.id.search_for_beer);
clickButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent bar = new Intent(MapsActivity.this, SearchBeer.class);
bar.putExtra("tloc", Double.toString(location.getLongitude()) + "," + Double.toString(location.getLatitude()));
startActivity(bar);
}
});
startNotes();
}
public void startNotes() {
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(MapsActivity.this, BeerNotes.class);
PendingIntent pintent = PendingIntent.getService(MapsActivity.this, 12345, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + (5 * 1000), 5 * 1000, pintent);
}
我的 BroadcastReceiver ...我已经注释掉了我想要执行的代码,现在只是想获取日志,但我什么也没得到。
package com.tapmap.app.tapmapapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import java.io.InputStream;
import java.net.HttpURLConnection;
public class BeerNotes extends BroadcastReceiver {
private Exception exception;
private HttpURLConnection urlConnection;
public InputStream in;
private String total;
private static final long REPEAT_TIME = 1000 * 30;
private static final String APP_TAG = "LOG: ";
private static final int EXEC_INTERVAL = 20 * 1000;
@Override
public void onReceive(Context context, Intent intent) {
Log.i(APP_TAG, "onReceive() called");
/*
try {
URL url = new URL("http://fltapmap.com/notes.php");
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
in = new BufferedInputStream(urlConnection.getInputStream());
try {
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String line;
total = "";
while ((line = r.readLine()) != null) {
total += line + "\n";
}
urlConnection.disconnect();
Log.i("TOTAL NOTES", total);
} catch(IOException ioe) {
Log.i("MALFORMED1", ioe.getMessage());
urlConnection.disconnect();
}
} catch (IOException ioe) {
Log.i("MALFORMED2", ioe.getMessage());
urlConnection.disconnect();
}
} catch (MalformedURLException ioex) {
Log.i("MALFORMED3", ioex.getMessage());
}
*/
}
}
清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tapmap.app.tapmapapp" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="com.javapapers.android.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.javapapers.android.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
<meta-data
android:name="com.google.android.gms.version"
android:configChanges="orientation|screenSize"
android:screenOrientation="portrait"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAksheZLMAALUfLHKWOsfTFCz7iP_KwpCE" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".BarBrewry"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_bar_brewry"
android:theme="@style/FullscreenTheme" >
</activity>
<activity
android:name=".SearchBeer"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_search_beer"
android:theme="@style/FullscreenTheme" >
</activity>
<activity
android:name=".ViewBeer"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_search_beer"
android:theme="@style/FullscreenTheme" >
</activity>
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
<provider
android:name="com.facebook.FacebookContentProvider"
android:authorities="com.facebook.app.FacebookContentProvider934301593259187"
android:exported="true" />
<receiver
android:name="com.tapmap.app.tapmapapp.BeerNotes"></receiver>
</application>
</manifest>
将PendingIntent.getService()
更改为PendingIntent.getBroadcast()
编辑
我注意到您 BroadcastReceiver
中的注释代码将尝试发出网络请求。这将导致您的应用程序崩溃并出现 NetworkOnMainThread
异常。我建议您创建一个扩展 IntentService
的 class 并在 onHandleIntent()
内部进行网络操作。在这种情况下,您可以使用 PendingIntent.getService()
让意图转到服务。
我浏览了两打样本、文章等,试图找出我的代码无法运行的原因。我有一个非常简单的广播监听器,我正试图与警报管理器通话。这是我的代码:
主要Activity onCreate 和函数(MapsActivity.java)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(240 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(80 * 1000); // 1 second, in milliseconds
Button clickButton = (Button) findViewById(R.id.search_for_beer);
clickButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent bar = new Intent(MapsActivity.this, SearchBeer.class);
bar.putExtra("tloc", Double.toString(location.getLongitude()) + "," + Double.toString(location.getLatitude()));
startActivity(bar);
}
});
startNotes();
}
public void startNotes() {
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(MapsActivity.this, BeerNotes.class);
PendingIntent pintent = PendingIntent.getService(MapsActivity.this, 12345, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + (5 * 1000), 5 * 1000, pintent);
}
我的 BroadcastReceiver ...我已经注释掉了我想要执行的代码,现在只是想获取日志,但我什么也没得到。
package com.tapmap.app.tapmapapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import java.io.InputStream;
import java.net.HttpURLConnection;
public class BeerNotes extends BroadcastReceiver {
private Exception exception;
private HttpURLConnection urlConnection;
public InputStream in;
private String total;
private static final long REPEAT_TIME = 1000 * 30;
private static final String APP_TAG = "LOG: ";
private static final int EXEC_INTERVAL = 20 * 1000;
@Override
public void onReceive(Context context, Intent intent) {
Log.i(APP_TAG, "onReceive() called");
/*
try {
URL url = new URL("http://fltapmap.com/notes.php");
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
in = new BufferedInputStream(urlConnection.getInputStream());
try {
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String line;
total = "";
while ((line = r.readLine()) != null) {
total += line + "\n";
}
urlConnection.disconnect();
Log.i("TOTAL NOTES", total);
} catch(IOException ioe) {
Log.i("MALFORMED1", ioe.getMessage());
urlConnection.disconnect();
}
} catch (IOException ioe) {
Log.i("MALFORMED2", ioe.getMessage());
urlConnection.disconnect();
}
} catch (MalformedURLException ioex) {
Log.i("MALFORMED3", ioex.getMessage());
}
*/
}
}
清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tapmap.app.tapmapapp" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="com.javapapers.android.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.javapapers.android.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
<meta-data
android:name="com.google.android.gms.version"
android:configChanges="orientation|screenSize"
android:screenOrientation="portrait"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAksheZLMAALUfLHKWOsfTFCz7iP_KwpCE" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".BarBrewry"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_bar_brewry"
android:theme="@style/FullscreenTheme" >
</activity>
<activity
android:name=".SearchBeer"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_search_beer"
android:theme="@style/FullscreenTheme" >
</activity>
<activity
android:name=".ViewBeer"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_search_beer"
android:theme="@style/FullscreenTheme" >
</activity>
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
<provider
android:name="com.facebook.FacebookContentProvider"
android:authorities="com.facebook.app.FacebookContentProvider934301593259187"
android:exported="true" />
<receiver
android:name="com.tapmap.app.tapmapapp.BeerNotes"></receiver>
</application>
</manifest>
将PendingIntent.getService()
更改为PendingIntent.getBroadcast()
编辑
我注意到您 BroadcastReceiver
中的注释代码将尝试发出网络请求。这将导致您的应用程序崩溃并出现 NetworkOnMainThread
异常。我建议您创建一个扩展 IntentService
的 class 并在 onHandleIntent()
内部进行网络操作。在这种情况下,您可以使用 PendingIntent.getService()
让意图转到服务。