0

我喜欢在用户解锁手机时让应用程序启动服务。当我开始解锁手机时,什么也没有发生,当我登录应用程序时(登录后它将运行ThirdActivity.java),应用程序被强制停止。错误日志显示如下:

11-28 14:28:52.846: E/AndroidRuntime(6439): FATAL EXCEPTION: main
11-28 14:28:52.846: E/AndroidRuntime(6439): java.lang.RuntimeException: Unable to start  activity    ComponentInfo{com.example.android.project/com.example.android.project.ThirdActivity}:   java.lang.NullPointerException: println needs a message
11-28 14:28:52.846: E/AndroidRuntime(6439):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2205)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2240)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at android.app.ActivityThread.access$600(ActivityThread.java:139)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at android.os.Looper.loop(Looper.java:156)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at android.app.ActivityThread.main(ActivityThread.java:4987)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at java.lang.reflect.Method.invokeNative(Native Method)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at java.lang.reflect.Method.invoke(Method.java:511)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at dalvik.system.NativeStart.main(Native Method)
11-28 14:28:52.846: E/AndroidRuntime(6439): Caused by: java.lang.NullPointerException: println needs a message
11-28 14:28:52.846: E/AndroidRuntime(6439):     at android.util.Log.println_native(Native Method)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at android.util.Log.d(Log.java:138)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at com.example.android.project.ThirdActivity.onCreate(ThirdActivity.java:52)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at android.app.Activity.performCreate(Activity.java:4538)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
11-28 14:28:52.846: E/AndroidRuntime(6439):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2161)
11-28 14:28:52.846: E/AndroidRuntime(6439):     ... 11 more

在我添加以下代码之前,它照常运行:

    intentFilter = new IntentFilter();
    intentFilter.addAction(MyService.MY_ACTION);
    registerReceiver(intentReceiver, intentFilter);

    private BroadcastReceiver intentReceiver = new BroadcastReceiver() {...};
    protected void displayNotification(){...}

有人对这个问题有什么建议吗?

这是 StartMyServiceAtBootReceiver.java

public class StartMyServiceAtBootReceiver extends BroadcastReceiver{

    public void onReceive(Context context, Intent intent) {
          if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
                 HttpTest(context);                             
           }
     }

    public static boolean isNetworkAvailable( Context startMyServiceAtBootReceiver ) {
        Context context = startMyServiceAtBootReceiver.getApplicationContext();
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
        return false;
        } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
        for (int i = 0; i < info.length; i++) {
        if (info[i].getState() == NetworkInfo.State.CONNECTED) {
        return true;
        }
        }
        }
        }
        return false;
        } 

    public static void HttpTest( final Context startMyServiceAtBootReceiver)
    {
    if(isNetworkAvailable( startMyServiceAtBootReceiver) ){

         Intent start = new Intent(startMyServiceAtBootReceiver, MyService.class);
         start.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         startMyServiceAtBootReceiver.startService(start);
    }
    }

  }

我的服务.java

public class MyService extends Service{

int counter = 0;
static final int UPDATE_INTERVAL = 15000;
private Timer timer = new Timer();
DefaultHttpClient httpclient;
HttpPost httppost;
String line,result;
HttpResponse response;
InputStream is;
BufferedReader reader;
StringBuilder sb;
final static String MY_ACTION = "MY_ACTION";

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}


public int onStartCommand(Intent intent, int flags, int startId){
    doSomethingRepeatedly();
    return START_STICKY;        
}

