我正在尝试创建一个 android 应用程序,该应用程序不断检查远程数据库中的新记录,并在添加新记录时提供通知。我想对添加的每条记录重复此操作。
到目前为止,我已经完成了以下操作创建了一个从数据库中获取数据的服务。任何人都可以建议在固定间隔后一次又一次地调用服务的最佳方法,或者保持服务正常运行并重复调用方法。什么会证明更好的表现?
我正在尝试创建一个 android 应用程序,该应用程序不断检查远程数据库中的新记录,并在添加新记录时提供通知。我想对添加的每条记录重复此操作。
到目前为止,我已经完成了以下操作创建了一个从数据库中获取数据的服务。任何人都可以建议在固定间隔后一次又一次地调用服务的最佳方法,或者保持服务正常运行并重复调用方法。什么会证明更好的表现?
不断检查远程数据库中的新记录将在您的应用程序中产生负载。
您可以使用 Google Cloud 到设备消息服务。每次远程数据库有新记录时,这都会向设备发送通知消息。
请检查:http: //developer.android.com/google/gcm/index.html
GCM 的步骤
1.在AndroidManifest.xml中添加以下权限和接收者
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.example.test.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.test.permission.C2D_MESSAGE" />
<receiver
android:name="com.example.test.MyBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.example.test" />
</intent-filter>
</receiver>
注意:查找并替换 com.example.test 为您的包名称
MyBroadcastReceiver.java
public class MyBroadcastReceiver extends BroadcastReceiver{
private static final String TAG = "GCM";
MyPrefs myPrefs ;
@Override
public void onReceive(Context context, Intent intent) {
myPrefs = new MyPrefs(context);
Log.d(TAG,"inside onReceive");
String action = intent.getAction();
if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
handleRegistration(context,intent);
} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(context,intent);
}
}
private void handleRegistration(Context context,Intent intent) {
String registrationId = intent.getStringExtra("registration_id");
String error = intent.getStringExtra("error");
String unregistered = intent.getStringExtra("unregistered");
// registration succeeded
if (registrationId != null) {
Log.d(TAG, "Device_reg_id : "+registrationId);
// store registration ID on shared preferences
myPrefs.putString("DEVICE_REG_ID", registrationId);
// notify 3rd-party server about the registered ID
generateNotification(context, "Registration Sucessful", "Device register sucessfully!");
}
// unregistration succeeded
if (unregistered != null) {
// get old registration ID from shared preferences
// notify 3rd-party server about the unregistered ID
}
// last operation (registration or unregistration) returned an error;
if (error != null) {
if ("SERVICE_NOT_AVAILABLE".equals(error)) {
// optionally retry using exponential back-off
// (see Advanced Topics)
} else {
// Unrecoverable error, log it
Log.i(TAG, "Received error: " + error);
}
}
}
private void handleMessage(Context context, Intent intent) {
String data = intent.getExtras().getString("data");
generateNotification(context, "New Message is received", data);
}
private void generateNotification(Context context,String title,String text) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(text);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getBroadcast(context,0,resultIntent, 0);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(0, mBuilder.build());
}
MainActivity.java
public class MainActivity extends Activity {
String device_reg_id;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyPrefs prefs = new MyPrefs(this);
device_reg_id = prefs.getString("DEVICE_REG_ID");
if (device_reg_id == null )
{
Log.d("GCM", "Registration start");
// registration
Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
// sets the app name in the intent
registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
registrationIntent.putExtra("sender", "1850XXXX2785");
startService(registrationIntent);
}else
{
// send a message to device its self
String api_key = "AIzaSyBXSJHPqFiYeYdAoYfN1XlI20Es";
Sender sender = new Sender(api_key);
Message message = new Message.Builder()
.collapseKey("1")
.timeToLive(3)
.delayWhileIdle(true)
.addData("data", "Welcome!")
.build();
Result result;
try {
result = sender.send(message, device_reg_id, 5);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
MyPrefs.java
public class MyPrefs {
private SharedPreferences sp;
private Editor editor;
public MyPrefs(Context context){
sp = PreferenceManager.getDefaultSharedPreferences(context);
editor = sp.edit();
}
public void putString(String key,String Value){
editor.putString(key,Value);
editor.commit();
}
public String getString(String key){
return sp.getString(key,null);
}
}
注意不要忘记从 sdk\extras\google\gcm\gcm-server\dist导入gcm-server.jar 。如果您在 sdk 中找不到路径,则在 Android SDK Manager 的 Extras 下安装 Google Cloud Messaging for Android Libaray