这是一个场景:我的app,执行与mysql db的连接,其中另一个用户写入数据。我的应用程序只有在必要时才能连接到db,因此用户激活侦听器,如果在服务器端,db包含特定数据,则发出通知并停止侦听。我已经实现了提供通知和后台服务的功能,但我不知道如何通过asynctask将数据发送到php文件,因为要发送到asynctask查询的数据不是相同的但每次都要改变。所以我想,当用户发送第一个请求时,应用程序会写入要在首选项文件上发送的数据,因此每当后台服务进行新的调用时,它都会读取params以从首选项发送到文件php。 还有其他解决方案吗? 有人可以帮助我解释每次警报激活服务时如何拨打首选项吗? 我使用过这段代码:
在主要活动中
public void start() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 8000;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
AlarmReceiver类
public class AlarmReceiver extends BroadcastReceiver{
SharedPreferences sharedPreferences;
String userid;
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Service Ok", Toast.LENGTH_SHORT).show();
//Only to know that it was tested and works properly!
// Here I should read preferences from preference file and
// call asynctask that receives json result. If it's 1 it
// call a procedure for notification and then erase data
// and stops service, otherwise it wait for a new call
// every 5 minutes
}
}
对不起我的长篇帖子,我希望能得到你们的帮助。 提前谢谢。
答案 0 :(得分:1)
你可以在android中使用HttpClient,
查看示例发布到服务器调用
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.example.com");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", "test_user"));
nameValuePair.add(new BasicNameValuePair("password", "123456789"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
try {
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
别忘了提及
<uses-permission android:name="android.permission.INTERNET" />
这是共享偏好调用
SharedPreferences sharedpreferences = getSharedPreferences("myPreference", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
获取字符串
String value = preferences.getString("key", "DEFAULT");
在onreceive中调用共享首选项就像在下面
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences prefs = context.getSharedPreferences("myPreference",
Context.MODE_PRIVATE);
}