我编写的应用程序将来自android的拨出电话号码发送到服务器。
这是我的代码:
service.java
package info;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class ServiceToSendData extends Service {
// private static final String TAG = "HelloService";
public static boolean isRunning = false;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
isRunning = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
}
}).start();
return Service.START_STICKY;
}
@Override
public void onDestroy() {
isRunning = false;
}
}
outgoingCall Reciver
import org.json.JSONException;
import org.json.JSONObject;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.StrictMode;
public class OutgoingCallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
// Log.i("Outgoing Call", "call to: " + phoneNumber);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("type", "outgoingCall");
}
catch (JSONException e) {
e.printStackTrace();
}
try {
jsonObject.put("number", phoneNumber);
}
catch (JSONException e) {
e.printStackTrace();
}
try {
jsonObject.put("content", "0");
}
catch (JSONException e) {
e.printStackTrace();
}
if (phoneNumber != null) {
sendDataToServer sdts = new sendDataToServer();
sdts.run(jsonObject, context);
}
Intent startServiceIntent = new Intent(context, ServiceToSendData.class);
context.startService(startServiceIntent);
}
}
解释问题
1 - 如果应用程序处于打开状态或应用程序已最小化,此代码可以正常工作,但是当我关闭应用程序代码无效时,以及nullpointerexception问题?
2 - 从服务中使用上下文访问数据库的任何方式吗?
提前感谢。