private void doSomethingRepeatedly(){
    timer.scheduleAtFixedRate(new TimerTask(){
        public void run(){
        //  Log.d("MyService", String.valueOf(++counter));
            try{
             httpclient = new DefaultHttpClient();
                httppost = new HttpPost("http://www.kryptoquest.com/testing/checking.php");
                response = httpclient.execute(httppost);
                is = response.getEntity().getContent();
        }catch(Exception e){
            Log.e("log_tag", "Error:"+e.toString());
        }

        //convert response to string
        try{
                    reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                sb = new StringBuilder();
                line = null;
                while ((line = reader.readLine()) != null) {

                        sb.append(line + "\n");

                }
                Log.d("test",sb.toString());
                is.close();

                result = sb.toString();

             Intent intent = new Intent();
             intent.setAction(MY_ACTION);

             intent.putExtra("DATAPASSED", result);

             sendBroadcast(intent);


        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }
        }
    },10000,UPDATE_INTERVAL);
}




public void onDestroy(){
    super.onDestroy();

    if(timer != null){
        timer.cancel();
    }

    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
}

  }

第三活动.java

public class ThirdActivity extends ListActivity{
Bundle b;
String user,line,result,datapassed;
DefaultHttpClient httpclient;
HttpPost httppost;
HttpResponse response;
InputStream is = null;
BufferedReader reader;
StringBuilder sb;
ArrayList<NameValuePair> nameValuePairs;
ListView lv;
IntentFilter intentFilter;
int notification = 1;
String str = "";
String[] data;
int dlength;


public void onCreate(Bundle savedInstancesState){
    super.onCreate(savedInstancesState);
    setContentView(R.layout.list_screen);
    lv = (ListView) findViewById(android.R.id.list);
    Log.d("dg",user);
    getList();
    intentFilter = new IntentFilter();
    intentFilter.addAction(MyService.MY_ACTION);
    registerReceiver(intentReceiver, intentFilter);
    user = getIntent().getExtras().getString("user");
}

    public void getList(){
    new Thread(){
        public void run(){
            try{
                 httpclient = new DefaultHttpClient();
                 httppost = new HttpPost("http://www.kryptoquest.com/tracker/friendlist.php");
                 response = httpclient.execute(httppost);
                 is = response.getEntity().getContent();
            }catch(Exception e){
                Log.e("log_tag", "Error:"+e.toString());
            }

            //convert response to string
            try{
                    reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                    sb = new StringBuilder();
                    line = null;
                    while ((line = reader.readLine()) != null) {

                            sb.append(line + "\n");

                    }
                    Log.d("test",sb.toString());
                    is.close();

                    result = sb.toString();

                    final String[] friend = result.split("[*]");

                    runOnUiThread(new Runnable()
                    {
                        public void run(){                              
                            setListAdapter(new ArrayAdapter<String>(ThirdActivity.this,android.R.layout.simple_list_item_1,friend)); 
                        }
                    });


            }catch(Exception e){
                    Log.e("log_tag", "Error converting result "+e.toString());
            }
        }
    }.start();
}

 private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        datapassed = intent.getStringExtra("DATAPASSED");
        if(datapassed.length()>0){

            data = datapassed.split("[*]");
            dlength = data.length;

            for(int i=0;i<dlength;i++){
                if(i==dlength-1){
                    str += String.valueOf(data[i]);                 
                }else{
                    str += String.valueOf(data[i]) + ",";
                }   
            }
            Log.d("dataServices",str);
            displayNotification();
                str = "";           
        }
        }
        };

        protected void displayNotification(){
            Intent i = new Intent(this,NotificationView.class);
            i.putExtra("notification", notification);
            i.putExtra("name",str);
            Log.d("String",str);
            PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationManager mnotis =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

            Notification notis = new Notification(R.drawable.notices2,"Reminder:You have " + dlength + " new friend request",System.currentTimeMillis());
            notis.setLatestEventInfo(this,"Friend Request", str + "has sent you a friend request",pi);
            notis.vibrate = new long[]{100,250,100,500};
            mnotis.notify(0, notis);
        }
           }
4

1 回答 1

1

onCreate()此行 Log.d("dg",user);中,此行user变量始终为空,因为您在方法末尾分配了值onCreate()。将此行移动到onCreate()方法的末尾并检查空值,log.d如果值不为空,则仅调用 ..

于 2012-11-28T08:40:59.613 回答