我正在开发一个应用程序,其中“更新程序”不断要求来自服务器的数据。如果它接收到新数据,则数据通过LocalBroadcast发送到活动。为此,我需要在构造函数中传递的当前Context。此外,新数据被写入Singleton类(通过应用程序的运行时存储它)。
问题是,我需要不断为我的LocalBroadcast新的Context,但它只在构造函数中传递了一次。是否有人知道每次LocalBroadcast发送内容时如何获取当前上下文?
我找到了这个答案,但我总是警告将上下文类放在静态字段中。 (Get application context from non activity singleton class)
感谢阅读和每一条建议。 这是我的“更新程序”代码:
<?php
# You should think about containing your connection inside a class or function
$server ="localhost";
$user ="root";
$password = "";
$db = "customers";
# This should be the class version of this library not the function
$con = new mysqli($server,$user,$password,$db);
# This part should work now
if($con->connect_errno){
die(json_encode(['success'=>false,'msg'=>"cannot connect to the database".$con->connect_error]));
}
# I'm gonna switch to post here...
$input = (!empty($_POST['name']))? trim($_POST['name']) : false;
# If it's empty, just stop
if(empty($input))
die(json_encode(['success'=>false,'msg'=>'Input is empty']));
# You have to bind parameters, this is a security hole
//$sql ="SELECT * FROM customers WHERE name = '$input'";
# Prepare the statement with a question mark as a placeholder
$query = $con->prepare("SELECT `name`,`contact` FROM customers WHERE name = ?");
# Put the value in here, indicating it is a string (s)
$query->bind_param('s',$input);
# Execute the query
$query->execute();
# Get the results from the query
$result = $query->get_result();
# Fetch the array as associative
$customer = $result->fetch_assoc();
# Add a success row in the array so the json parse is not malformed on return
$customer = (empty($customer))? ['success'=>false] : array_merge(['success'=>true],$customer);
# Print the string
die(json_encode($customer));
答案 0 :(得分:1)
更改
this.cntxt = context;
要
cntxt = context.getApplicationContext();
代替。其中cntxt
是静态上下文。它不会创建活动泄漏,因为它使用应用程序上下文。
如果您了解Android中的后台服务,那就更好了 https://developer.android.com/training/run-background-service/create-service.html