- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个从广播接收器启动的异步任务。
代码:
public static class SrvPositioning extends Service {
// An alarm for rising in special times to fire the
// pendingIntentPositioning
private AlarmManager alarmManagerPositioning;
// A PendingIntent for calling a receiver in special times
public PendingIntent pendingIntentPositioning;
Location location;
//GPSTracker gps;
@Override
public void onCreate() {
super.onCreate();
alarmManagerPositioning = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Intent intentToFire = new Intent(
ReceiverPositioningAlarm.ACTION_REFRESH_SCHEDULE_ALARM);
intentToFire.putExtra(ReceiverPositioningAlarm.COMMAND,
ReceiverPositioningAlarm.SENDER_SRV_POSITIONING);
pendingIntentPositioning = PendingIntent.getBroadcast(this, 0,
intentToFire, 0);
};
@Override
public void onStart(Intent intent, int startId) {
try {
long interval = 3000;//3 secs
System.out.println("Service called");
int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
long timetoRefresh = SystemClock.elapsedRealtime();
alarmManagerPositioning.setInexactRepeating(alarmType,
timetoRefresh, interval, pendingIntentPositioning);
//Toast.makeText(this, "SrvPositioning fired", Toast.LENGTH_SHORT).show();
} catch (NumberFormatException e) {
Toast.makeText(this,
"error running service: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this,
"error running service: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDestroy() {
this.alarmManagerPositioning.cancel(pendingIntentPositioning);
// ReceiverPositioningAlarm.stopLocationListener();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
public static class ReceiverPositioningAlarm extends BroadcastReceiver {
public static final String COMMAND = "SENDER";
public static final int SENDER_ACT_DOCUMENT = 0;
public static final int SENDER_SRV_POSITIONING = 1;
public static final String ACTION_REFRESH_SCHEDULE_ALARM =
"ACTION_REFRESH_SCHEDULE_ALARM";
//private static final Context _context=null;
String jsonStr="";
@Override
public void onReceive(final Context context, Intent intent) {
//Toast.makeText(context, "new request received by receiver",
//Toast.LENGTH_SHORT).show();
// create class object
//SessionManager s=new SessionManager(context);
//userid=s.getUserId();
System.out.println("RecieverPositioning Alarm");
//_context = context;
new ChatScreen().new GetPeriodicChat(recieverid).execute();
}
}
服务和广播接收器都是 ChatScreen 类的内部类。
我在 ChatScreen.java 的 onCreate() 中初始化了一个共享首选项,例如:
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.chatscreen2);
preftimestamp= ChatScreen.this.getSharedPreferences(Constants.ACCESS_TIMESTAMP, Context.MODE_PRIVATE);
现在,当我尝试在异步任务 GetPeriodicChat(recieverid)(从广播接收器启动的那个)的 doInBackground() 中访问此共享首选项时,我遇到了 NPE。
这是异步任务的代码:
public class GetPeriodicChat extends AsyncTask<String,String,String>{
String r_id="";
public GetPeriodicChat(String r_id) {
// TODO Auto-generated constructor stub
System.out.println("get periodic chat called");
chatlisthashmapperiodically = new ArrayList<HashMap<String, String>>();
preftimestamp= ChatScreen.this.getSharedPreferences(Constants.ACCESS_TIMESTAMP, Context.MODE_PRIVATE);
this.r_id=r_id;
}
protected void onPreExecute() {
super.onPreExecute();
try{
//showLoading(R.string.loading);
}catch(Exception e){
e.printStackTrace();
}
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
urlgetallchatmessage=Constants.getmessagetimestamp;
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("sender_id",userid));
nameValuePairs.add(new BasicNameValuePair("receiver_id",r_id));//rec
String last_timestamp =preftimestamp.getString(Constants.ACCESS_TIMESTAMP,null);
System.out.println("Last timestamp in periodically-->"+last_timestamp);
nameValuePairs.add(new BasicNameValuePair("last_timestamp",last_timestamp));
ServiceHandle sh = new ServiceHandle();
String jsonResponse = sh.makeServiceCall(urlgetallchatmessage, ServiceHandle.POST,nameValuePairs);
// after getting JSON string from the URL
System.out.println(""+ jsonResponse );
try {
if ( jsonResponse != null)
{
JSONObject c = new JSONObject( jsonResponse );
//JSONObject c = jsonObj;
successallchat=Integer.parseInt(c.getString("success"));
if(successallchat==1)
{
if(c.has(TAG_GETHISTORY_ARRAY)){
chatlistperiodically = c.getJSONArray(TAG_GETHISTORY_ARRAY);
// looping through All Contacts
for (int i = 0; i <chatlistperiodically.length(); i++) {
JSONObject j_chat = chatlistperiodically.getJSONObject(i);
String timestamp= j_chat.getString(TAG_TIMESTAMP);
String chatmessage= j_chat.getString(TAG_MESSAGE);
String sender_id= j_chat.getString(TAG_SENDER_ID);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_TIMESTAMP,timestamp);
map.put(TAG_MESSAGE,chatmessage);
map.put(TAG_SENDER_ID,sender_id);
SharedPreferences.Editor editor = preftimestamp.edit();
// System.out.println(projectid+"--->In Projectactivity");
editor.putString(Constants.ACCESS_TIMESTAMP,timestamp);
editor.commit();
//map.put(TAG_PDESC,pdetails);
chatlisthashmapperiodically.add(map);
}
}
}
}
else
{
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Server not responding!", Toast.LENGTH_SHORT).show();
}
});
}
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}//doInbacckground
@SuppressLint("NewApi")
protected void onPostExecute(String file_url) {
//removeLoading();
if(successallchat==1)
{
}
}//postexecute
}//Asynctask
我在异步任务的构造函数中 preftimestamp= ChatScreen.this.getSharedPreferences(Constants.ACCESS_TIMESTAMP, Context.MODE_PRIVATE);
行遇到 NPE。可能是什么问题?如果我没有在构造函数上定义异步任务,然后我也遇到了 NPE。请帮忙。
最佳答案
将您的 AsyncTask 更新为:
public class GetPeriodicChat extends AsyncTask<String,String,String>{
String r_id="";
public GetPeriodicChat(String r_id, Context context) {
...
// ************ Instead of ChatScreen.this pass Context object in constuctor and use it here.
preftimestamp= context.getSharedPreferences(Constants.ACCESS_TIMESTAMP, Context.MODE_PRIVATE);
...
}
}//Asynctask
用法:
new ChatScreen().new GetPeriodicChat(recieverid, context).execute();
将 Activity 上下文作为参数传递给 AsyncTask。除非您在 Activity 中定义静态上下文变量,否则您将无法访问 Activity 外部的 Activity 上下文,这不是最佳做法。
关于android - 无法访问从广播接收器启动的异步任务中的共享首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33820106/
关闭。这个问题是opinion-based 。目前不接受答案。 想要改进这个问题吗?更新问题,以便 editing this post 可以用事实和引文来回答它。 . 已关闭 4 年前。 Improv
PowerShell Web Access 允许您通过 Web 浏览器运行 PowerShell cmdlet。它显示了一个基于 Web 的控制台窗口。 有没有办法运行 cmdlet 而无需在控制台窗
我尝试在无需用户登录的情况下访问 Sharepoint 文件。 我可以通过以下任一方式获取访问 token 方法一: var client = new RestClient("https://logi
我目前正在尝试通过 Chrome 扩展程序访问 Google 服务。我的理解是,对于 JS 应用程序,Google 首选的身份验证机制是 OAuth。我的应用目前已成功通过 OAuth 向服务进行身份
假设我有纯抽象类 IHandler 和派生自它的类: class IHandler { public: virtual int process_input(char input) = 0; };
我有一个带有 ThymeLeaf 和 Dojo 的 Spring 应用程序,这给我带来了问题。当我从我的 HTML 文件中引用 CSS 文件时,它们在 Firebug 中显示为中止。但是,当我通过在地
这个问题已经有答案了: JavaScript property access: dot notation vs. brackets? (17 个回答) 已关闭 6 年前。 为什么这不起作用? func
我想将所有流量重定向到 https,只有 robot.txt 应该可以通过 http 访问。 是否可以为 robot.txt 文件创建异常(exception)? 我的 .htaccess 文件: R
我遇到了 LinkedIn OAuth2: "Unable to verify access token" 中描述的相同问题;但是,那里描述的解决方案并不能解决我的问题。 我能够成功请求访问 toke
问题 我有一个暴露给 *:8080 的 Docker 服务容器. 我无法通过 localhost:8080 访问容器. Chrome /curl无限期挂断。 但是如果我使用任何其他本地IP,我就可以访
我正在使用 Google 的 Oauth 2.0 来获取用户的 access_token,但我不知道如何将它与 imaplib 一起使用来访问收件箱。 最佳答案 下面是带有 oauth 2.0 的 I
我正在做 docker 入门指南:https://docs.docker.com/get-started/part3/#recap-and-cheat-sheet-optional docker-co
我正在尝试使用静态 IP 在 AKS 上创建一个 Web 应用程序,自然找到了一个带有 Nginx ingress controller in Azure's documentation 的解决方案。
这是我在名为 foo.js 的文件中的代码。 console.log('module.exports:', module.exports) console.log('module.id:', modu
我试图理解访问键。我读过https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-se
我正在使用 MGTwitterEngine"将 twitter 集成到我的应用程序中。它在 iOS 4.2 上运行良好。当我尝试从任何 iOS 5 设备访问 twitter 时,我遇到了身份验证 to
我试图理解访问键。我读过https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-se
我正在使用以下 API 列出我的 Facebook 好友。 https://graph.facebook.com/me/friends?access_token= ??? 我想知道访问 token 过
401 Unauthorized - Show headers - { "error": { "errors": [ { "domain": "global", "reas
我已经将我的 django 应用程序部署到 heroku 并使用 Amazon s3 存储桶存储静态文件,我发现从 s3 存储桶到 heroku 获取数据没有问题。但是,当我测试查看内容存储位置时,除
我是一名优秀的程序员,十分优秀!