我的服务很新,所以请耐心等待。我正在尝试从我的broadcastreceiver启动服务类,但应用程序崩溃了。在我的broadcastreceiver中,我正在检查传入的短信并插入数据库,然后开始服务。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.anew"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.anew.MyBroadcast">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<action android:name="android.provider.Telephony.SMS_SENT" />
</intent-filter>
</receiver>
<service android:name=".LocalService" />
</application>
</manifest>
public class LocalService extends Service {
SQLiteDatabase db;
String resource, Time, Mesg, webResponse;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startid) {
// Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Cursor c=db.rawQuery("SELECT * FROM student WHERE id=(SELECT MIN(id) FROM student)", null);
if(c.getCount()==0){
Toast.makeText(getApplicationContext(), "No SMS found", Toast.LENGTH_SHORT).show();
}
else if(c.moveToNext()) {
Sender = c.getString(1);
TimeStamp = c.getString(2);
Mesg = c.getString(3);
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/createsms.asmx/broadcast?");
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(5);
nameValuePair.add(new BasicNameValuePair("a", "AB1"));
nameValuePair.add(new BasicNameValuePair("b", "IN"));
nameValuePair.add(new BasicNameValuePair("c", resource));
nameValuePair.add(new BasicNameValuePair("d", Time));
nameValuePair.add(new BasicNameValuePair("e", Mesg));
//Encoding POST data
try{
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
System.out.println(e);
}
//making POST request.
try{
HttpResponse response = httpClient.execute(httpPost);
String XmlString = EntityUtils.toString(response.getEntity());
XmlString=XmlString.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim();
XmlString = XmlString.substring(XmlString.indexOf("[") + 1, XmlString.lastIndexOf("]"));
JSONObject jObj = new JSONObject(XmlString);
webResponse = jObj.getString("status");
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
System.out.println(e);
} catch (IOException e) {
// Log exception
e.printStackTrace();
System.out.println(e);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // onStart ends
@Override
public void onDestroy() {
//Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}
public class MyBroadcast extends BroadcastReceiver {
Context mContext;
String msg_body;
String mob_no, name;
String dttm, key;
SQLiteDatabase db;
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
db=context.openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
StringBuffer content = new StringBuffer();
if (messages.length > 0) {
for (int i = 0; i < messages.length; i++) {
content.append(messages[i].getMessageBody());
mob_no = messages[i].getOriginatingAddress();
Calendar calendar = Calendar.getInstance();
Date finaldate = calendar.getTime();
dttm = finaldate.toString();
}
}
msg_body = content.toString();
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(mob_no));
Cursor c = context.getContentResolver().query(lookupUri, new String[]{ContactsContract.Data.DISPLAY_NAME},null,null,null);
try {
if(c.moveToFirst()) {
name = c.getString(0);
db.execSQL("INSERT INTO student (sender, timestamp, mesg) VALUES('"+name+"','"+dttm+"','"+msg_body+"');");
context.startService(new Intent(context,LocalService.class));
} else {
db.execSQL("INSERT INTO student (sender,timestamp,mesg) VALUES('"+mob_no+"','"+dttm+"','"+msg_body+"');");
context.startService(new Intent(context,LocalService.class));
}
} catch (Exception e) {
// TODO: handle exception
} finally {
c.close();
}
}
}
}
10-08 11:45:44.776: E/AndroidRuntime(15029): FATAL EXCEPTION: main
10-08 11:45:44.776: E/AndroidRuntime(15029): Process: com.example.anew, PID: 15029
10-08 11:45:44.776: E/AndroidRuntime(15029): java.lang.RuntimeException: Unable to start service com.example.anew.LocalService@41e40438 with Intent { cmp=com.example.anew/.LocalService }: java.lang.NullPointerException
10-08 11:45:44.776: E/AndroidRuntime(15029): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2923)
10-08 11:45:44.776: E/AndroidRuntime(15029): at android.app.ActivityThread.access$2100(ActivityThread.java:155)
10-08 11:45:44.776: E/AndroidRuntime(15029): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1428)
10-08 11:45:44.776: E/AndroidRuntime(15029): at android.os.Handler.dispatchMessage(Handler.java:110)
10-08 11:45:44.776: E/AndroidRuntime(15029): at android.os.Looper.loop(Looper.java:193)
10-08 11:45:44.776: E/AndroidRuntime(15029): at android.app.ActivityThread.main(ActivityThread.java:5388)
10-08 11:45:44.776: E/AndroidRuntime(15029): at java.lang.reflect.Method.invokeNative(Native Method)
10-08 11:45:44.776: E/AndroidRuntime(15029): at java.lang.reflect.Method.invoke(Method.java:515)
10-08 11:45:44.776: E/AndroidRuntime(15029): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-08 11:45:44.776: E/AndroidRuntime(15029): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:655)
10-08 11:45:44.776: E/AndroidRuntime(15029): at dalvik.system.NativeStart.main(Native Method)
10-08 11:45:44.776: E/AndroidRuntime(15029): Caused by: java.lang.NullPointerException
10-08 11:45:44.776: E/AndroidRuntime(15029): at com.example.anew.LocalService.onStart(LocalService.java:51)
10-08 11:45:44.776: E/AndroidRuntime(15029): at android.app.Service.onStartCommand(Service.java:450)
10-08 11:45:44.776: E/AndroidRuntime(15029): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2906)
10-08 11:45:44.776: E/AndroidRuntime(15029): ... 10 more
答案 0 :(得分:0)
下面:
Cursor c=db.rawQuery("SELECT * FROM student
WHERE id=(SELECT MIN(id) FROM student)", null);
db
对象是null
,因为在服务的任何地方都没有初始化。对象是:
db=LocalService.this.openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
Cursor c=db.rawQuery("SELECT * FROM student
WHERE id=(SELECT MIN(id) FROM student)", null);