1

我使用线程创建了一个应用程序。在线程中,我有一个发送通知的程序,但它不起作用。我哪里错了?

代码:

 NotificationManager notificationManager;   
    Notification myNotification;   
    private final String myBlog = "http://www.example.com/";  
    private static final int MY_NOTIFICATION_ID=1;  


   @Override  
    public void onCreate(Bundle savedInstanceState) {   
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.dashboard);   

 userFunctions = new UserFunctions();   

  inputUsername = (TextView) findViewById(R.id.loginUsername);   
        btnLogout = (Button) findViewById(R.id.btnLogout);   
       inputThread = (TextView) findViewById(R.id.thread_modified_text);   
       SharedPreferences userDetails = getSharedPreferences("userdetails", MODE_PRIVATE);  
        username = userDetails.getString("username", "");   
        inputUsername.setText(username);    

 currentThread = new Thread(this);   
            currentThread.start();

}

    @Override  
    public void run() {    
        try {   
                   while(username != null)  
                    {  
            Thread.sleep(5000);  
            threadHandler.sendEmptyMessage(0);         
                    }                                     
        } catch (InterruptedException e) {  
            //    
        }  
    }

private Handler threadHandler = new Handler() 
{

public void handleMessage(android.os.Message msg) {

   myNotification = new Notification(R.drawable.stat_notify_chat,   
                    "A new notificatin!",   
                    System.currentTimeMillis());    
     Context context = getApplicationContext();    
     String notificationTitle = "Notification";    
     String notificationText = "XXXX";    
     Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog));    
     PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(),     
                                   0, myIntent,    
                                    Intent.FLAG_ACTIVITY_NEW_TASK);    
      myNotification.defaults |= Notification.DEFAULT_SOUND;    
      myNotification.flags |= Notification.FLAG_AUTO_CANCEL;   
      myNotification.setLatestEventInfo(context,    
                                  notificationTitle,    
                                  notificationText,    
                                  pendingIntent);    
      notificationManager.notify(MY_NOTIFICATION_ID, myNotification);    

}
}
4

1 回答 1

0

我认为您应该在线程的 run() 方法中编写 Looper.prepare()。这对我有用。希望这会有所帮助。

于 2012-11-09T09:33:42.567 回答